From 6b9d00f549c84a0ef0f81628a956f797859af603 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:50:33 +0200 Subject: [PATCH 01/48] chore(fork): servers and the installer update from pnupu/t3code releases Co-Authored-By: Claude Opus 5.5 --- .../features/settings/environment-maintenance.test.ts | 10 +++++----- apps/server/src/cli/update.test.ts | 2 +- packages/shared/src/cliRelease.ts | 2 +- scripts/install.sh | 2 +- scripts/install.test.ts | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/apps/mobile/src/features/settings/environment-maintenance.test.ts b/apps/mobile/src/features/settings/environment-maintenance.test.ts index 86b104a45e638..92b52b1863d6c 100644 --- a/apps/mobile/src/features/settings/environment-maintenance.test.ts +++ b/apps/mobile/src/features/settings/environment-maintenance.test.ts @@ -58,7 +58,7 @@ describe("environment release checks", () => { const signal = new AbortController().signal; const feed = (...tags: ReadonlyArray) => new Response( - `tag:github.com,2008:https://github.com/pingdotgg/t3code/releases${tags + `tag:github.com,2008:https://github.com/pnupu/t3code/releases${tags .map((tag) => `tag:github.com,2008:Repository/1/${tag}`) .join("")}`, ); @@ -67,7 +67,7 @@ describe("environment release checks", () => { vi.stubGlobal( "fetch", vi.fn(async (url: string) => - url === "https://github.com/pingdotgg/t3code/releases.atom" + url === "https://github.com/pnupu/t3code/releases.atom" ? feed( "desktop-preview", "v1.0.0-preview.20260924.3", @@ -93,11 +93,11 @@ describe("environment release checks", () => { vi.stubGlobal( "fetch", vi.fn(async (url: string) => { - if (url === "https://github.com/pingdotgg/t3code/releases.atom") return feed(...nightlies); - if (url === "https://api.github.com/repos/pingdotgg/t3code/releases?per_page=100&page=1") { + if (url === "https://github.com/pnupu/t3code/releases.atom") return feed(...nightlies); + if (url === "https://api.github.com/repos/pnupu/t3code/releases?per_page=100&page=1") { return Response.json(Array.from({ length: 100 }, () => ({ tag_name: "v2.0.0" }))); } - if (url === "https://api.github.com/repos/pingdotgg/t3code/releases?per_page=100&page=2") { + if (url === "https://api.github.com/repos/pnupu/t3code/releases?per_page=100&page=2") { return Response.json([ { tag_name: "v1.0.0-preview.20260925.1", draft: true }, { tag_name: "v1.0.0-preview.20260924.3" }, diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.ts index 464dfd0523a19..88ad23c004069 100644 --- a/apps/server/src/cli/update.test.ts +++ b/apps/server/src/cli/update.test.ts @@ -57,7 +57,7 @@ it.effect("authenticates each release page until the requested channel is found" const httpClient = HttpClient.make((request) => { const url = new URL(request.url); assert.equal(url.origin, "https://api.github.com"); - assert.equal(url.pathname, "/repos/pingdotgg/t3code/releases"); + assert.equal(url.pathname, "/repos/pnupu/t3code/releases"); assert.equal(request.headers.accept, "application/vnd.github+json"); assert.equal(request.headers.authorization, "Bearer gh-token"); const page = url.searchParams.get("page") ?? ""; diff --git a/packages/shared/src/cliRelease.ts b/packages/shared/src/cliRelease.ts index 07a0c73b17947..9c670defdbafe 100644 --- a/packages/shared/src/cliRelease.ts +++ b/packages/shared/src/cliRelease.ts @@ -3,7 +3,7 @@ import * as Schema from "effect/Schema"; import { compareSemverVersions } from "./semver.ts"; -const CLI_RELEASE_REPOSITORY = "pingdotgg/t3code"; +const CLI_RELEASE_REPOSITORY = "pnupu/t3code"; export const CLI_RELEASES_PAGE_URL = `https://github.com/${CLI_RELEASE_REPOSITORY}/releases`; export const CLI_RELEASE_CHECKSUMS_FILE = "SHA256SUMS"; export const CLI_RELEASE_BASE_URL_ENV = "T3CODE_RELEASE_BASE_URL"; diff --git a/scripts/install.sh b/scripts/install.sh index bc53dcc578d92..a9ae3a7abb3a0 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -17,7 +17,7 @@ # instead of fetching the release again. set -eu -repo="pingdotgg/t3code" +repo="pnupu/t3code" base_url="${T3CODE_RELEASE_BASE_URL:-https://github.com/${repo}/releases/download}" t3_home="${T3CODE_HOME:-$HOME/.t3}" case "$t3_home" in diff --git a/scripts/install.test.ts b/scripts/install.test.ts index 4580820c73143..a29f44da7fb91 100644 --- a/scripts/install.test.ts +++ b/scripts/install.test.ts @@ -80,10 +80,10 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer chan if (failures-- > 0) return response.writeHead(504).end(); const url = new URL(request.url ?? "/", "http://fixture"); const body = - url.pathname === "/pingdotgg/t3code/releases/latest" && + url.pathname === "/pnupu/t3code/releases/latest" && request.headers.accept === "application/json" ? { tag_name: "v1.2.3" } - : url.pathname === "/repos/pingdotgg/t3code/releases" + : url.pathname === "/repos/pnupu/t3code/releases" ? { "1": nightlies, "2": [{ tag_name: `v${version}` }, { tag_name: "v1.2.3" }] }[ url.searchParams.get("page") ?? "" ] From 6f36b48ed5bd80112c8f5b5e9a44712f8b4974ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:50:33 +0200 Subject: [PATCH 02/48] ci(fork): publish self-updating releases and sync with upstream stable fork-release.yml builds Linux x64 and macOS arm64 desktop apps and the linux-x64 CLI archive on every push to main. The macOS app is re-signed with a self-signed identity so Squirrel.Mac accepts later updates. scripts/fork/sync.sh rebases main onto each new upstream stable tag. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/fork-release.yml | 340 ++++++++++++++++++++++++ FORK.md | 40 +++ scripts/fork/refresh-update-manifest.ts | 41 +++ scripts/fork/resign-macos.sh | 42 +++ scripts/fork/sign-macos-app.ts | 20 ++ scripts/fork/sync.sh | 45 ++++ 6 files changed, 528 insertions(+) create mode 100644 .github/workflows/fork-release.yml create mode 100644 FORK.md create mode 100644 scripts/fork/refresh-update-manifest.ts create mode 100755 scripts/fork/resign-macos.sh create mode 100644 scripts/fork/sign-macos-app.ts create mode 100755 scripts/fork/sync.sh diff --git a/.github/workflows/fork-release.yml b/.github/workflows/fork-release.yml new file mode 100644 index 0000000000000..2c07978b0c417 --- /dev/null +++ b/.github/workflows/fork-release.yml @@ -0,0 +1,340 @@ +# Publishes pnupu/t3code releases that the desktop app, `t3 update`, and the +# background service install from (see FORK.md). Upstream's release.yml needs +# pingdotgg infrastructure, so this file stays fork-only and never conflicts. +name: Fork release + +on: + push: + branches: [main] + workflow_dispatch: + +concurrency: + group: fork-release + cancel-in-progress: false + +permissions: + contents: read + +env: + UPSTREAM_URL: https://github.com/pingdotgg/t3code.git + +jobs: + preflight: + name: Resolve version + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + outputs: + skip: ${{ steps.meta.outputs.skip }} + version: ${{ steps.meta.outputs.version }} + tag: ${{ steps.meta.outputs.tag }} + base: ${{ steps.meta.outputs.base }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - id: meta + name: Resolve the upstream base and the next fork version + run: | + set -euo pipefail + # Fork patch = upstream patch * 1000 + fork build, so every fork release sorts + # above the previous one and stays on the stable channel. + base="" + for tag in $(git ls-remote --tags --refs "$UPSTREAM_URL" | awk '{sub("refs/tags/","",$2); print $2}' \ + | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V -r | head -20); do + git fetch --no-tags -q "$UPSTREAM_URL" "refs/tags/$tag:refs/upstream/$tag" + if git merge-base --is-ancestor "refs/upstream/$tag" HEAD; then base="$tag"; break; fi + done + test -n "$base" || { echo "main is not based on an upstream stable tag." >&2; exit 1; } + IFS=. read -r major minor patch <<< "${base#v}" + start=$((patch * 1000)) + last=$(git tag -l "v$major.$minor.*" | sed "s/^v$major\.$minor\.//" \ + | awk -v s="$start" '/^[0-9]+$/ && $1 > s && $1 < s + 1000' | sort -n | tail -1) + if [[ -n "$last" && "$(git rev-parse "v$major.$minor.$last^{commit}")" == "$(git rev-parse HEAD)" ]]; then + echo "HEAD is already released as v$major.$minor.$last." + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + version="$major.$minor.$(( ${last:-$start} + 1 ))" + { + echo "skip=false" + echo "base=$base" + echo "version=$version" + echo "tag=v$version" + } >> "$GITHUB_OUTPUT" + echo "Releasing $version on upstream $base." + + check: + name: Typecheck and fork tests + needs: [preflight] + if: needs.preflight.outputs.skip == 'false' + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + cache: true + run-install: true + + - name: Typecheck + run: vp run typecheck + + - name: Test what the fork changed + run: | + set -euo pipefail + base="${{ needs.preflight.outputs.base }}" + git fetch --no-tags -q "$UPSTREAM_URL" "refs/tags/$base:refs/upstream/$base" + tests=() + while IFS= read -r file; do + case "$file" in + *.browser.test.ts | *.browser.test.tsx) ;; + *.test.ts | *.test.tsx) [[ -f "$file" ]] && tests+=("$file") ;; + *.ts | *.tsx) + for candidate in "${file%.*}.test.ts" "${file%.*}.test.tsx"; do + [[ -f "$candidate" ]] && tests+=("$candidate") + done + ;; + esac + done < <(git diff --name-only "refs/upstream/$base" HEAD) + if [[ ${#tests[@]} -eq 0 ]]; then + echo "No fork tests to run." + exit 0 + fi + printf '%s\n' "${tests[@]}" | sort -u | xargs vp test run + + build_cli: + name: Build CLI archive (linux-x64) + needs: [preflight] + if: needs.preflight.outputs.skip == 'false' + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v6 + with: + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + # T3 Connect public identifiers, not secrets (see .env.example). + - name: Load T3 Connect public config + run: grep -E '^T3CODE_' .env.example >> "$GITHUB_ENV" + + - uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + cache: true + run-install: | + args: + - --filter=t3... + - --filter=@t3tools/web... + - --filter=@t3tools/scripts... + + - uses: dtolnay/rust-toolchain@stable + with: + targets: x86_64-unknown-linux-gnu + + - name: Align package versions + run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}" + + - name: Install native build libraries + run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config + + - name: Build web client + run: vp run --filter @t3tools/web build + + - name: Bundle server with web client + run: node apps/server/scripts/cli.ts build --verbose + + - name: Build resource monitor + run: | + cargo build --locked --release \ + --manifest-path native/resource-monitor/Cargo.toml \ + --target x86_64-unknown-linux-gnu + mkdir -p "$RUNNER_TEMP/cli-resource-monitor/linux-x64" + cp native/resource-monitor/target/x86_64-unknown-linux-gnu/release/t3-resource-monitor \ + "$RUNNER_TEMP/cli-resource-monitor/linux-x64/t3-resource-monitor" + + - name: Build CLI single-executable + run: node apps/server/scripts/cli.ts build-exe --verbose + + - name: Build CLI archive + run: | + node scripts/build-cli-archive.ts \ + --platform linux \ + --arch x64 \ + --version "${{ needs.preflight.outputs.version }}" \ + --resource-monitor-dir "$RUNNER_TEMP/cli-resource-monitor" \ + --output-dir release-cli + + - uses: actions/upload-artifact@v7 + with: + name: cli-linux-x64 + path: release-cli/* + if-no-files-found: error + + build_desktop: + name: Build ${{ matrix.label }} + needs: [preflight] + if: needs.preflight.outputs.skip == 'false' + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + include: + - label: Linux x64 + runner: ubuntu-latest + platform: linux + target: AppImage + arch: x64 + rust_target: x86_64-unknown-linux-gnu + - label: macOS arm64 + runner: macos-latest + platform: mac + target: dmg + arch: arm64 + rust_target: aarch64-apple-darwin + steps: + - uses: actions/checkout@v6 + with: + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Load T3 Connect public config + run: grep -E '^T3CODE_' .env.example >> "$GITHUB_ENV" + + - uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + cache: true + run-install: | + args: + - --filter=@t3tools/desktop... + - --filter=t3... + - --filter=@t3tools/scripts... + + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.rust_target }} + + - name: Align package versions + run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}" + + - name: Install Linux build libraries + if: matrix.platform == 'linux' + run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config imagemagick + + - name: Build desktop artifact + run: | + vp run dist:desktop:artifact \ + --platform "${{ matrix.platform }}" \ + --target "${{ matrix.target }}" \ + --arch "${{ matrix.arch }}" \ + --build-version "${{ needs.preflight.outputs.version }}" \ + --verbose + + - name: Collect release assets + run: | + set -euo pipefail + mkdir -p release-publish + shopt -s nullglob + for file in release/*.{dmg,zip,AppImage,deb,blockmap,yml}; do + [[ "$(basename "$file")" == builder-debug* ]] || cp "$file" release-publish/ + done + if [[ "${{ matrix.platform }}" == "linux" ]] && ! compgen -G "release-publish/*.deb" >/dev/null; then + echo "Linux build did not produce a .deb." >&2 + exit 1 + fi + + - name: Sign macOS app with the fork identity + if: matrix.platform == 'mac' + env: + MACOS_SIGNING_P12: ${{ secrets.MACOS_SIGNING_P12 }} + MACOS_SIGNING_PASSWORD: ${{ secrets.MACOS_SIGNING_PASSWORD }} + run: bash scripts/fork/resign-macos.sh release-publish + + - uses: actions/upload-artifact@v7 + with: + name: desktop-${{ matrix.platform }}-${{ matrix.arch }} + path: release-publish/* + if-no-files-found: error + + release: + name: Publish GitHub Release + needs: [preflight, check, build_cli, build_desktop] + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - uses: actions/download-artifact@v8 + with: + path: release-assets + merge-multiple: true + + - name: Write checksums and notes + run: | + set -euo pipefail + (cd release-assets && sha256sum t3-* > SHA256SUMS) + base="${{ needs.preflight.outputs.base }}" + git fetch --no-tags -q "$UPSTREAM_URL" "refs/tags/$base:refs/upstream/$base" + { + echo "T3 Code $base from [upstream](https://github.com/pingdotgg/t3code/releases/tag/$base) with these fork changes:" + echo + git log --no-merges --format='- %s' "refs/upstream/$base..HEAD" + } > "$RUNNER_TEMP/notes.md" + + # The tag keeps this commit reachable after the next sync rebases main. + - name: Publish release + uses: softprops/action-gh-release@v3 + with: + tag_name: ${{ needs.preflight.outputs.tag }} + target_commitish: ${{ github.sha }} + name: T3 Code ${{ needs.preflight.outputs.version }} + body_path: ${{ runner.temp }}/notes.md + prerelease: false + make_latest: true + files: release-assets/* + fail_on_unmatched_files: true + + report: + name: Report a failed release + needs: [preflight, check, build_cli, build_desktop, release] + if: failure() + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + gh issue create --label fork-sync \ + --title "Fork release failed on $(echo "$GITHUB_SHA" | cut -c1-10)" \ + --body "Machines stay on the last release. Run: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" diff --git a/FORK.md b/FORK.md new file mode 100644 index 0000000000000..425a3a18bc3b5 --- /dev/null +++ b/FORK.md @@ -0,0 +1,40 @@ +# pnupu/t3code + +Upstream T3 Code stable releases plus a few fork commits. `main` is always an upstream +stable tag with the fork commits rebased on top, so it is force-pushed on every sync. + +## How a release reaches the machines + +1. `scripts/fork/sync.sh` rebases `main` onto the newest upstream stable tag and pushes. + A T3 Code scheduled task on serveri runs it and resolves conflicts. +2. Every push to `main` runs `.github/workflows/fork-release.yml`: typecheck, the tests + beside fork changes, a Linux x64 desktop build and CLI archive, and a macOS arm64 build + re-signed with the fork's self-signed identity. It publishes `vX.Y.(Z*1000+n)`, so + upstream `v0.1.4` becomes `0.1.4001`, `0.1.4002`, and so on. +3. The desktop app offers the release; its update button moves every connected server. + +A conflict or a failed release opens a `fork-sync` issue and publishes nothing, so +machines stay on the last release. + +## Installing on a new machine + +Linux server (runs the background service): + +```sh +curl -fsSL https://raw.githubusercontent.com/pnupu/t3code/main/scripts/install.sh | sh +``` + +Mac: download `T3-Code--arm64.zip` from the latest release with `curl` and unzip +it into `/Applications`. A browser download is quarantined and needs Open Anyway in +System Settings → Privacy & Security once. Later updates come through the app. + +Update from the fork's desktop app or the web UI a fork server serves. app.t3.codes and +the iPhone app look for upstream versions, which fork servers cannot install. + +## Adding a fork feature + +- One commit per feature, with its tests beside the code, so the release checks catch a + sync that broke it. +- Put the code in new files and keep edits to busy upstream files to a line or two. +- No database migrations: upstream numbers them sequentially. +- Offer the feature upstream too; once it lands there, drop the commit. diff --git a/scripts/fork/refresh-update-manifest.ts b/scripts/fork/refresh-update-manifest.ts new file mode 100644 index 0000000000000..7f5ce8f2ec2cf --- /dev/null +++ b/scripts/fork/refresh-update-manifest.ts @@ -0,0 +1,41 @@ +// @effect-diagnostics nodeBuiltinImport:off globalConsole:off - a synchronous release-asset rewrite run once in CI. +import { createHash } from "node:crypto"; +import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +// Rewrites sha512/size in electron-builder's latest*.yml after files were re-packed. +// Blockmaps of re-packed files are gone, so their blockMapSize lines are dropped too. +const dir = process.argv[2]; +if (!dir) throw new Error("usage: refresh-update-manifest.ts "); + +const digest = (file: string) => + createHash("sha512").update(readFileSync(join(dir, file))).digest("base64"); + +for (const manifest of readdirSync(dir).filter((name) => /^latest.*\.yml$/.test(name))) { + let current: string | undefined; + const lines = readFileSync(join(dir, manifest), "utf8").split("\n"); + const out: string[] = []; + for (const line of lines) { + const entry = /^(\s*-?\s*)(url|path): (.+)$/.exec(line); + if (entry) current = entry[3]!.trim(); + const field = /^(\s*)(sha512|size|blockMapSize): /.exec(line); + if (field && current && existsInDir(current)) { + if (field[2] === "blockMapSize") continue; + out.push( + `${field[1]}${field[2]}: ${field[2] === "sha512" ? digest(current) : statSync(join(dir, current)).size}`, + ); + continue; + } + out.push(line); + } + writeFileSync(join(dir, manifest), out.join("\n")); + console.log(`refreshed ${manifest}`); +} + +function existsInDir(file: string): boolean { + try { + return statSync(join(dir!, file)).isFile(); + } catch { + return false; + } +} diff --git a/scripts/fork/resign-macos.sh b/scripts/fork/resign-macos.sh new file mode 100755 index 0000000000000..e447f1e2b7c0b --- /dev/null +++ b/scripts/fork/resign-macos.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Re-signs the macOS build with the fork's self-signed identity. Squirrel.Mac installs an +# update only when it satisfies the running app's designated requirement, which an +# unsigned (ad-hoc) build never does. No hardened runtime: there is no notarization. +set -euo pipefail + +release_dir=$(cd "$1" && pwd) +: "${MACOS_SIGNING_P12:?}" "${MACOS_SIGNING_PASSWORD:?}" + +work=$(mktemp -d) +keychain="$work/fork-signing.keychain-db" +keychain_password=$(uuidgen) +security create-keychain -p "$keychain_password" "$keychain" +security set-keychain-settings -lut 21600 "$keychain" +security unlock-keychain -p "$keychain_password" "$keychain" +printf '%s' "$MACOS_SIGNING_P12" | base64 --decode > "$work/signing.p12" +security import "$work/signing.p12" -k "$keychain" -P "$MACOS_SIGNING_PASSWORD" -T /usr/bin/codesign +security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$keychain_password" "$keychain" >/dev/null +# shellcheck disable=SC2046 +security list-keychains -d user -s "$keychain" $(security list-keychains -d user | tr -d '"') +identity=$(security find-identity -p codesigning "$keychain" | awk '$1 ~ /^[0-9]+\)$/ { print $2; exit }') +test -n "$identity" || { echo "No signing identity in MACOS_SIGNING_P12." >&2; exit 1; } + +zip=$(ls "$release_dir"/*.zip) +dmg=$(ls "$release_dir"/*.dmg) +ditto -x -k "$zip" "$work/app" +app=$(ls -d "$work"/app/*.app) + +node scripts/fork/sign-macos-app.ts "$app" "$identity" "$keychain" +codesign --verify --deep --strict --verbose=2 "$app" +codesign -d -r- "$app" 2>&1 | tee "$work/requirement.txt" +grep -q "certificate leaf" "$work/requirement.txt" + +rm -f "$zip" "$zip.blockmap" "$dmg" "$dmg.blockmap" +ditto -c -k --sequesterRsrc --keepParent "$app" "$zip" +mkdir "$work/dmg" +ditto "$app" "$work/dmg/$(basename "$app")" +ln -s /Applications "$work/dmg/Applications" +hdiutil create -volname "$(basename "$app" .app)" -srcfolder "$work/dmg" -ov -format UDZO "$dmg" + +node scripts/fork/refresh-update-manifest.ts "$release_dir" +security delete-keychain "$keychain" diff --git a/scripts/fork/sign-macos-app.ts b/scripts/fork/sign-macos-app.ts new file mode 100644 index 0000000000000..82759711719be --- /dev/null +++ b/scripts/fork/sign-macos-app.ts @@ -0,0 +1,20 @@ +import { sign } from "@electron/osx-sign"; + +const [app, identity, keychain] = process.argv.slice(2); +if (!app || !identity || !keychain) { + throw new Error("usage: sign-macos-app.ts "); +} + +await sign({ + app, + identity, + keychain, + platform: "darwin", + // Self-signed and never notarized: skip Developer ID checks, Apple's timestamp server, + // the hardened runtime, and the entitlements only it needs. + identityValidation: false, + preAutoEntitlements: false, + preEmbedProvisioningProfile: false, + batchCodesignCalls: true, + optionsForFile: () => ({ hardenedRuntime: false, timestamp: "none" }), +}); diff --git a/scripts/fork/sync.sh b/scripts/fork/sync.sh new file mode 100755 index 0000000000000..0189f93dc6e16 --- /dev/null +++ b/scripts/fork/sync.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Rebases the fork's commits onto the newest upstream stable release and pushes main; +# the push publishes a release (fork-release.yml). Runs from a clone of pnupu/t3code +# with push access. Exit 0: synced or nothing to do. Exit 3: the rebase stopped on a +# conflict and is left in progress to resolve, then `git rebase --continue` and push. +set -euo pipefail + +upstream=https://github.com/pingdotgg/t3code.git +repo=pnupu/t3code + +if [[ -d "$(git rev-parse --git-path rebase-merge)" || -d "$(git rev-parse --git-path rebase-apply)" ]]; then + echo "A rebase is already in progress; resolve it first." >&2 + exit 3 +fi + +git fetch -q origin main --tags +git checkout -q -B main origin/main +before=$(git rev-parse HEAD) + +tags=$(git ls-remote --tags --refs "$upstream" | awk '{sub("refs/tags/","",$2); print $2}' \ + | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V -r | head -20) +latest=$(head -1 <<< "$tags") +base="" +for tag in $tags; do + git fetch --no-tags -q "$upstream" "refs/tags/$tag:refs/upstream/$tag" + if git merge-base --is-ancestor "refs/upstream/$tag" HEAD; then base="$tag"; break; fi +done +test -n "$base" || { echo "main is not based on an upstream stable tag." >&2; exit 1; } +if [[ "$base" == "$latest" ]]; then + echo "Already on $latest." + exit 0 +fi + +echo "Rebasing $(git rev-list --count "refs/upstream/$base..HEAD") fork commits from $base onto $latest." +if ! git rebase --onto "refs/upstream/$latest" "refs/upstream/$base"; then + title="Upstream $latest does not apply cleanly" + if [[ -z "$(gh issue list -R "$repo" --label fork-sync --state open --search "\"$title\" in:title" --json number --jq '.[].number')" ]]; then + gh issue create -R "$repo" --label fork-sync --title "$title" \ + --body "Rebasing the fork commits from $base onto $latest stopped on a conflict. Machines stay on the last release until main is pushed." + fi + exit 3 +fi + +git push -q --force-with-lease="main:$before" origin main +echo "Pushed main on $latest; fork-release.yml publishes it." From d9d9dbdfada1fedeeb19a6159c1137ecf38d2945 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:01:53 +0200 Subject: [PATCH 03/48] fix(server): worktree tasks can run in another project or linked environment (#23) delegate_task with isolation "worktree" refused target.projectId of another local project and refused every task in a linked environment. Now: - delegated_task.request takes an optional projectId. The child thread is created in that project, so launch preparation makes its worktree there, and the provider enablement check uses that project. - A local task in another project needs isolation "worktree" and branches from that project's checkout HEAD. A shared child would inherit this thread's checkout, so that case is still refused. Same-project tasks keep the parent checkout's commit. - A task in a linked environment launches there with a worktree from HEAD, which resolves in that project's checkout, so no commit that only this side has is sent. Co-authored-by: Claude Opus 5.5 --- .../src/mcp/OrchestratorMcpService.test.ts | 135 ++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 29 ++-- .../src/orchestration-v2/Orchestrator.ts | 1 + .../ThreadManagementService.ts | 2 +- apps/server/src/peer/RemoteDelegation.test.ts | 26 +++- apps/server/src/peer/RemoteDelegation.ts | 19 +-- packages/contracts/src/orchestrationV2.ts | 2 + 7 files changed, 190 insertions(+), 24 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index f49bcc7c9412f..3427c78813061 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -2667,6 +2667,141 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + const otherProjectId = ProjectId.make("project:mcp-providers-other"); + it.effect.each([ + { + isolation: "worktree" as const, + outcome: "running", + dispatched: [ + { + projectId: otherProjectId, + workspaceStrategy: { + type: "worktree", + baseRef: "head-of:/repo/other", + startFromOrigin: false, + }, + }, + ], + }, + { isolation: "shared" as const, outcome: "invalid_request", dispatched: [] }, + ])( + "a task in another project here with $isolation isolation", + ({ isolation, outcome, dispatched: expected }) => + Effect.gen(function* () { + const dispatched = yield* Ref.make>([]); + const task = { + id: taskId, + threadId: parentThreadId, + runId: parentRunId, + parentNodeId, + origin: "app_owned", + createdBy: "agent", + driver: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, + providerThreadId: null, + childThreadId, + nativeTaskRef: null, + prompt: "Fix the other repository.", + title: null, + model: "gpt-5.4", + status: "running", + result: null, + startedAt: null, + completedAt: null, + }; + let delegated = false; + const layerDependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + getThreadRecords: (threadId) => + Effect.succeed( + threadId === parentThreadId + ? parentProjection(delegated ? [task] : []) + : childProjection, + ), + dispatch: (command) => + Ref.update(dispatched, (commands) => [...commands, command]).pipe( + Effect.andThen( + Effect.sync(() => { + delegated = true; + }), + ), + Effect.as({ + sequence: 1, + storedEvents: [ + { + sequence: 1, + commandId: null, + event: { type: "subagent.updated", payload: task }, + }, + ], + } as never), + ), + }), + providerRegistryLayer([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + adapterRegistryLayer([codexInstanceId]), + Layer.mock(ProjectService.ProjectService)({ + getById: (id) => + Effect.succeedSome({ + id, + title: id, + workspaceRoot: id === otherProjectId ? "/repo/other" : "/repo/parent", + } as never), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ServerSettings.layerTest(), + ); + + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const result = yield* service + .delegateTask(scope, { + task: "Fix the other repository.", + target: { projectId: otherProjectId }, + isolation, + mode: "async", + clientRequestId: `delegate-other-project-${isolation}`, + }) + .pipe( + Effect.map((task): string => task.status), + Effect.catch((error) => Effect.succeed(error.code)), + ); + assert.equal(result, outcome); + const commands = (yield* Ref.get(dispatched)) as ReadonlyArray<{ + readonly projectId?: ProjectId; + readonly workspaceStrategy?: unknown; + }>; + assert.deepEqual( + commands.map(({ projectId, workspaceStrategy }) => ({ projectId, workspaceStrategy })), + expected, + ); + }).pipe( + Effect.provide( + OrchestratorMcpService.layer.pipe( + Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), + Layer.provide( + Layer.mock(GitVcsDriver.GitVcsDriver)({ + resolveCommit: ({ cwd }) => + Effect.succeed({ commitSha: `head-of:${cwd}` } as never), + }), + ), + Layer.provide(layerDependencies), + ), + ), + ); + }), + ); + it.effect( "retrying an accepted driver-only delegation replays even after the project disables every candidate", () => diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 5c5c9636406e1..7410fec868a63 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2653,13 +2653,13 @@ const make = Effect.gen(function* () { : readTask(scope, taskId, false, true); } const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task"); - if ( - input.target?.projectId !== undefined && - input.target.projectId !== parent.thread.projectId - ) { + const projectId = input.target?.projectId ?? parent.thread.projectId; + const otherProject = projectId !== parent.thread.projectId; + // A shared child would inherit this thread's checkout, which is not in that project. + if (otherProject && input.isolation !== "worktree") { return yield* failure( "invalid_request", - "A local task runs in this thread's project. Omit target.projectId, or pass target.environmentId to run it in that environment's project.", + 'A local task in another project needs isolation "worktree". Omit target.projectId to share this thread\'s checkout.', ); } const parentRun = parent.runs @@ -2684,7 +2684,7 @@ const make = Effect.gen(function* () { }); const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId); const target = yield* resolveTargetRechecking({ - parent, + parent: { thread: { ...parent.thread, projectId } }, target: input.target, providers, skipProjectEnablementFilter: isRetryOfAcceptedDelegation, @@ -2700,21 +2700,29 @@ const make = Effect.gen(function* () { ); let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) { - const project = yield* requireProject(parent.thread.projectId); + const project = yield* requireProject(projectId); + // Another project branches from its own checkout: it does not have this thread's commits. const base = yield* gitDriver .resolveCommit({ - cwd: parent.thread.worktreePath ?? project.workspaceRoot, + cwd: otherProject + ? project.workspaceRoot + : (parent.thread.worktreePath ?? project.workspaceRoot), revision: "HEAD", }) .pipe( Effect.mapError(() => - failure("invalid_request", "Unable to resolve the parent checkout commit."), + failure( + "invalid_request", + otherProject + ? `Unable to resolve the checkout commit of project "${project.title}" (${project.workspaceRoot}).` + : "Unable to resolve the parent checkout commit.", + ), ), ); // Launch preparation creates the worktree from the project root, so a // parent checkout in another repository (such as a Git folder inside // Scratch) would hand it a commit it cannot find. - if (parent.thread.worktreePath !== null) { + if (!otherProject && parent.thread.worktreePath !== null) { yield* gitDriver .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha }) .pipe( @@ -2745,6 +2753,7 @@ const make = Effect.gen(function* () { modelSelection: target.modelSelection, runtimeMode, interactionMode, + ...(otherProject ? { projectId } : {}), ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), // Async delegations wake the parent on every child terminal; wait // delegations deliver through the blocking tool call until `awaitTask` diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 2805935d38890..6ace86cd8bade 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -9461,6 +9461,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), runtimeMode: command.runtimeMode, interactionMode: command.interactionMode, + ...(command.projectId === undefined ? {} : { projectId: command.projectId }), ...(command.workspaceStrategy === undefined ? {} : { branch: null, worktreePath: null }), }; const task: OrchestrationV2Subagent = { diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 611d9a3244f24..b71d5eb96438e 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -781,7 +781,7 @@ const make = Effect.gen(function* () { return orchestrator.getThreadRecords(command.parentThreadId, []).pipe( Effect.flatMap((parent) => assertProviderInstanceEnabled({ - projectId: parent.thread.projectId, + projectId: command.projectId ?? parent.thread.projectId, commandId: command.commandId, instanceId: command.modelSelection.instanceId, }), diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 90c6eb83baae5..76284ecb1129a 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -96,6 +96,11 @@ interface BoxThread { readonly delegatedFrom: Ref.Ref; /** The model and modes it was launched with. */ readonly launchedWith: Ref.Ref; + /** The project and checkout it was launched in. */ + readonly launchedIn: Ref.Ref | null>; /** The first message the thread there was launched with. */ readonly message: Ref.Ref; readonly status: Ref.Ref; @@ -151,6 +156,10 @@ const makeBoxThread = Effect.gen(function* () { ), delegatedFrom: yield* Ref.make(null), launchedWith: yield* Ref.make(null), + launchedIn: yield* Ref.make | null>(null), message: yield* Ref.make(null), status: yield* Ref.make("running"), reply: yield* Ref.make("Working…"), @@ -501,6 +510,7 @@ const boxToolkitLayer = (thread: BoxThread) => { ), }); const layerBoxLaunches = Layer.mock(ThreadLaunch.ThreadLaunchService)({ + checkWorktreeBase: () => Effect.void, launch: (input) => Ref.get(thread.runless).pipe( Effect.flatMap((runless) => @@ -508,6 +518,12 @@ const boxToolkitLayer = (thread: BoxThread) => { Effect.andThen(Ref.set(thread.linkOrigin, input.linkOrigin ?? null)), Effect.andThen(Ref.set(thread.delegatedFrom, input.delegatedFrom ?? null)), Effect.andThen(Ref.set(thread.message, input.initialMessage?.text ?? null)), + Effect.andThen( + Ref.set(thread.launchedIn, { + projectId: input.projectId, + workspaceStrategy: input.workspaceStrategy, + }), + ), Effect.andThen( Ref.set(thread.launchedWith, { modelSelection: input.modelSelection, @@ -1284,7 +1300,7 @@ it.effect("a task naming another driver there never runs its model on the parent ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); -it.effect("refuses worktree isolation for a task there before launching anything", () => +it.effect("launches a worktree task there from that project's own checkout", () => Effect.scoped( Effect.gen(function* () { const thread = yield* makeBoxThread; @@ -1302,9 +1318,11 @@ it.effect("refuses worktree isolation for a task there before launching anything target: { environmentId: box.environmentId }, isolation: "worktree", }); - expect(result.isError).toBe(true); - expect(JSON.stringify(result.content)).toContain("isolation"); - expect(yield* Ref.get(thread.launched)).toBeNull(); + expect(result.isError, JSON.stringify(result.content)).toBe(false); + expect(yield* Ref.get(thread.launchedIn)).toEqual({ + projectId: boxProject, + workspaceStrategy: { type: "worktree", baseRef: "HEAD", startFromOrigin: false }, + }); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 8fcd240e70577..b9bc94a28498e 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -288,15 +288,6 @@ const make = Effect.gen(function* () { } const parentNodeId = parentRun.rootNodeId; const { target } = input; - // A worktree there would branch from a commit this checkout has and the - // other may not, so a remote task runs in that project's checkout. - if (input.isolation === "worktree") { - return yield* new OrchestratorMcpFailure({ - code: "invalid_request", - message: - 'A task in a linked environment runs in that project\'s checkout; isolation "worktree" is not supported there. Omit isolation, or use t3_thread_launch with environmentId and a worktree workspaceStrategy.', - }); - } // The provider and model inherit as they do for a task here. Another // provider there has no model to inherit, so the caller names one. const inherited = parent.thread.modelSelection; @@ -354,6 +345,16 @@ const make = Effect.gen(function* () { modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) }, ...(runtimeMode === undefined ? {} : { runtimeMode }), ...(interactionMode === undefined ? {} : { interactionMode }), + // HEAD resolves in that project's checkout, so no commit only this side has goes there. + ...(input.isolation === "worktree" + ? { + workspaceStrategy: { + type: "worktree" as const, + baseRef: "HEAD", + startFromOrigin: false, + }, + } + : {}), message: task, clientRequestId: `delegate:${scope.thread.threadId}:${key}`, // The thread there shows it is this thread's subagent, with a way back. diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 38d2e98ef72c2..33a6e121b645d 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3535,6 +3535,8 @@ export const OrchestrationV2Command = Schema.Union([ modelSelection: ModelSelection, runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, + // Defaults to the parent's project. + projectId: Schema.optional(ProjectId), workspaceStrategy: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy), // Defaults to settled_only; fire-and-forget wakes require always. completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])), From 01fa891a55dec9747282a8b62d0c89f71bc3f13b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:29:27 +0200 Subject: [PATCH 04/48] feat(web): fork servers show Fork environment identification (#25) A server built by the fork looked the same as an upstream build. Fork releases are numbered X.Y.(Z*1000+n), so a primary server version with a plain patch number of 1000 or more now gives the stage label "Fork". The default artwork mode shows a new git-branch artwork in the sidebar header, the pill mode shows a "Fork" pill, Settings > Appearance lists "Fork artwork", and the tab title reads "T3 Code (Fork)". The settings contract does not change: "artwork" follows the stage, so upstream clients still decode the setting. The artwork has its own --stage-fork-* tokens and keeps one palette in every theme. Co-authored-by: Claude Fable 5.2 --- apps/web/src/branding.logic.test.ts | 41 ++++++ apps/web/src/branding.logic.ts | 5 + apps/web/src/components/ForkBranchArt.tsx | 138 ++++++++++++++++++ .../components/SidebarStageBackdrop.test.ts | 32 ++++ .../src/components/SidebarStageBackdrop.tsx | 9 +- .../settings/AppearanceSettingsPanel.tsx | 11 +- apps/web/src/index.css | 10 ++ 7 files changed, 243 insertions(+), 3 deletions(-) create mode 100644 apps/web/src/branding.logic.test.ts create mode 100644 apps/web/src/components/ForkBranchArt.tsx create mode 100644 apps/web/src/components/SidebarStageBackdrop.test.ts diff --git a/apps/web/src/branding.logic.test.ts b/apps/web/src/branding.logic.test.ts new file mode 100644 index 0000000000000..7278f1709f430 --- /dev/null +++ b/apps/web/src/branding.logic.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + resolveServerBackedAppDisplayName, + resolveServerBackedAppStageLabel, +} from "./branding.logic"; + +describe("resolveServerBackedAppStageLabel", () => { + it.each([ + ["0.1.9001", "Fork"], + ["0.1.1000", "Fork"], + ["12.3.14027", "Fork"], + ["0.1.9", "Beta"], + ["0.1.999", "Beta"], + ["0.1.9001-rc.1", "Beta"], + ["0.1.10-nightly.20261118.1", "Nightly"], + ["0.1.9001-nightly.20261118.1", "Nightly"], + [null, "Beta"], + ])("labels server version %s as %s", (primaryServerVersion, expected) => { + expect( + resolveServerBackedAppStageLabel({ primaryServerVersion, fallbackStageLabel: "Beta" }), + ).toBe(expected); + }); +}); + +describe("resolveServerBackedAppDisplayName", () => { + it.each([ + ["0.1.9001", "T3 Code (Fork)"], + ["0.1.10-nightly.20261118.1", "T3 Code (Nightly)"], + ["0.1.9", "T3 Code (Beta)"], + ])("names the app for server version %s as %s", (primaryServerVersion, expected) => { + expect( + resolveServerBackedAppDisplayName({ + baseName: "T3 Code", + fallbackDisplayName: "T3 Code (Beta)", + fallbackStageLabel: "Beta", + primaryServerVersion, + }), + ).toBe(expected); + }); +}); diff --git a/apps/web/src/branding.logic.ts b/apps/web/src/branding.logic.ts index f53103d904ad0..30ec9ec92c9a6 100644 --- a/apps/web/src/branding.logic.ts +++ b/apps/web/src/branding.logic.ts @@ -1,4 +1,6 @@ const NIGHTLY_SERVER_VERSION_PATTERN = /^[^-+]+-(?:nightly|preview)\.\d{8}\.\d+$/; +// Fork releases are numbered X.Y.(Z*1000+n) (FORK.md), so a plain patch of 1000 or more is a fork build. +const FORK_SERVER_VERSION_PATTERN = /^\d+\.\d+\.[1-9]\d{3,}$/; export function formatAppDisplayName(input: { readonly baseName: string; @@ -30,6 +32,9 @@ export function resolveServerBackedAppStageLabel(input: { readonly primaryServerVersion: string | null | undefined; readonly fallbackStageLabel: string; }): string { + if (input.primaryServerVersion && FORK_SERVER_VERSION_PATTERN.test(input.primaryServerVersion)) { + return "Fork"; + } return input.primaryServerVersion && NIGHTLY_SERVER_VERSION_PATTERN.test(input.primaryServerVersion) ? "Nightly" diff --git a/apps/web/src/components/ForkBranchArt.tsx b/apps/web/src/components/ForkBranchArt.tsx new file mode 100644 index 0000000000000..95734a996562f --- /dev/null +++ b/apps/web/src/components/ForkBranchArt.tsx @@ -0,0 +1,138 @@ +import { useId } from "react"; + +const FORK_COMMITS: ReadonlyArray<{ cx: number; cy: number }> = [ + { cx: 28, cy: 52 }, + { cx: 68, cy: 52 }, + { cx: 112, cy: 52 }, + { cx: 176, cy: 52 }, + { cx: 252, cy: 52 }, + { cx: 340, cy: 52 }, + { cx: 164, cy: 26 }, + { cx: 186, cy: 26 }, + { cx: 230, cy: 26 }, + { cx: 220, cy: 9 }, + { cx: 310, cy: 74 }, + { cx: 362, cy: 74 }, +]; + +const FORK_BRANCH_HEADS: ReadonlyArray<{ cx: number; cy: number; labelWidth: number }> = [ + { cx: 262, cy: 26, labelWidth: 22 }, + { cx: 244, cy: 9, labelWidth: 16 }, +]; + +export function ForkBranchArt({ compact = false }: { compact?: boolean }) { + const idPrefix = useId().replaceAll(":", ""); + const paperId = `${idPrefix}-stage-fork-paper`; + const glowId = `${idPrefix}-stage-fork-glow`; + const emberGlowId = `${idPrefix}-stage-fork-glow-ember`; + const dotsId = `${idPrefix}-stage-fork-dots`; + const glowsId = `${idPrefix}-stage-fork-glows`; + const graphId = `${idPrefix}-stage-fork-graph`; + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {FORK_COMMITS.map((commit) => ( + + ))} + + + {FORK_BRANCH_HEADS.map((head) => ( + + + + + ))} + + + + + + + + + + ); +} diff --git a/apps/web/src/components/SidebarStageBackdrop.test.ts b/apps/web/src/components/SidebarStageBackdrop.test.ts new file mode 100644 index 0000000000000..7be9d2e0be93e --- /dev/null +++ b/apps/web/src/components/SidebarStageBackdrop.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + resolveEnvironmentIdentificationPillLabel, + resolveSidebarStageBackdropVariant, +} from "./SidebarStageBackdrop"; + +describe("resolveSidebarStageBackdropVariant", () => { + it.each([ + ["Fork", "artwork", "fork"], + ["Fork", "nightly-artwork", "nightly"], + ["Fork", "dev-artwork", "dev"], + ["Fork", "pill", null], + ["Fork", "none", null], + ["Nightly", "artwork", "nightly"], + ["Dev", "artwork", "dev"], + ["Latest", "artwork", null], + ] as const)("shows %s in %s mode as %s", (stageLabel, mode, expected) => { + expect(resolveSidebarStageBackdropVariant(stageLabel, mode)).toBe(expected); + }); +}); + +describe("resolveEnvironmentIdentificationPillLabel", () => { + it.each([ + ["Fork", "Fork"], + ["Nightly", "Nightly"], + ["Dev", "Dev"], + ["Latest", null], + ])("labels the %s pill as %s", (stageLabel, expected) => { + expect(resolveEnvironmentIdentificationPillLabel(stageLabel)).toBe(expected); + }); +}); diff --git a/apps/web/src/components/SidebarStageBackdrop.tsx b/apps/web/src/components/SidebarStageBackdrop.tsx index b5c9d34ac6670..c9ddff06bbd2b 100644 --- a/apps/web/src/components/SidebarStageBackdrop.tsx +++ b/apps/web/src/components/SidebarStageBackdrop.tsx @@ -5,9 +5,10 @@ import { useId } from "react"; import { APP_STAGE_LABEL } from "../branding"; import { resolveServerBackedAppStageLabel } from "../branding.logic"; import { primaryServerConfigAtom } from "../state/server"; +import { ForkBranchArt } from "./ForkBranchArt"; -export type SidebarStageBackdropVariant = "nightly" | "dev"; -export type EnvironmentIdentificationPillLabel = "Dev" | "Nightly"; +export type SidebarStageBackdropVariant = "nightly" | "dev" | "fork"; +export type EnvironmentIdentificationPillLabel = "Dev" | "Nightly" | "Fork"; const STAGE_BACKDROP_VIEW_BOX = "0 0 8192 96"; @@ -21,6 +22,7 @@ export function resolveSidebarStageBackdropVariant( const normalized = stageLabel.trim().toLowerCase(); if (normalized === "nightly") return "nightly"; if (normalized === "dev") return "dev"; + if (normalized === "fork") return "fork"; return null; } @@ -30,6 +32,7 @@ export function resolveEnvironmentIdentificationPillLabel( const normalized = stageLabel.trim().toLowerCase(); if (normalized === "dev") return "Dev"; if (normalized === "nightly") return "Nightly"; + if (normalized === "fork") return "Fork"; return null; } @@ -61,10 +64,12 @@ export function SidebarStageBackdrop({ variant }: { variant: SidebarStageBackdro } function StageBackdropArt({ variant }: { variant: SidebarStageBackdropVariant }) { + if (variant === "fork") return ; return variant === "nightly" ? : ; } export function StageBackdropButtonArt({ variant }: { variant: SidebarStageBackdropVariant }) { + if (variant === "fork") return ; return variant === "nightly" ? : ; } diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index 00783b085d609..38000cc04bd45 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -66,6 +66,15 @@ function environmentIdentificationOptions( ["none", "None"], ]; } + if (stageVariant === "fork") { + return [ + ["artwork", "Fork artwork"], + ["nightly-artwork", "Nightly artwork"], + ["dev-artwork", "Dev artwork"], + ["pill", "Version pill"], + ["none", "None"], + ]; + } return [ ["artwork", "None"], ["nightly-artwork", "Nightly artwork"], @@ -119,7 +128,7 @@ export function AppearanceSettingsPanel() { ? "Only built-in themes show artwork, so this theme shows the version pill." : "Only built-in themes show artwork." : environmentStageVariant - ? "Choose how Dev and Nightly environments are identified." + ? "Choose how Dev, Nightly, and Fork environments are identified." : "Show Dev or Nightly artwork in the sidebar header."; const glassOpacityRatio = (settings.glassOpacity - MIN_GLASS_OPACITY) / (MAX_GLASS_OPACITY - MIN_GLASS_OPACITY); diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 771c714b1ff8a..a7e5c7d8c09d7 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -703,11 +703,21 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil --stage-night-glow-highlight: oklch(0.553749 0.176543 271.958); --stage-night-glow-secondary: oklch(0.345571 0.117466 273.568); --stage-night-sparkle: oklch(0.880867 0.057747 269.011); + /* Fork artwork keeps one palette in every theme, so a fork server always reads the same. */ + --stage-fork-top: oklch(0.8 0.125 72); + --stage-fork-mid: oklch(0.64 0.16 48); + --stage-fork-bottom: oklch(0.42 0.12 32); + --stage-fork-highlight: oklch(0.965 0.03 85); + --stage-fork-secondary: oklch(0.83 0.12 68); + --stage-fork-line: oklch(0.975 0.02 80); @variant dark { --stage-art-top: oklch(0.581473 0.149124 256.9); --stage-art-mid: oklch(0.456509 0.159377 261.945); --stage-art-bottom: oklch(0.291327 0.136578 267.649); + --stage-fork-top: oklch(0.6 0.125 58); + --stage-fork-mid: oklch(0.44 0.105 40); + --stage-fork-bottom: oklch(0.27 0.06 30); } } From cc928574d8253f67ff3a2acdc1d992dac31dfa15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:01:51 +0200 Subject: [PATCH 05/48] fix(ci): fork releases build on Ubuntu 24.04 to keep glibc at 2.39 (#26) * fix(ci): fork releases build on Ubuntu 24.04 to keep glibc at 2.39 ubuntu-latest moved past glibc 2.39, so node-pty compiled against 2.42 and the Linux desktop build's glibc check stopped the release. The CLI archive had the same problem without a check, and would not load on Ubuntu 24.04 servers. Upstream's release jobs also pin Ubuntu 24.04. Co-Authored-By: Claude Opus 5.5 * fix(ci): note why fork Linux release jobs pin Ubuntu 24.04 Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/fork-release.yml | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/workflows/fork-release.yml b/.github/workflows/fork-release.yml index 2c07978b0c417..8e09f58ef613c 100644 --- a/.github/workflows/fork-release.yml +++ b/.github/workflows/fork-release.yml @@ -21,7 +21,7 @@ env: jobs: preflight: name: Resolve version - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 10 permissions: contents: write @@ -74,7 +74,7 @@ jobs: name: Typecheck and fork tests needs: [preflight] if: needs.preflight.outputs.skip == 'false' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 45 steps: - uses: actions/checkout@v6 @@ -121,7 +121,7 @@ jobs: name: Build CLI archive (linux-x64) needs: [preflight] if: needs.preflight.outputs.skip == 'false' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 45 steps: - uses: actions/checkout@v6 @@ -199,7 +199,8 @@ jobs: matrix: include: - label: Linux x64 - runner: ubuntu-latest + # Ubuntu 24.04 keeps glibc at GLIBC_BUILD_CEILING (scripts/linux-glibc.ts); do not use ubuntu-latest. + runner: ubuntu-24.04 platform: linux target: AppImage arch: x64 @@ -280,7 +281,7 @@ jobs: release: name: Publish GitHub Release needs: [preflight, check, build_cli, build_desktop] - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: contents: write @@ -327,7 +328,7 @@ jobs: name: Report a failed release needs: [preflight, check, build_cli, build_desktop, release] if: failure() - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 permissions: issues: write steps: From daaf022220198eee0bdc40877b60f9086b270a1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:38:32 +0200 Subject: [PATCH 06/48] fix(web): Enter on a reasoning level closes the model picker Enter on a model moves focus to the reasoning column, but Enter on a level only set the level and left the picker open. Enter on a level now picks it and closes the picker. The composer's close behavior then focuses the message input. Space and clicks still keep the picker open, and Enter on a model still moves to its levels. Co-Authored-By: Claude Opus 5.5 --- .../chat/ProviderModelPicker.browser.test.tsx | 11 ++++++++++- .../components/chat/ProviderModelPicker.tsx | 18 ++++++++++++++++-- docs/user/keybindings.md | 3 ++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx index bf196f52542c2..a92df61e6ea47 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx @@ -95,7 +95,7 @@ it("keeps each registry image when adding a model from another ACP agent", async await vi.waitFor(() => expect(imageWidths()).toEqual([11, 17])); }); -it("keeps a docked picker open after a pick and hands focus to that model's effort", async () => { +it("keeps a docked picker open after a pick, hands focus to that model's effort and closes on Enter there", async () => { const instanceId = ProviderInstanceId.make("codex"); const entries = deriveProviderInstanceEntries([ { @@ -128,6 +128,7 @@ it("keeps a docked picker open after a pick and hands focus to that model's effo second: ["Medium"], plain: [], }; + const picked: string[] = []; function Picker() { const [model, setModel] = useState("original"); @@ -149,6 +150,7 @@ it("keeps a docked picker open after a pick and hands focus to that model's effo aria-checked={index === all.length - 1} data-effort-row data-effort-level + onClick={() => picked.push(level)} > {level} @@ -174,6 +176,13 @@ it("keeps a docked picker open after a pick and hands focus to that model's effo await expect.element(page.getByRole("radio", { name: "Medium" })).toHaveFocus(); await userEvent.keyboard("{Escape}"); await expect.element(search).not.toBeInTheDocument(); + + await screen.getByRole("button", { name: "Choose model" }).click(); + await userEvent.keyboard("{ArrowRight}"); + await expect.element(page.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("{Enter}"); + await expect.element(search).not.toBeInTheDocument(); + expect(picked).toEqual(["Medium"]); }); it("opens on the active provider when every favorite belongs to a disabled provider", async () => { diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 094f0c7098002..b92f8f07f56ad 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -123,7 +123,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { triggerShortcuts?: string; /** * Docks an effort column beside the list and a footer under both. The popup then stays open - * until Escape or an outside press, and picking a model moves focus to its levels. + * until Escape, an outside press or Enter on a level, and picking a model moves focus to its + * levels. */ effortColumn?: ReactNode; footer?: ReactNode; @@ -470,8 +471,21 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { data-model-picker-effort className="flex min-h-0 w-48 flex-col sm:shrink-0 border-l border-border/70 bg-muted/40 max-sm:h-64 max-sm:w-full max-sm:border-t max-sm:border-l-0" onKeyDown={(event) => { - if (event.key !== "ArrowLeft" || event.altKey || event.ctrlKey || event.metaKey) + if (event.altKey || event.ctrlKey || event.metaKey) return; + const target = event.target; + if ( + event.key === "Enter" && + target instanceof HTMLElement && + target.matches("[data-effort-level]") + ) { + // Enter confirms the level: it picks it and closes the picker. + event.preventDefault(); + event.stopPropagation(); + target.click(); + setIsMenuOpen(false); return; + } + if (event.key !== "ArrowLeft") return; event.preventDefault(); event.stopPropagation(); searchInputRef.current?.focus(); diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index 3e4d47e7c9433..f354201c28c4a 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -43,7 +43,8 @@ lowest, and decrease wraps from the lowest level to the highest. In the model picker, press Left in an empty search field or Shift+Tab to reach the provider list. Use Up/Down to move and Enter to choose. Right returns to model search. Right at the end of the search moves to the highlighted model's effort -levels, and Left comes back. Choosing a model keeps the picker open on its effort. `mod+shift+up` and `mod+shift+down` switch providers directly and clear the +levels, and Left comes back. Choosing a model keeps the picker open on its effort. Enter on a +level chooses it, closes the picker and returns to the message input. `mod+shift+up` and `mod+shift+down` switch providers directly and clear the search. These provider shortcuts can also be changed in Settings. These shortcuts run inside the focused web or desktop client. `mod` uses Command From 61932b57e481117dd6b3a1c93e4b74353a9b56dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:58:20 +0200 Subject: [PATCH 07/48] feat(web): thread details show weekly usage as activity rings The thread details panel showed no weekly limits unless the Usage limits row was on, and then only for the selected provider. Add a "Weekly usage rings" item, on by default, that draws each pooled weekly window across all environments as a concentric ring with the percent left beside it. Co-Authored-By: Claude Opus 5.5 --- .../components/chat/ThreadDetailsPanel.tsx | 3 + .../components/chat/ThreadDetailsUsage.tsx | 2 +- .../chat/ThreadDetailsUsageRings.tsx | 161 ++++++++++++++++++ .../src/components/chat/threadDetailsItems.ts | 1 + 4 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/components/chat/ThreadDetailsUsageRings.tsx diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 4942080dbb2d2..deccee2e187f7 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -31,6 +31,7 @@ import { ThreadDetailsUsage, type ThreadDetailsUsageInput, } from "./ThreadDetailsUsage"; +import { ThreadDetailsUsageRings } from "./ThreadDetailsUsageRings"; import { ThreadDetailsItemsMenuItems } from "./ThreadDetailsItemsMenu"; import { resolveThreadDetailsVisibility, THREAD_DETAILS_ITEMS } from "./threadDetailsItems"; import { useClientSettings } from "../../hooks/useSettings"; @@ -286,6 +287,8 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { {visible.usage ? : null} + {visible.usageRings ? : null} + {visible.context && props.usage.contextWindow ? ( ) : null} diff --git a/apps/web/src/components/chat/ThreadDetailsUsage.tsx b/apps/web/src/components/chat/ThreadDetailsUsage.tsx index 0d6c0129484ed..36ccd4c1a6b2b 100644 --- a/apps/web/src/components/chat/ThreadDetailsUsage.tsx +++ b/apps/web/src/components/chat/ThreadDetailsUsage.tsx @@ -24,7 +24,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { formatContextWindowCompactionMessage } from "./compaction.logic"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; -const PACE_LABEL: Record = { +export const PACE_LABEL: Record = { ahead: "Ahead of pace", on: "On pace", under: "Under pace", diff --git a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx new file mode 100644 index 0000000000000..91704a5e956cd --- /dev/null +++ b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx @@ -0,0 +1,161 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + collectLimitAccounts, + collectLimitPools, + displayLimitWindows, + formatDuration, +} from "@t3tools/shared/usageLimits"; + +import { useNowMinute } from "../../hooks/useNowMinute"; +import { usePrimarySettings } from "../../hooks/useSettings"; +import { cn } from "../../lib/utils"; +import { environmentPresentations } from "../../state/presentation"; +import { formatUpcomingTimestamp } from "../../timestampFormat"; +import { providerClients } from "../settings/providerDriverMeta"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { ThreadDetailsSection } from "./ThreadDetailsSection"; +import { PACE_LABEL } from "./ThreadDetailsUsage"; + +// Activity-ring hues, deepened in light mode so they hold contrast on a white card. +const RING_COLORS = [ + "text-[#e8104a] dark:text-[#fa114f]", + "text-[#5cb000] dark:text-[#a6ff00]", + "text-[#00a9c2] dark:text-[#00f0ff]", + "text-[#e69a00] dark:text-[#ffcc00]", +] as const; + +const SIZE = 76; +const STROKE = 7; +const STEP = 9; + +/** Weekly limits across all environments, as concentric rings that show the room left. */ +export function ThreadDetailsUsageRings() { + const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); + const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); + const nowMinute = useNowMinute(); + const now = Date.parse(`${nowMinute}:00Z`); + const rings = collectLimitPools(collectLimitAccounts(presentations), now) + .flatMap((pool) => { + const provider = providerClients.get(pool.driver)?.label ?? String(pool.driver); + return displayLimitWindows(pool) + .filter((window) => window.kind === "weekly") + .map((window) => ({ + key: `${pool.driver}:${window.id}`, + // "Weekly · Fable" names its model; plain "Weekly" falls back to the provider. + name: window.label.replace(/^Weekly(\s*·\s*)?/i, "") || provider, + title: `${provider} ${window.label}`, + window, + })); + }) + // lean: more than four rings leave no room in the center; revisit if a fifth weekly pool matters. + .slice(0, RING_COLORS.length); + if (rings.length === 0) return null; + + return ( + +
+ + {rings.map((ring, index) => { + const radius = SIZE / 2 - STROKE / 2 - index * STEP; + const circumference = 2 * Math.PI * radius; + const left = ring.window.remainingPercent; + return ( + + + {left > 0 ? ( + + ) : null} + + ); + })} + +
+ {rings.map((ring, index) => { + const left = ring.window.remainingPercent; + const reset = ring.window.resets.find((entry) => entry.at > now); + return ( + + + } + > + + {ring.name} + + {left}% + + + +
+ + {ring.title}: {left}% left + + {reset ? ( + + Resets in {formatDuration(reset.at - now)} ·{" "} + {formatUpcomingTimestamp( + new Date(reset.at).toISOString(), + timestampFormat, + now, + )} + + ) : null} + {ring.window.pace ? ( + {PACE_LABEL[ring.window.pace]} + ) : null} +
+
+
+ ); + })} +
+
+
+ ); +} diff --git a/apps/web/src/components/chat/threadDetailsItems.ts b/apps/web/src/components/chat/threadDetailsItems.ts index e6f94cc4e11c8..8de9f7d08d641 100644 --- a/apps/web/src/components/chat/threadDetailsItems.ts +++ b/apps/web/src/components/chat/threadDetailsItems.ts @@ -13,6 +13,7 @@ export const THREAD_DETAILS_ITEMS = [ { id: "lineage", label: "Lineage", defaultVisible: true }, { id: "sideChats", label: "Side chats", defaultVisible: true }, { id: "usage", label: "Usage limits", defaultVisible: false }, + { id: "usageRings", label: "Weekly usage rings", defaultVisible: true }, { id: "context", label: "Context window", defaultVisible: false }, ] as const; From fcf070e0186b4ac89390e70e3aaecaf69d83fc79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:02:48 +0200 Subject: [PATCH 08/48] fix(web): usage rings clamp percent, trim trailing Weekly, show partial refills MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Code review findings: the pooled percent left could leave 0-100 in the label, labels such as "Go · Weekly" kept the word Weekly, and a pool of several accounts said "Resets in" for a reset that restores only part. Co-Authored-By: Claude Opus 5.5 --- .../components/chat/ThreadDetailsUsageRings.tsx | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx index 91704a5e956cd..35cf6182034a0 100644 --- a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx +++ b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx @@ -41,9 +41,10 @@ export function ThreadDetailsUsageRings() { .filter((window) => window.kind === "weekly") .map((window) => ({ key: `${pool.driver}:${window.id}`, - // "Weekly · Fable" names its model; plain "Weekly" falls back to the provider. - name: window.label.replace(/^Weekly(\s*·\s*)?/i, "") || provider, + // "Weekly · Fable" and "Go · Weekly" keep their qualifier; plain "Weekly" names the provider. + name: window.label.replace(/^Weekly\s*·\s*|\s*·\s*Weekly$|^Weekly$/i, "") || provider, title: `${provider} ${window.label}`, + left: Math.max(0, Math.min(100, window.remainingPercent)), window, })); }) @@ -68,7 +69,7 @@ export function ThreadDetailsUsageRings() { {rings.map((ring, index) => { const radius = SIZE / 2 - STROKE / 2 - index * STEP; const circumference = 2 * Math.PI * radius; - const left = ring.window.remainingPercent; + const { left } = ring; return ( ) : null} @@ -100,7 +101,7 @@ export function ThreadDetailsUsageRings() {
{rings.map((ring, index) => { - const left = ring.window.remainingPercent; + const { left } = ring; const reset = ring.window.resets.find((entry) => entry.at > now); return ( @@ -138,7 +139,10 @@ export function ThreadDetailsUsageRings() { {reset ? ( - Resets in {formatDuration(reset.at - now)} ·{" "} + {ring.window.members.length > 1 + ? `+${reset.restoresPercent}% in ` + : "Resets in "} + {formatDuration(reset.at - now)} ·{" "} {formatUpcomingTimestamp( new Date(reset.at).toISOString(), timestampFormat, From ddb0319e36ef5a1ca399378daf0f07523289a5a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:03:28 +0200 Subject: [PATCH 09/48] fix(web): usage rings use their own palette, not Apple's activity colors Blue, orange, violet, and teal replace the pink, lime, and cyan. Co-Authored-By: Claude Opus 5.5 --- .../src/components/chat/ThreadDetailsUsageRings.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx index 35cf6182034a0..6dcfabe44ca7b 100644 --- a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx +++ b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx @@ -16,12 +16,12 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; import { PACE_LABEL } from "./ThreadDetailsUsage"; -// Activity-ring hues, deepened in light mode so they hold contrast on a white card. +// Deeper in light mode so each ring holds contrast on a white card. const RING_COLORS = [ - "text-[#e8104a] dark:text-[#fa114f]", - "text-[#5cb000] dark:text-[#a6ff00]", - "text-[#00a9c2] dark:text-[#00f0ff]", - "text-[#e69a00] dark:text-[#ffcc00]", + "text-[#2563eb] dark:text-[#60a5fa]", + "text-[#ea580c] dark:text-[#fb923c]", + "text-[#7c3aed] dark:text-[#a78bfa]", + "text-[#0d9488] dark:text-[#2dd4bf]", ] as const; const SIZE = 76; From 6dd654a926b6f541173882467deaca5213a8d8f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:07:22 +0200 Subject: [PATCH 10/48] fix(web): usage rings use the Usage page provider colors Each ring takes its provider's bar color at the same 35% fill as the Usage page bars, so Codex reads gray and Claude rings read orange. Co-Authored-By: Claude Opus 5.5 --- .../chat/ThreadDetailsUsageRings.tsx | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx index 6dcfabe44ca7b..91e3aa1837c14 100644 --- a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx +++ b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx @@ -13,16 +13,11 @@ import { environmentPresentations } from "../../state/presentation"; import { formatUpcomingTimestamp } from "../../timestampFormat"; import { providerClients } from "../settings/providerDriverMeta"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { barColor } from "../usage/UsageLimits"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; import { PACE_LABEL } from "./ThreadDetailsUsage"; -// Deeper in light mode so each ring holds contrast on a white card. -const RING_COLORS = [ - "text-[#2563eb] dark:text-[#60a5fa]", - "text-[#ea580c] dark:text-[#fb923c]", - "text-[#7c3aed] dark:text-[#a78bfa]", - "text-[#0d9488] dark:text-[#2dd4bf]", -] as const; +const MAX_RINGS = 4; const SIZE = 76; const STROKE = 7; @@ -37,6 +32,7 @@ export function ThreadDetailsUsageRings() { const rings = collectLimitPools(collectLimitAccounts(presentations), now) .flatMap((pool) => { const provider = providerClients.get(pool.driver)?.label ?? String(pool.driver); + const color = barColor(pool.driver); return displayLimitWindows(pool) .filter((window) => window.kind === "weekly") .map((window) => ({ @@ -44,12 +40,13 @@ export function ThreadDetailsUsageRings() { // "Weekly · Fable" and "Go · Weekly" keep their qualifier; plain "Weekly" names the provider. name: window.label.replace(/^Weekly\s*·\s*|\s*·\s*Weekly$|^Weekly$/i, "") || provider, title: `${provider} ${window.label}`, + color, left: Math.max(0, Math.min(100, window.remainingPercent)), window, })); }) // lean: more than four rings leave no room in the center; revisit if a fifth weekly pool matters. - .slice(0, RING_COLORS.length); + .slice(0, MAX_RINGS); if (rings.length === 0) return null; return ( @@ -71,7 +68,7 @@ export function ThreadDetailsUsageRings() { const circumference = 2 * Math.PI * radius; const { left } = ring; return ( - + {left > 0 ? ( ) : null} @@ -100,7 +97,7 @@ export function ThreadDetailsUsageRings() { })}
- {rings.map((ring, index) => { + {rings.map((ring) => { const { left } = ring; const reset = ring.window.resets.find((entry) => entry.at > now); return ( @@ -116,7 +113,8 @@ export function ThreadDetailsUsageRings() { > {ring.name} Date: Wed, 18 Nov 2026 18:15:42 +0200 Subject: [PATCH 11/48] fix(web): Fable and Claude weekly rings get different colors A provider's extra weekly windows turn its hue 45 degrees per ring, so Fable reads amber next to Claude's coral. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ThreadDetailsUsageRings.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx index 91e3aa1837c14..13136e0f6ea9a 100644 --- a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx +++ b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx @@ -35,12 +35,13 @@ export function ThreadDetailsUsageRings() { const color = barColor(pool.driver); return displayLimitWindows(pool) .filter((window) => window.kind === "weekly") - .map((window) => ({ + .map((window, index) => ({ key: `${pool.driver}:${window.id}`, // "Weekly · Fable" and "Go · Weekly" keep their qualifier; plain "Weekly" names the provider. name: window.label.replace(/^Weekly\s*·\s*|\s*·\s*Weekly$|^Weekly$/i, "") || provider, title: `${provider} ${window.label}`, - color, + // A provider's extra weekly windows turn its hue so each ring reads apart. + color: index === 0 ? color : `oklch(from ${color} l c calc(h + ${45 * index}))`, left: Math.max(0, Math.min(100, window.remainingPercent)), window, })); From c876a5bf28b7575ce6fa08959f06530832728a60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:25:48 +0200 Subject: [PATCH 12/48] fix(web): usage ring arcs match their percent and pooled tooltips skip empty refills Review findings: round caps made a 95% inner ring look full, and a spent pool member's reset showed "+0%" while hiding the reset that restores. Co-Authored-By: Claude Opus 5.5 --- .../components/chat/ThreadDetailsUsageRings.tsx | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx index 13136e0f6ea9a..f8dda49195228 100644 --- a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx +++ b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx @@ -89,7 +89,12 @@ export function ThreadDetailsUsageRings() { strokeWidth={STROKE} strokeLinecap="round" strokeDasharray={circumference} - strokeDashoffset={circumference * (1 - left / 100)} + // Round caps add half a stroke at each end; trim the dash so the drawn arc matches the percent. + strokeDashoffset={ + left >= 100 + ? 0 + : circumference - Math.max(0, (circumference * left) / 100 - STROKE) + } className="opacity-35 transition-[stroke-dashoffset] duration-500 ease-out motion-reduce:transition-none" /> ) : null} @@ -100,7 +105,11 @@ export function ThreadDetailsUsageRings() {
{rings.map((ring) => { const { left } = ring; - const reset = ring.window.resets.find((entry) => entry.at > now); + const pooled = ring.window.members.length > 1; + // A spent pool member's reset can restore nothing; name the next one that does. + const reset = ring.window.resets.find( + (entry) => entry.at > now && (!pooled || entry.restoresPercent > 0), + ); return ( {reset ? ( - {ring.window.members.length > 1 - ? `+${reset.restoresPercent}% in ` - : "Resets in "} + {pooled ? `+${reset.restoresPercent}% in ` : "Resets in "} {formatDuration(reset.at - now)} ·{" "} {formatUpcomingTimestamp( new Date(reset.at).toISOString(), From e910180cad2f6cf3f4c9eaefe0fd2d6bf482186b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:45:24 +0200 Subject: [PATCH 13/48] fix(web): small usage percents still draw a ring dot, full pools keep their reset time Review findings: a trimmed zero-length dash hid small values on inner rings, and a pool with no restoring reset showed no reset time at all. Co-Authored-By: Claude Opus 5.5 --- .../chat/ThreadDetailsUsageRings.tsx | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx index f8dda49195228..c54d12f03af6d 100644 --- a/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx +++ b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx @@ -88,14 +88,14 @@ export function ThreadDetailsUsageRings() { stroke="currentColor" strokeWidth={STROKE} strokeLinecap="round" - strokeDasharray={circumference} - // Round caps add half a stroke at each end; trim the dash so the drawn arc matches the percent. - strokeDashoffset={ + // Round caps add half a stroke at each end, so trim the dash to match the percent. + // A non-zero dash keeps a small value visible as a cap-sized dot. + strokeDasharray={`${ left >= 100 - ? 0 - : circumference - Math.max(0, (circumference * left) / 100 - STROKE) - } - className="opacity-35 transition-[stroke-dashoffset] duration-500 ease-out motion-reduce:transition-none" + ? circumference + : Math.max(0.01, (circumference * left) / 100 - STROKE) + } ${circumference}`} + className="opacity-35 transition-[stroke-dasharray] duration-500 ease-out motion-reduce:transition-none" /> ) : null} @@ -106,10 +106,10 @@ export function ThreadDetailsUsageRings() { {rings.map((ring) => { const { left } = ring; const pooled = ring.window.members.length > 1; - // A spent pool member's reset can restore nothing; name the next one that does. - const reset = ring.window.resets.find( - (entry) => entry.at > now && (!pooled || entry.restoresPercent > 0), - ); + // A spent pool member's reset can restore nothing; name the next one that does, else the next one. + const upcoming = ring.window.resets.filter((entry) => entry.at > now); + const refill = pooled ? upcoming.find((entry) => entry.restoresPercent > 0) : undefined; + const reset = refill ?? upcoming[0]; return ( {reset ? ( - {pooled ? `+${reset.restoresPercent}% in ` : "Resets in "} + {refill ? `+${refill.restoresPercent}% in ` : "Resets in "} {formatDuration(reset.at - now)} ·{" "} {formatUpcomingTimestamp( new Date(reset.at).toISOString(), From 69befe5cc7ac043cb6d737188e7fae5e41d73f6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:50:06 +0200 Subject: [PATCH 14/48] feat(pull-requests): per-project feed rules and hidden pull requests The combined Pull Requests list showed every project's pull requests, so users could not follow only their own work in one repository while seeing everything in another, or leave a repository out (upstream Ideas discussion pingdotgg/t3code#27475). - Contracts: new project-scoped server setting `pullRequestFeed` (all, reviewing, authored, hidden; default all) and global `hiddenPullRequests` (URLs, max 500, compared case-insensitively). Server settings hold them, so web, desktop and mobile on one environment share the rules. - client-runtime: `pull-request-feed` resolves a project's rule and decides which rows the combined feed shows. Rules apply only when no single project is picked; hidden pull requests leave every view. - Web: the list applies the rules to its groups and keeps its flat rows consistent; hidden projects get no query. Right-click a row to hide it or set its project's rule. A quiet "Show N hidden" control and a Settings list undo hiding. The feed rule select sits next to the default merge method, so projects can override it. - Mobile: the list applies the same rules, rows get Hide from feed / Show in feed, and Settings -> Source control gets the feed rule and the hidden list. - Docs: how to set rules and unhide. Co-Authored-By: Claude Opus 5.5 --- .../pull-requests/PullRequestsScreen.tsx | 55 ++++++- .../pull-requests/usePullRequestFeed.ts | 64 ++++++++ ...SettingsServerControlsRouteScreen.test.tsx | 3 + .../SettingsServerControlsRouteScreen.tsx | 52 +++++- .../pullRequest/PullRequestListGroups.tsx | 9 +- .../components/pullRequest/PullRequestRow.tsx | 40 +++-- .../pullRequest/PullRequestsPage.tsx | 18 +++ .../pullRequest/pullRequestLinkContextMenu.ts | 10 +- .../pullRequest/pullRequestList.logic.test.ts | 37 +++++ .../pullRequestListGroups.logic.ts | 56 +++++-- ...pullRequestProjectAssignment.logic.test.ts | 19 +++ .../pullRequestProjectAssignment.logic.ts | 4 +- .../pullRequest/usePullRequestFeed.ts | 148 ++++++++++++++++++ .../pullRequest/usePullRequestListView.ts | 15 +- .../settings/ProjectDefaultsSettings.tsx | 48 ++++++ .../settings/SettingInheritance.tsx | 4 + .../components/settings/SettingsPanels.tsx | 35 +++++ .../src/components/settings/scopedSettings.ts | 48 +++++- .../src/components/settings/settingsSearch.ts | 13 ++ .../components/settings/useScopedSettings.ts | 3 +- docs/user/source-control.md | 14 ++ packages/client-runtime/package.json | 4 + .../src/pullRequestFeed.test.ts | 90 +++++++++++ .../client-runtime/src/pullRequestFeed.ts | 148 ++++++++++++++++++ packages/contracts/src/pullRequest.ts | 11 ++ packages/contracts/src/settings.ts | 8 +- 26 files changed, 917 insertions(+), 39 deletions(-) create mode 100644 apps/mobile/src/features/pull-requests/usePullRequestFeed.ts create mode 100644 apps/web/src/components/pullRequest/usePullRequestFeed.ts create mode 100644 packages/client-runtime/src/pullRequestFeed.test.ts create mode 100644 packages/client-runtime/src/pullRequestFeed.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index d0672f064064a..36379a839d91d 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -32,6 +32,12 @@ import { import { usePullRequestList } from "./usePullRequestList"; import { usePullRequestListControls } from "./usePullRequestListControls"; import { usePullRequestListActions } from "./usePullRequestListActions"; +import { usePullRequestFeed } from "./usePullRequestFeed"; +import { + isPullRequestHidden, + pullRequestFeedGroup, + pullRequestFeedVisibility, +} from "@t3tools/client-runtime/pull-request-feed"; import { filterPullRequestList, pullRequestListFacets, @@ -190,6 +196,26 @@ export function PullRequestsScreen( ), [result.entries, controls, query, result.data, connectedKey], ); + const feed = usePullRequestFeed(); + const [showHidden, setShowHidden] = useState(false); + const viewers = result.data?.viewers ?? {}; + const visibilities = entries.map((entry) => + pullRequestFeedVisibility( + entry, + pullRequestFeedGroup(entry, viewers[`${entry.environmentId} ${entry.host}`]), + { + scopedToProject: Boolean(controls.projectId), + involvement: controls.involvement, + ruleFor: feed.ruleFor, + hidden: feed.hidden, + }, + ), + ); + const hiddenCount = visibilities.filter((visibility) => visibility === "hidden").length; + const feedEntries = entries.filter( + (_, index) => + visibilities[index] === "shown" || (visibilities[index] === "hidden" && showHidden), + ); const facets = pullRequestListFacets(result.entries); const [knownFacets, setKnownFacets] = useState({ environmentId, source: facets, ...facets }); if (knownFacets.environmentId !== environmentId || knownFacets.source !== facets) { @@ -261,8 +287,21 @@ export function PullRequestsScreen( [ + ...actions(entry), + ...(feed.canHide(entry.environmentId) + ? [ + isPullRequestHidden(feed.hidden, entry.url) + ? { id: "unhide", title: "Show in feed", image: "eye" } + : { id: "hide", title: "Hide from feed", image: "eye.slash" }, + ] + : []), + ]} + onAction={(entry, action) => { + if (action === "hide") feed.hide(entry); + else if (action === "unhide") feed.unhide(entry.url); + else select(entry, action); + }} busy={busyKey === pullRequestKey(item)} selected={selectedKey === pullRequestKey(item)} sidebar={sidebar} @@ -272,7 +311,7 @@ export function PullRequestsScreen( + {hiddenCount > 0 ? ( + + +
+ ) : null} {listError && shownCount > 0 ? (
diff --git a/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts index c6107a155bf76..351e7aa967869 100644 --- a/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts +++ b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts @@ -40,9 +40,17 @@ export async function showPullRequestLinkContextMenu({ } catch { return; } + if (action !== null) await runPullRequestLinkAction(action, url); +} + +export async function runPullRequestLinkAction( + action: PullRequestLinkContextMenuAction, + url: string, +): Promise { + const api = readLocalApi(); try { if (action === "copy-link") await writeTextToClipboard(url, "link"); - else if (action === "open-external") await api.shell.openExternal(url); + else await api?.shell.openExternal(url); } catch { toastManager.add({ type: "error", diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts index dfa31d4dbcd6b..3a4705a3fe479 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts @@ -682,6 +682,43 @@ describe("the priority groups against a paginated feed", () => { groups.find((group) => group.key === "others")?.entries.map((row) => row.number), ).toEqual([6123]); }); + + it("applies each project's feed rule and keeps the flat rows to what the groups show", () => { + const mine = authoredRow(1, "2026-08-11T08:00:00Z"); + const theirs = entry({ number: 2, updatedAt: "2026-08-11T09:00:00Z" }); + const other = entry({ number: 3, projectId: "project-2" as ProjectId }); + const hiddenRow = entry({ number: 4, projectId: "project-2" as ProjectId }); + const groupsFor = (scopedToProject: boolean) => + pullRequestGroups({ + known: [mine, theirs, other, hiddenRow], + baseline: undefined, + providers: [], + viewers: VIEWERS, + involvement: "all", + localFilters: {}, + hasLocalFilters: false, + text: "", + answeredLocally: false, + baselineEmpty: true, + held: undefined, + authored: undefined, + reviewing: undefined, + partitionsWanted: false, + feed: { + scopedToProject, + ruleFor: (row) => (row.projectId === "project-1" ? "authored" : "all"), + hidden: new Set([hiddenRow.url]), + showHidden: false, + }, + }); + + const combined = groupsFor(false); + expect(combined.entries.map((row) => row.number)).toEqual([1, 3]); + expect(combined.groups.map((group) => group.key)).toEqual(["authored", "others"]); + expect(combined.hiddenCount).toBe(1); + expect(combined.heldPullRequestsBySurface.size).toBe(2); + expect(groupsFor(true).entries.map((row) => row.number)).toEqual([2, 1, 3]); + }); }); describe("pull request list overrides", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts b/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts index 31f02978c918d..7f5feb8ce1fb4 100644 --- a/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts @@ -1,3 +1,7 @@ +import { + filterPullRequestFeed, + type PullRequestFeedOptions, +} from "@t3tools/client-runtime/pull-request-feed"; import type { PullRequestInvolvement, PullRequestListFilters, @@ -39,6 +43,7 @@ export function pullRequestGroups({ authored, reviewing, partitionsWanted, + feed, }: { known: ReadonlyArray; /** The text-free rows already loaded, or undefined when the typed filters cannot vet them. */ @@ -55,6 +60,10 @@ export function pullRequestGroups({ authored: ReadonlyArray | undefined; reviewing: ReadonlyArray | undefined; partitionsWanted: boolean; + /** Project feed rules and hidden pull requests; `hiddenCount` counts hidden rows in this view. */ + feed?: Omit, "involvement"> & { + readonly showHidden: boolean; + }; }) { const searchingHosts = new Set( providers.flatMap((provider) => (provider.searchesOnHost ? [provider.host] : [])), @@ -69,7 +78,7 @@ export function pullRequestGroups({ : involvementEntries; }; - const entries = (() => { + const searched = (() => { const narrowedEntries = narrowRows(known); if (text.length === 0) { return narrowedEntries.toSorted(comparePullRequestsByRecency); @@ -89,20 +98,10 @@ export function pullRequestGroups({ return missed.length === 0 ? matched : [...matched, ...rankPullRequestMatches(missed, text)]; })(); - const listedPullRequestTabStatuses: Record = Object.fromEntries( - entries.map((entry) => [ - pullRequestSurfaceId(entry), - { - state: entry.state, - isDraft: entry.isDraft, - }, - ]), - ); - - const groups = (() => { - if (involvement !== "all") return [{ key: "others" as const, label: "", entries }]; + const grouped = (() => { + if (involvement !== "all") return [{ key: "others" as const, label: "", entries: searched }]; if (baselineEmpty) { - return groupPullRequestsByInvolvement(entries, viewers); + return groupPullRequestsByInvolvement(searched, viewers); } const narrow = (rows: ReadonlyArray | undefined) => rows === undefined || !hasLocalFilters @@ -113,11 +112,35 @@ export function pullRequestGroups({ const narrowedAuthored = narrow(partitionsWanted ? (authored ?? held?.authored) : undefined); const narrowedReviewing = narrow(partitionsWanted ? (reviewing ?? held?.reviewing) : undefined); if (narrowedAuthored === undefined || narrowedReviewing === undefined) { - return groupPullRequestsByInvolvement(entries, viewers); + return groupPullRequestsByInvolvement(searched, viewers); } - return partitionPullRequestsWithPriority(entries, narrowedAuthored, narrowedReviewing); + return partitionPullRequestsWithPriority(searched, narrowedAuthored, narrowedReviewing); })(); + // lean: projects ruled "authored" or "reviewing" are still read by the main list, and their + // other rows drop here, which can leave a short page. Revisit if users report sparse pages. + const { groups, hiddenCount } = + feed === undefined + ? { groups: grouped, hiddenCount: 0 } + : filterPullRequestFeed(grouped, { ...feed, involvement }); + const entries = + groups === grouped + ? searched + : (() => { + const kept = new Set(groups.flatMap((group) => group.entries.map((entry) => entry.url))); + return searched.filter((entry) => kept.has(entry.url)); + })(); + + const listedPullRequestTabStatuses: Record = Object.fromEntries( + entries.map((entry) => [ + pullRequestSurfaceId(entry), + { + state: entry.state, + isDraft: entry.isDraft, + }, + ]), + ); + const entriesByStatsKey: ReadonlyMap = new Map( groups.flatMap((group) => group.entries.map((entry) => [pullRequestEntryKey(entry), entry] as const), @@ -132,6 +155,7 @@ export function pullRequestGroups({ entries, listedPullRequestTabStatuses, groups, + hiddenCount, entriesByStatsKey, heldPullRequestsBySurface, }; diff --git a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts index 7b8da285376f4..eb615d7b868ed 100644 --- a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts @@ -159,6 +159,25 @@ describe("assignment query limits", () => { }), ).not.toThrow(); }); + + it("names the projects a feed keeps once another project there is hidden", () => { + const projects = [project("a", "env-1", "x/a"), project("b", "env-1", "x/b")]; + expect(pullRequestProjectQueries(projects, envs("env-1"))).toEqual([ + { environmentId: "env-1" }, + ]); + expect( + pullRequestProjectQueries( + projects, + envs("env-1"), + undefined, + undefined, + (candidate) => candidate.id === "b", + ), + ).toEqual([{ environmentId: "env-1", projectIds: ["a"] }]); + expect( + pullRequestProjectQueries(projects, envs("env-1"), undefined, undefined, () => true), + ).toEqual([]); + }); }); describe("one server per repository", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts index f192776675a5c..032a948e66a71 100644 --- a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts @@ -181,12 +181,14 @@ export function pullRequestProjectQueries( environmentIds: ReadonlyArray, hostAvailability?: PullRequestHostAvailability, unreachableEnvironmentIds?: ReadonlySet, + /** Projects the feed leaves out entirely; their environment then lists the rest by id. */ + excluded?: (project: AssignableProject) => boolean, ): ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly projectIds?: ReadonlyArray; }> { const assignment = assignProjectsToEnvironments( - projects, + excluded === undefined ? projects : projects.filter((project) => !excluded(project)), environmentIds, environmentIds[0], hostAvailability, diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts new file mode 100644 index 0000000000000..773704740a349 --- /dev/null +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -0,0 +1,148 @@ +import { + hiddenPullRequestUrls, + isPullRequestHidden, + PULL_REQUEST_FEED_RULES, + pullRequestFeedRule, + withHiddenPullRequest, + withoutHiddenPullRequest, +} from "@t3tools/client-runtime/pull-request-feed"; +import type { + ContextMenuItem, + EnvironmentId, + ProjectId, + PullRequestFeedRule, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; + +import { useStableCallback } from "~/hooks/useStableCallback"; +import { readLocalApi } from "~/localApi"; +import { useEnvironments } from "~/state/environments"; + +import { + applyPendingScopedWrites, + pendingScopedWritesAtom, + planEnvironmentSettingsPatch, + planProjectOverridePatch, +} from "../settings/scopedSettings"; +import { useRunScopedPlan } from "../settings/useScopedSettings"; +import { runPullRequestLinkAction } from "./pullRequestLinkContextMenu"; +import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic"; +import type { PullRequestRowMenu } from "./PullRequestRow"; + +type FeedMenuAction = + | "copy-link" + | "open-external" + | "hide" + | "unhide" + | `rule:${PullRequestFeedRule}`; + +/** Per-project feed rules and hidden pull requests, read from every environment's settings. */ +export function usePullRequestFeed() { + const { environments: known } = useEnvironments(); + const pendingWrites = useAtomValue(pendingScopedWritesAtom); + const environments = applyPendingScopedWrites(known, pendingWrites); + const runPlan = useRunScopedPlan(); + const settingsOf = (environmentId: EnvironmentId) => + environments.find((environment) => environment.environmentId === environmentId)?.serverConfig + ?.settings; + const hidden = hiddenPullRequestUrls( + environments.map((environment) => environment.serverConfig?.settings), + ); + + const ruleFor = (entry: { environmentId: EnvironmentId; projectId: ProjectId }) => + pullRequestFeedRule(settingsOf(entry.environmentId), entry.projectId); + + // Original spelling, newest last, once per link. + const hiddenUrls = [ + ...new Map( + environments + .flatMap((environment) => environment.serverConfig?.settings.hiddenPullRequests ?? []) + .map((url) => [url.toLowerCase(), url] as const), + ).values(), + ]; + + const hide = (entry: Pick) => + runPlan( + environments.filter((environment) => environment.environmentId === entry.environmentId), + (current) => + planEnvironmentSettingsPatch(current, (settings) => ({ + hiddenPullRequests: withHiddenPullRequest(settings.hiddenPullRequests, entry.url), + })), + ); + + // Every environment that holds the link hides it, so unhiding clears them all. + const unhide = (url: string) => + runPlan(environments, (current) => + planEnvironmentSettingsPatch(current, (settings) => { + const next = withoutHiddenPullRequest(settings.hiddenPullRequests, url); + return next.length === settings.hiddenPullRequests.length + ? null + : { hiddenPullRequests: next }; + }), + ); + + const setProjectRule = ( + project: { environmentId: EnvironmentId; projectId: ProjectId }, + rule: PullRequestFeedRule, + ) => + runPlan(environments, (current) => + planProjectOverridePatch( + current, + { id: project.projectId, environmentId: project.environmentId }, + { pullRequestFeed: rule }, + ), + ); + + const openRowMenu = async ( + entry: EnvironmentPullRequestEntry, + openLabel: string, + position: { readonly x: number; readonly y: number }, + ) => { + const api = readLocalApi(); + if (!api) return; + const isHidden = isPullRequestHidden(hidden, entry.url); + const rule = ruleFor(entry); + const rulesSupported = + environments.find((environment) => environment.environmentId === entry.environmentId) + ?.serverConfig?.environment.capabilities.projectSettingsOverrides === true; + const items: ContextMenuItem[] = [ + { id: "copy-link", label: "Copy link", icon: "copy" }, + { id: "open-external", label: openLabel }, + isHidden + ? { id: "unhide", label: "Show in feed", separatorBefore: true } + : { id: "hide", label: "Hide from feed", separatorBefore: true }, + { + id: "rule:all", + label: `Feed for ${entry.projectTitle}`, + disabled: !rulesSupported, + children: PULL_REQUEST_FEED_RULES.map((option) => ({ + id: `rule:${option.value}` as const, + label: option.label, + checked: option.value === rule, + })), + }, + ]; + let action: FeedMenuAction | null = null; + try { + action = await api.contextMenu.show(items, position); + } catch { + return; + } + if (action === "copy-link" || action === "open-external") { + await runPullRequestLinkAction(action, entry.url); + } else if (action === "hide") { + hide(entry); + } else if (action === "unhide") { + unhide(entry.url); + } else { + const picked = PULL_REQUEST_FEED_RULES.find((option) => action === `rule:${option.value}`); + if (picked) setProjectRule(entry, picked.value); + } + }; + + const showRowMenu: PullRequestRowMenu = useStableCallback((entry, openLabel, position) => { + void openRowMenu(entry, openLabel, position); + }); + + return { hidden, hiddenUrls, ruleFor, unhide, showRowMenu }; +} diff --git a/apps/web/src/components/pullRequest/usePullRequestListView.ts b/apps/web/src/components/pullRequest/usePullRequestListView.ts index 7b9e128f12b66..6a4ade10dde66 100644 --- a/apps/web/src/components/pullRequest/usePullRequestListView.ts +++ b/apps/web/src/components/pullRequest/usePullRequestListView.ts @@ -40,6 +40,7 @@ import { pullRequestProjectQueries, type PullRequestHostAvailability, } from "./pullRequestProjectAssignment.logic"; +import { pullRequestFeedRule } from "@t3tools/client-runtime/pull-request-feed"; import { pullRequestFilterProjects } from "@t3tools/client-runtime/pull-request-project-filter"; import { pullRequestListEntryId } from "./pullRequestListGroups.logic"; @@ -141,7 +142,19 @@ export function usePullRequestScope( }> => { const plain = queryEnvironmentIds.map((environmentId) => ({ environmentId })); if (!projectsKnown || scopedProjectId !== undefined) return plain; - return pullRequestProjectQueries(projects, queryEnvironmentIds, availability, unreachable); + return pullRequestProjectQueries( + projects, + queryEnvironmentIds, + availability, + unreachable, + (project) => + pullRequestFeedRule( + capableEnvironments.find( + (environment) => environment.environmentId === project.environmentId, + )?.serverConfig?.settings, + project.id, + ) === "hidden", + ); }; const environmentQueries = queriesFor(hostAvailability); // What the page reads once a refresh forgets host reads; refresh must refetch these too. diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx index 97c9ca0483ab8..8270619899c62 100644 --- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx +++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx @@ -5,6 +5,7 @@ import { managedRuntimeModeDenial, } from "@t3tools/contracts"; import { createModelSelection, pickModelSelection } from "@t3tools/shared/model"; +import { PULL_REQUEST_FEED_RULES } from "@t3tools/client-runtime/pull-request-feed"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { useNavigate } from "@tanstack/react-router"; @@ -104,6 +105,7 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting const mixedAutoPull = useScopedSettingsMixed(["defaultAutoPull"]); const mixedAgentCredits = useScopedSettingsMixed(["removeAgentCreditsOnMerge"]); const mixedMergeMethod = useScopedSettingsMixed(["pullRequestMergeMethod"]); + const mixedPullRequestFeed = useScopedSettingsMixed(["pullRequestFeed"]); const modelSource = useScopedSettingSource(["defaultModelSelection"]); const isProjectScope = scope.kind === "project" || scope.kind === "checkout"; const unavailable = connectedEnvironments.length === 0; @@ -518,6 +520,52 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting } /> + + updateSettings({ pullRequestFeed: DEFAULT_SERVER_SETTINGS.pullRequestFeed }) + } + /> + ) : null + } + control={ + + } + /> )} diff --git a/apps/web/src/components/settings/SettingInheritance.tsx b/apps/web/src/components/settings/SettingInheritance.tsx index 8f83f137241e4..30ef6cf6a7b26 100644 --- a/apps/web/src/components/settings/SettingInheritance.tsx +++ b/apps/web/src/components/settings/SettingInheritance.tsx @@ -13,6 +13,7 @@ import { cn } from "../../lib/utils"; import type { EnvironmentPresentation } from "../../state/environments"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { resolveEnvModeLabel, WORKTREE_SUBMODULES_LABELS } from "../BranchToolbar.logic"; +import { PULL_REQUEST_FEED_RULES } from "@t3tools/client-runtime/pull-request-feed"; import { PULL_REQUEST_MERGE_METHOD_LABELS } from "../pullRequest/pullRequestDetail.logic"; import { Button, InlineButton } from "../ui/button"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; @@ -73,6 +74,9 @@ function formatValue(key: keyof ServerSettings, value: unknown): string { if (key === "worktreeSubmodules" && value in WORKTREE_SUBMODULES_LABELS) { return WORKTREE_SUBMODULES_LABELS[value as WorktreeSubmodules]; } + if (key === "pullRequestFeed") { + return PULL_REQUEST_FEED_RULES.find((option) => option.value === value)?.label ?? value; + } if (key === "pullRequestMergeMethod" && value in PULL_REQUEST_MERGE_METHOD_LABELS) { return PULL_REQUEST_MERGE_METHOD_LABELS[ value as keyof typeof PULL_REQUEST_MERGE_METHOD_LABELS diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 633e18a567b2f..b3c67850503b5 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -115,7 +115,9 @@ import { nativeLanguageName, SYSTEM_LANGUAGE } from "@t3tools/client-runtime/loc import { SUPPORTED_LOCALES } from "../../i18n/locales"; import { BackgroundActivitySettingsRow } from "./BackgroundActivitySettings"; import { AdvancedSettings } from "./AdvancedSettings"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { PullRequestLinksOpenInAppSetting } from "./IntegrationsSettings"; +import { usePullRequestFeed } from "../pullRequest/usePullRequestFeed"; import { StorageCleanupSections } from "./StorageSettings"; import { UpdateTrackSwitchDialog } from "./UpdateTrackSwitchDialog"; import { environmentIdsKey } from "~/state/environmentAtomList"; @@ -1649,11 +1651,44 @@ export function DiffsSettingsPanel() { } /> + ); } +function HiddenPullRequestsSetting() { + const { hiddenUrls, unhide } = usePullRequestFeed(); + return ( + + {hiddenUrls.length === 0 ? null : ( +
    + {hiddenUrls.toReversed().map((url) => { + const link = sourceControlClients.parseChangeRequestUrl(url)?.link; + return ( +
  • + + {link ? `${link.repository} #${link.number}` : url} + + +
  • + ); + })} +
+ )} +
+ ); +} + /** The Providers panel can render without a settings scope, as its tests do; this row needs one. */ export function CompactIdleThreadsRow() { return useOptionalSettingsScope() === null ? null : ; diff --git a/apps/web/src/components/settings/scopedSettings.ts b/apps/web/src/components/settings/scopedSettings.ts index d0654f8902d8c..01e9f0113e1ca 100644 --- a/apps/web/src/components/settings/scopedSettings.ts +++ b/apps/web/src/components/settings/scopedSettings.ts @@ -242,7 +242,7 @@ interface ScopedServerWrite { } function projectOverrideWrites( - scope: Extract, + members: readonly { readonly id: ProjectId; readonly environmentId: EnvironmentId }[], environments: readonly ScopedSettingsEnvironment[], update: ( current: ProjectSettingsOverrides, @@ -252,7 +252,7 @@ function projectOverrideWrites( ): ScopedServerWrite[] { const byId = new Map(environments.map((environment) => [environment.environmentId, environment])); const writes = new Map(); - for (const member of scope.members) { + for (const member of members) { const environment = byId.get(member.environmentId); if (!environment?.serverConfig || environment.connection.phase !== "connected") { continue; @@ -314,7 +314,7 @@ export function planScopedSettingsPatch( : isProjectScope ? unscopableKeys.length > 0 ? [] - : projectOverrideWrites(scope, environments, (current, settings, projectId) => { + : projectOverrideWrites(scope.members, environments, (current, settings, projectId) => { // Override entries store whole objects; complete partial patches from each target's effective // value. const effective = resolveProjectSettings(settings, projectId).settings; @@ -415,7 +415,7 @@ export function planScopedSettingsClear( ) { const serverWrites = scope.kind === "project" || scope.kind === "checkout" - ? projectOverrideWrites(scope, environments, (_current, settings, projectId) => + ? projectOverrideWrites(scope.members, environments, (_current, settings, projectId) => clearProjectSettingsOverrides(settings, projectId, keys), ) : []; @@ -518,6 +518,46 @@ function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | un type ScopedSettingsPlan = ReturnType; +const unavailablePlan = ( + serverWrites: ScopedServerWrite[], + unavailableReason: string, +): ScopedSettingsPlan => ({ + clientPatch: {}, + hasClientWrite: false, + serverWrites, + unavailableReason: serverWrites.length > 0 ? null : unavailableReason, +}); + +/** One project's override, written from outside Settings, such as a list row. */ +export function planProjectOverridePatch( + environments: readonly ScopedSettingsEnvironment[], + project: { readonly id: ProjectId; readonly environmentId: EnvironmentId }, + patch: ProjectSettingsOverrides, +): ScopedSettingsPlan { + return unavailablePlan( + projectOverrideWrites([project], environments, (current) => ({ ...current, ...patch })), + "Connect this project's environment to save its setting.", + ); +} + +/** Environment-wide writes computed from each environment's newest settings. */ +export function planEnvironmentSettingsPatch( + environments: readonly ScopedSettingsEnvironment[], + update: (settings: ServerSettings) => ServerSettingsPatch | null, +): ScopedSettingsPlan { + return unavailablePlan( + environments.flatMap((environment) => { + const previous = environment.serverConfig?.settings; + if (!previous || environment.connection.phase !== "connected") return []; + const patch = update(previous); + return patch === null + ? [] + : [{ environmentId: environment.environmentId, label: environment.label, previous, patch }]; + }), + "Connect the environment to save this setting.", + ); +} + type ScopedSettingsPersistServer = (input: { environmentId: EnvironmentId; input: { patch: ServerSettingsPatch }; diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 937e37dd8ec38..c0c69617227b7 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1111,6 +1111,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/browser", searchTerms: ["address bar duckduckgo google bing brave kagi ecosia custom url"], }, + { + id: "hidden-pull-requests", + title: "Hidden pull requests", + to: "/settings/diffs", + searchTerms: ["pr feed list hide unhide show excluded"], + }, { id: "pull-request-links-open-in-app", title: "Open pull requests in T3 Code", @@ -1148,6 +1154,13 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "project-defaults", searchTerms: ["pull request merge squash rebase last selected"], }, + { + id: "pull-request-feed", + title: "Pull request feed", + to: "/settings/source-control", + scope: "project-defaults", + searchTerms: ["pull requests list feed authored waiting on me review requested hide exclude"], + }, { id: "source-control", title: "Source control", diff --git a/apps/web/src/components/settings/useScopedSettings.ts b/apps/web/src/components/settings/useScopedSettings.ts index d67e2d3124282..1496686a6e05e 100644 --- a/apps/web/src/components/settings/useScopedSettings.ts +++ b/apps/web/src/components/settings/useScopedSettings.ts @@ -56,7 +56,8 @@ export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) return scopedSettingsSource(targets, keys); } -function useRunScopedPlan() { +/** Runs a settings plan with the queued writer, pending echoes and failure toasts of Settings. */ +export function useRunScopedPlan() { const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false }); return ( environments: Parameters[0], diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 2f068d8827494..4b274ac173f73 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -244,6 +244,20 @@ PR creation from Git actions continue to use the project's environment. For Azure DevOps, use the host website to change comments. Bitbucket does not support reopening a declined pull request. +### Choose what the list shows + +When the list shows all projects, each project adds pull requests by its **Pull request feed** +rule: **All pull requests**, **Waiting on me** (your review is requested), **Authored by me**, or +**Hidden**. Set the default in Settings → Source control, and override it for a project with the +project selector there. On web and desktop you can also right-click a pull request and choose a +rule for its project. Picking one project in the list's project filter shows all its pull +requests. + +To hide one pull request, right-click it on web and desktop, or touch and hold it on mobile, and +choose **Hide from feed**. Hidden pull requests leave every list. Press **Show N hidden** in the +list to see them again, then choose **Show in feed** to unhide one. You can also unhide them in +Settings → Diffs & pull requests on web and desktop, or Settings → Source control on mobile. + ### Review guides Review guides are in beta. Turn on **Review guides** in Settings → Source control to add the diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d303b27c879f9..276c75a2aaa09 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -463,6 +463,10 @@ "types": "./src/threadReference.ts", "default": "./src/threadReference.ts" }, + "./pull-request-feed": { + "types": "./src/pullRequestFeed.ts", + "default": "./src/pullRequestFeed.ts" + }, "./pull-request-project-filter": { "types": "./src/pullRequestProjectFilter.ts", "default": "./src/pullRequestProjectFilter.ts" diff --git a/packages/client-runtime/src/pullRequestFeed.test.ts b/packages/client-runtime/src/pullRequestFeed.test.ts new file mode 100644 index 0000000000000..a21c707875952 --- /dev/null +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from "@effect/vitest"; +import { DEFAULT_SERVER_SETTINGS, ProjectId, type PullRequestFeedRule } from "@t3tools/contracts"; + +import { + filterPullRequestFeed, + pullRequestFeedGroup, + pullRequestFeedRule, + pullRequestFeedShows, + withHiddenPullRequest, + withoutHiddenPullRequest, + type PullRequestFeedGroup, +} from "./pullRequestFeed.ts"; + +const projectA = ProjectId.make("project-a"); +const projectB = ProjectId.make("project-b"); + +describe("pull request feed rules", () => { + it.each<[PullRequestFeedRule, PullRequestFeedGroup, "all" | "authored" | "reviewing", boolean]>([ + ["all", "others", "all", true], + ["hidden", "authored", "all", false], + ["authored", "authored", "all", true], + ["authored", "reviewRequested", "all", false], + ["authored", "others", "all", false], + ["reviewing", "reviewRequested", "all", true], + ["reviewing", "authored", "all", false], + // A narrowed tab holds one group keyed "others" whose kind is the tab's involvement. + ["authored", "others", "authored", true], + ["authored", "others", "reviewing", false], + ["reviewing", "others", "reviewing", true], + ["reviewing", "others", "authored", false], + ])("%s shows a %s row under %s: %s", (rule, group, involvement, shown) => { + expect(pullRequestFeedShows(rule, group, involvement)).toBe(shown); + }); + + it("resolves a project override over the environment rule", () => { + const settings = { + ...DEFAULT_SERVER_SETTINGS, + pullRequestFeed: "authored" as const, + projectSettingsOverrides: { [projectA]: { pullRequestFeed: "hidden" as const } }, + }; + expect(pullRequestFeedRule(settings, projectA)).toBe("hidden"); + expect(pullRequestFeedRule(settings, projectB)).toBe("authored"); + expect(pullRequestFeedRule(null, projectB)).toBe("all"); + }); + + it("puts authored before a review request", () => { + const entry = { author: { login: "Me" }, viewerReviewRequested: true }; + expect(pullRequestFeedGroup(entry, "me")).toBe("authored"); + expect(pullRequestFeedGroup(entry, "someone")).toBe("reviewRequested"); + expect(pullRequestFeedGroup({ ...entry, viewerReviewRequested: false }, null)).toBe("others"); + }); + + it("applies project rules to the combined feed and hides pull requests in every view", () => { + const row = (projectId: ProjectId, url: string) => ({ projectId, url }); + const groups = [ + { key: "authored" as const, entries: [row(projectA, "https://h/a/1")] }, + { + key: "others" as const, + entries: [row(projectA, "https://h/a/2"), row(projectB, "https://H/B/3")], + }, + ]; + const rules: Record = { [projectA]: "authored" }; + const options = { + involvement: "all" as const, + ruleFor: (entry: { projectId: ProjectId }) => rules[entry.projectId] ?? "all", + hidden: new Set(["https://h/b/3"]), + }; + + expect(filterPullRequestFeed(groups, { ...options, scopedToProject: false })).toEqual({ + groups: [groups[0]], + hiddenCount: 1, + }); + expect( + filterPullRequestFeed(groups, { ...options, scopedToProject: false, showHidden: true }), + ).toEqual({ + groups: [groups[0], { key: "others", entries: [row(projectB, "https://H/B/3")] }], + hiddenCount: 1, + }); + expect(filterPullRequestFeed(groups, { ...options, scopedToProject: true })).toEqual({ + groups: [groups[0], { key: "others", entries: [row(projectA, "https://h/a/2")] }], + hiddenCount: 1, + }); + }); + + it("hides and unhides by URL regardless of case", () => { + const hidden = withHiddenPullRequest(["https://h/a/1"], "https://H/A/1"); + expect(hidden).toEqual(["https://H/A/1"]); + expect(withoutHiddenPullRequest(hidden, "https://h/a/1")).toEqual([]); + }); +}); diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts new file mode 100644 index 0000000000000..11dc987119aad --- /dev/null +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -0,0 +1,148 @@ +import { + HIDDEN_PULL_REQUESTS_LIMIT, + type ProjectId, + type PullRequestFeedRule, + type PullRequestInvolvement, + type ServerSettings, +} from "@t3tools/contracts"; + +export type PullRequestFeedSettings = Pick< + ServerSettings, + "pullRequestFeed" | "projectSettingsOverrides" | "hiddenPullRequests" +>; + +/** Which list group a pull request falls in; authored wins over a review request. */ +export type PullRequestFeedGroup = "authored" | "reviewRequested" | "others"; + +export const PULL_REQUEST_FEED_RULES: ReadonlyArray<{ + readonly value: PullRequestFeedRule; + readonly label: string; +}> = [ + { value: "all", label: "All pull requests" }, + { value: "reviewing", label: "Waiting on me" }, + { value: "authored", label: "Authored by me" }, + { value: "hidden", label: "Hidden" }, +]; + +export function pullRequestFeedRule( + settings: PullRequestFeedSettings | null | undefined, + projectId: ProjectId, +): PullRequestFeedRule { + if (!settings) return "all"; + return settings.projectSettingsOverrides[projectId]?.pullRequestFeed ?? settings.pullRequestFeed; +} + +export function pullRequestFeedGroup( + entry: { + readonly author: { readonly login: string } | null; + readonly viewerReviewRequested: boolean; + }, + viewer: string | null | undefined, +): PullRequestFeedGroup { + if (viewer && entry.author?.login.toLowerCase() === viewer.toLowerCase()) return "authored"; + return entry.viewerReviewRequested ? "reviewRequested" : "others"; +} + +/** A narrowed involvement tab holds one group of that kind, whatever its key says. */ +export function pullRequestFeedShows( + rule: PullRequestFeedRule, + group: PullRequestFeedGroup, + involvement: PullRequestInvolvement = "all", +): boolean { + const kind = + involvement === "authored" + ? "authored" + : involvement === "reviewing" + ? "reviewRequested" + : group; + switch (rule) { + case "all": + return true; + case "hidden": + return false; + case "authored": + return kind === "authored"; + case "reviewing": + return kind === "reviewRequested"; + } +} + +/** Every environment's hidden list counts, so a pull request stays hidden when another serves it. */ +export function hiddenPullRequestUrls( + settings: Iterable | null | undefined>, +): ReadonlySet { + const urls = new Set(); + for (const entry of settings) { + for (const url of entry?.hiddenPullRequests ?? []) urls.add(url.toLowerCase()); + } + return urls; +} + +export function isPullRequestHidden(hidden: ReadonlySet, url: string): boolean { + return hidden.size > 0 && hidden.has(url.toLowerCase()); +} + +/** The oldest entries fall off at the limit, so hiding always succeeds. */ +export function withHiddenPullRequest( + hidden: ReadonlyArray, + url: string, +): ReadonlyArray { + const kept = withoutHiddenPullRequest(hidden, url); + return [...kept, url].slice(-HIDDEN_PULL_REQUESTS_LIMIT); +} + +export function withoutHiddenPullRequest( + hidden: ReadonlyArray, + url: string, +): ReadonlyArray { + const key = url.toLowerCase(); + return hidden.filter((entry) => entry.toLowerCase() !== key); +} + +export interface PullRequestFeedOptions { + /** Rules apply only to the combined feed, not when the list shows one project. */ + readonly scopedToProject: boolean; + readonly involvement: PullRequestInvolvement; + readonly ruleFor: (entry: Entry) => PullRequestFeedRule; + readonly hidden: ReadonlySet; +} + +/** `rule` drops the row silently; `hidden` is a row the user hid and can show again. */ +export function pullRequestFeedVisibility( + entry: Entry, + group: PullRequestFeedGroup, + options: PullRequestFeedOptions, +): "shown" | "rule" | "hidden" { + if ( + !options.scopedToProject && + !pullRequestFeedShows(options.ruleFor(entry), group, options.involvement) + ) { + return "rule"; + } + return isPullRequestHidden(options.hidden, entry.url) ? "hidden" : "shown"; +} + +/** Narrows list groups to the feed. Emptied groups drop out. */ +export function filterPullRequestFeed< + Group extends { + readonly key: PullRequestFeedGroup; + readonly entries: ReadonlyArray<{ readonly url: string }>; + }, +>( + groups: ReadonlyArray, + options: PullRequestFeedOptions & { readonly showHidden?: boolean }, +): { readonly groups: ReadonlyArray; readonly hiddenCount: number } { + let hiddenCount = 0; + let changed = false; + const next = groups.flatMap((group) => { + const entries = group.entries.filter((entry) => { + const visibility = pullRequestFeedVisibility(entry, group.key, options); + if (visibility === "hidden") hiddenCount += 1; + return visibility === "shown" || (visibility === "hidden" && options.showHidden === true); + }); + if (entries.length === group.entries.length) return [group]; + changed = true; + return entries.length === 0 ? [] : [{ ...group, entries }]; + }); + return { groups: changed ? next : groups, hiddenCount }; +} diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index d438080369a40..bd109a2413de4 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -63,6 +63,17 @@ export const PullRequestMergeMethod = Schema.Literals([ ]); export type PullRequestMergeMethod = typeof PullRequestMergeMethod.Type; +/** Which of a project's pull requests the combined Pull Requests feed shows. */ +export const PullRequestFeedRule = Schema.Literals(["all", "reviewing", "authored", "hidden"]); +export type PullRequestFeedRule = typeof PullRequestFeedRule.Type; + +export const HIDDEN_PULL_REQUESTS_LIMIT = 500; +/** Pull request URLs the user hid from the feed, compared case-insensitively. */ +export const HiddenPullRequests = Schema.Array( + Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(2048)), +).check(Schema.isMaxLength(HIDDEN_PULL_REQUESTS_LIMIT)); +export type HiddenPullRequests = typeof HiddenPullRequests.Type; + export const PullRequestAction = Schema.Literals([ "merge", "ready", diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 0013e288983e0..d400c07ec8ee4 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -53,7 +53,7 @@ import { ProviderInstanceId, ProviderDriverKind, } from "./providerInstance.ts"; -import { PullRequestMergeMethod } from "./pullRequest.ts"; +import { HiddenPullRequests, PullRequestFeedRule, PullRequestMergeMethod } from "./pullRequest.ts"; import { CloudSpeechModelId, SpeechAcceleration, @@ -1191,6 +1191,7 @@ export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [ "branchNamePrefix", "branchNameInstructions", "pullRequestMergeMethod", + "pullRequestFeed", "sidebarAutoSettleOnMerge", "sidebarAutoSettleAfterDays", "sidebarAutoSettleKeepPullRequests", @@ -1229,6 +1230,7 @@ export const ProjectSettingsOverrides = Schema.Struct({ branchNamePrefix: Schema.optionalKey(TrimmedString), branchNameInstructions: Schema.optionalKey(TrimmedString), pullRequestMergeMethod: Schema.optionalKey(Schema.NullOr(PullRequestMergeMethod)), + pullRequestFeed: Schema.optionalKey(PullRequestFeedRule), sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean), sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)), sidebarAutoSettleKeepPullRequests: Schema.optionalKey(Schema.Boolean), @@ -1559,6 +1561,8 @@ export const ServerSettings = Schema.Struct({ pullRequestMergeMethod: Schema.NullOr(PullRequestMergeMethod).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), + pullRequestFeed: PullRequestFeedRule.pipe(Schema.withDecodingDefault(Effect.succeed("all"))), + hiddenPullRequests: HiddenPullRequests.pipe(Schema.withDecodingDefault(Effect.succeed([]))), // Schema.Unknown preserves unknown-driver configs across versions; see providerInstance.ts. providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe( @@ -1947,6 +1951,8 @@ export const ServerSettingsPatch = Schema.Struct({ reviewGuideModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)), reviewGuideInstructions: Schema.optionalKey(TrimmedString), pullRequestMergeMethod: Schema.optionalKey(Schema.NullOr(PullRequestMergeMethod)), + pullRequestFeed: Schema.optionalKey(PullRequestFeedRule), + hiddenPullRequests: Schema.optionalKey(HiddenPullRequests), observability: Schema.optionalKey( Schema.Struct({ otlpTracesUrl: Schema.optionalKey(TrimmedString), From f9f78cbf0908afa9bdb401b06a9760e9b2baf6c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:04:23 +0200 Subject: [PATCH 15/48] fix(pull-requests): feed rules hold across environments and older servers Review fixes for the pull request feed rules: - A hidden project now also leaves out the same repository on other environments, which otherwise took over its listing and showed the hidden rows again. - New `pullRequestFeed` environment capability. Clients offer the rule, hiding and unhiding only where the server stores them and the session can write settings, so older servers and standard pairings no longer lose the write. - Mobile builds each hide or unhide on its own writes still in flight, so quick hides no longer drop each other. Unhide is offered only where a writable environment holds the link. - The web row menu leaves links and selected text to the browser's menu. - The empty state says "Nothing under these filters" when feed rules or hidden pull requests removed the rows. - One shared `hiddenPullRequestList` helper replaces the copies in the web and mobile hooks. Co-Authored-By: Claude Opus 5.5 --- .../pull-requests/PullRequestsScreen.tsx | 14 +-- .../pull-requests/usePullRequestFeed.ts | 90 +++++++++++------ ...SettingsServerControlsRouteScreen.test.tsx | 2 +- .../SettingsServerControlsRouteScreen.tsx | 62 ++++++------ .../src/environment/ServerEnvironment.ts | 1 + .../components/pullRequest/PullRequestRow.tsx | 7 ++ .../pullRequest/PullRequestsPage.tsx | 5 +- .../pullRequestListGroups.logic.ts | 5 +- ...pullRequestProjectAssignment.logic.test.ts | 10 ++ .../pullRequestProjectAssignment.logic.ts | 12 ++- .../pullRequest/usePullRequestFeed.ts | 59 +++++++----- .../settings/ProjectDefaultsSettings.tsx | 96 ++++++++++--------- .../components/settings/SettingsPanels.tsx | 9 +- .../src/pullRequestFeed.test.ts | 14 +++ .../client-runtime/src/pullRequestFeed.ts | 31 ++++-- packages/contracts/src/environment.ts | 2 + 16 files changed, 271 insertions(+), 148 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index 36379a839d91d..ef89200390f3a 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -289,13 +289,13 @@ export function PullRequestsScreen( onSelect={selectPullRequest} getActions={(entry) => [ ...actions(entry), - ...(feed.canHide(entry.environmentId) - ? [ - isPullRequestHidden(feed.hidden, entry.url) - ? { id: "unhide", title: "Show in feed", image: "eye" } - : { id: "hide", title: "Hide from feed", image: "eye.slash" }, - ] - : []), + ...(isPullRequestHidden(feed.hidden, entry.url) + ? feed.canUnhide(entry.url) + ? [{ id: "unhide", title: "Show in feed", image: "eye" }] + : [] + : feed.canHide(entry.environmentId) + ? [{ id: "hide", title: "Hide from feed", image: "eye.slash" }] + : []), ]} onAction={(entry, action) => { if (action === "hide") feed.hide(entry); diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts index b2f9f546133f4..663eef62ab597 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts @@ -1,11 +1,14 @@ import { useAtomValue } from "@effect/atom-react"; import { + hiddenPullRequestList, hiddenPullRequestUrls, + isPullRequestHidden, pullRequestFeedRule, withHiddenPullRequest, withoutHiddenPullRequest, } from "@t3tools/client-runtime/pull-request-feed"; import { AuthSettingsWriteScope, type EnvironmentId, type ProjectId } from "@t3tools/contracts"; +import { useState } from "react"; import { readEnvironmentScope } from "../../state/session"; import { environmentServerConfigsAtom } from "../../state/server"; @@ -15,50 +18,79 @@ import { useSettingsWriter } from "../settings/useSettingsWriter"; export function usePullRequestFeed() { const configs = useAtomValue(environmentServerConfigsAtom); const writeSettings = useSettingsWriter(); - const settings = [...configs.values()].map((config) => config.settings); - const hidden = hiddenPullRequestUrls(settings); - // Original spelling, once per link. - const hiddenUrls = [ - ...new Map( - settings.flatMap((entry) => entry.hiddenPullRequests).map((url) => [url.toLowerCase(), url]), - ).values(), - ]; + // A write replaces the whole list, so the next one must build on it before the server echoes. + const [pending, setPending] = useState>>( + () => new Map(), + ); + const hiddenOf = (environmentId: EnvironmentId) => + pending.get(environmentId) ?? configs.get(environmentId)?.settings.hiddenPullRequests ?? []; + const lists = [...configs.keys()].map((environmentId) => ({ + hiddenPullRequests: hiddenOf(environmentId), + })); + const hidden = hiddenPullRequestUrls(lists); + const hiddenUrls = hiddenPullRequestList(lists); const ruleFor = (entry: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId; }) => pullRequestFeedRule(configs.get(entry.environmentId)?.settings, entry.projectId); + /** Older servers drop the list, and a standard pairing cannot write settings. */ const canHide = (environmentId: EnvironmentId) => - configs.has(environmentId) && readEnvironmentScope(environmentId, AuthSettingsWriteScope); + configs.get(environmentId)?.environment.capabilities.pullRequestFeed === true && + readEnvironmentScope(environmentId, AuthSettingsWriteScope); - const hide = (entry: { readonly environmentId: EnvironmentId; readonly url: string }) => { - const current = configs.get(entry.environmentId)?.settings; - if (!current || !canHide(entry.environmentId)) return; + const write = (next: ReadonlyMap>) => { + if (next.size === 0) return; + setPending((current) => new Map([...current, ...next])); void writeSettings( [], - [ - { - environmentId: entry.environmentId, - patch: { - hiddenPullRequests: withHiddenPullRequest(current.hiddenPullRequests, entry.url), - }, - }, - ], + [...next].map(([environmentId, hiddenPullRequests]) => ({ + environmentId, + patch: { hiddenPullRequests }, + })), + ).finally(() => + setPending((current) => { + const settled = new Map(current); + for (const [environmentId, list] of next) { + if (settled.get(environmentId) === list) settled.delete(environmentId); + } + return settled; + }), + ); + }; + + const hide = (entry: { readonly environmentId: EnvironmentId; readonly url: string }) => { + if (!canHide(entry.environmentId)) return; + write( + new Map([ + [entry.environmentId, withHiddenPullRequest(hiddenOf(entry.environmentId), entry.url)], + ]), ); }; + const holders = (url: string) => + [...configs.keys()].filter( + (environmentId) => + canHide(environmentId) && + isPullRequestHidden( + hiddenPullRequestUrls([{ hiddenPullRequests: hiddenOf(environmentId) }]), + url, + ), + ); + // Every environment that holds the link hides it, so unhiding clears them all. const unhide = (url: string) => - void writeSettings( - [], - [...configs].flatMap(([environmentId, config]) => { - const next = withoutHiddenPullRequest(config.settings.hiddenPullRequests, url); - return next.length === config.settings.hiddenPullRequests.length || !canHide(environmentId) - ? [] - : [{ environmentId, patch: { hiddenPullRequests: next } }]; - }), + write( + new Map( + holders(url).map((environmentId) => [ + environmentId, + withoutHiddenPullRequest(hiddenOf(environmentId), url), + ]), + ), ); - return { hidden, hiddenUrls, ruleFor, canHide, hide, unhide }; + const canUnhide = (url: string) => holders(url).length > 0; + + return { hidden, hiddenUrls, ruleFor, canHide, canUnhide, hide, unhide }; } diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx index c3d071757a267..99301a52a74c2 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx @@ -61,7 +61,7 @@ vi.mock("../../state/session", () => ({ })); vi.mock("../../state/server", () => ({ serverEnvironment: { updateSettings: {} } })); vi.mock("../pull-requests/usePullRequestFeed", () => ({ - usePullRequestFeed: () => ({ hiddenUrls: [], unhide: () => {} }), + usePullRequestFeed: () => ({ hiddenUrls: [], unhide: () => {}, canUnhide: () => false }), })); vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) })); vi.mock("../../state/use-atom-command", () => ({ diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 63ffc89df63f2..f7ec828d61781 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -449,33 +449,40 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { onValueChange={(value) => write({ removeAgentCreditsOnMerge: value })} /> - - ) : null - } - > - {PULL_REQUEST_FEED_RULES.map((option, index) => ( - 0} - disabled={disabledFor("pullRequestFeed")} - onPress={() => write({ pullRequestFeed: option.value })} - /> - ))} - + {/* Older servers drop the rule. */} + {targets.every( + (target) => + target.environment.serverConfig.environment.capabilities.pullRequestFeed === + true, + ) ? ( + + ) : null + } + > + {PULL_REQUEST_FEED_RULES.map((option, index) => ( + 0} + disabled={disabledFor("pullRequestFeed")} + onPress={() => write({ pullRequestFeed: option.value })} + /> + ))} + + ) : null} {projectSelected || feed.hiddenUrls.length === 0 ? null : ( feed.unhide(url)} /> ); diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 813efbe53ea30..f3b94a1f65647 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -246,6 +246,7 @@ export const make = Effect.gen(function* () { threadAutoSettlementScope: true, threadRestartContinuation: true, projectSettingsOverrides: true, + pullRequestFeed: true, projectProviderInstanceOverrides: true, threadSnooze: true, threadForceStop: true, diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsx index 7c3bdf2b82221..777907a0fadbf 100644 --- a/apps/web/src/components/pullRequest/PullRequestRow.tsx +++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx @@ -122,6 +122,13 @@ function PullRequestRowImpl({ onContextMenu={ onRowMenu ? (event) => { + // Links and selected text keep the browser's own menu. + if ( + (event.target instanceof Element && event.target.closest("a")) || + window.getSelection()?.isCollapsed === false + ) { + return; + } event.preventDefault(); onRowMenu(entry, openLabel, { x: event.clientX, y: event.clientY }); } diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index ff952ef0e3143..6ec330174a076 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -760,6 +760,7 @@ export function PullRequestsPage() { listedPullRequestTabStatuses, groups, hiddenCount, + ruledOutCount, entriesByStatsKey, heldPullRequestsBySurface, } = pullRequestGroups({ @@ -1277,7 +1278,9 @@ export function PullRequestsPage() { search.state !== "open" || search.involvement !== "all" || scopedProjectId !== undefined || - search.host !== undefined + search.host !== undefined || + hiddenCount > 0 || + ruledOutCount > 0 } searching={typedQuery.length > 0 && (!querySettled || showingCarried)} canLoadMore={listData?.truncated === true && (canContinue || pageSize < MAX_PAGE_SIZE)} diff --git a/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts b/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts index 7f5feb8ce1fb4..6dbf8fe31558e 100644 --- a/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts @@ -119,9 +119,9 @@ export function pullRequestGroups({ // lean: projects ruled "authored" or "reviewing" are still read by the main list, and their // other rows drop here, which can leave a short page. Revisit if users report sparse pages. - const { groups, hiddenCount } = + const { groups, hiddenCount, ruledOutCount } = feed === undefined - ? { groups: grouped, hiddenCount: 0 } + ? { groups: grouped, hiddenCount: 0, ruledOutCount: 0 } : filterPullRequestFeed(grouped, { ...feed, involvement }); const entries = groups === grouped @@ -156,6 +156,7 @@ export function pullRequestGroups({ listedPullRequestTabStatuses, groups, hiddenCount, + ruledOutCount, entriesByStatsKey, heldPullRequestsBySurface, }; diff --git a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts index eb615d7b868ed..3d84488a7fedc 100644 --- a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts @@ -177,6 +177,16 @@ describe("assignment query limits", () => { expect( pullRequestProjectQueries(projects, envs("env-1"), undefined, undefined, () => true), ).toEqual([]); + // Another environment's copy of the hidden repository must not take over its listing. + expect( + pullRequestProjectQueries( + [...projects, project("b2", "env-2", "x/b")], + envs("env-1", "env-2"), + undefined, + undefined, + (candidate) => candidate.id === "b", + ), + ).toEqual([{ environmentId: "env-1", projectIds: ["a"] }]); }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts index 032a948e66a71..a264d9fabcf4b 100644 --- a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts @@ -187,8 +187,18 @@ export function pullRequestProjectQueries( readonly environmentId: EnvironmentId; readonly projectIds?: ReadonlyArray; }> { + const kept = (() => { + if (excluded === undefined) return projects; + const hidden = projects.filter(excluded); + // Another environment's copy of a hidden repository would otherwise take over its listing. + const hiddenKeys = new Set(hidden.flatMap((project) => repositoryKey(project) ?? [])); + return projects.filter((project) => { + const key = repositoryKey(project); + return !hidden.includes(project) && (key === undefined || !hiddenKeys.has(key)); + }); + })(); const assignment = assignProjectsToEnvironments( - excluded === undefined ? projects : projects.filter((project) => !excluded(project)), + kept, environmentIds, environmentIds[0], hostAvailability, diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index 773704740a349..b90a7cceca370 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -1,4 +1,5 @@ import { + hiddenPullRequestList, hiddenPullRequestUrls, isPullRequestHidden, PULL_REQUEST_FEED_RULES, @@ -6,17 +7,19 @@ import { withHiddenPullRequest, withoutHiddenPullRequest, } from "@t3tools/client-runtime/pull-request-feed"; -import type { - ContextMenuItem, - EnvironmentId, - ProjectId, - PullRequestFeedRule, +import { + AuthSettingsWriteScope, + type ContextMenuItem, + type EnvironmentId, + type ProjectId, + type PullRequestFeedRule, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { useStableCallback } from "~/hooks/useStableCallback"; import { readLocalApi } from "~/localApi"; import { useEnvironments } from "~/state/environments"; +import { readEnvironmentScope } from "~/state/session"; import { applyPendingScopedWrites, @@ -45,21 +48,24 @@ export function usePullRequestFeed() { const settingsOf = (environmentId: EnvironmentId) => environments.find((environment) => environment.environmentId === environmentId)?.serverConfig ?.settings; - const hidden = hiddenPullRequestUrls( - environments.map((environment) => environment.serverConfig?.settings), - ); + const allSettings = environments.map((environment) => environment.serverConfig?.settings); + const hidden = hiddenPullRequestUrls(allSettings); + const hiddenUrls = hiddenPullRequestList(allSettings); const ruleFor = (entry: { environmentId: EnvironmentId; projectId: ProjectId }) => pullRequestFeedRule(settingsOf(entry.environmentId), entry.projectId); - // Original spelling, newest last, once per link. - const hiddenUrls = [ - ...new Map( - environments - .flatMap((environment) => environment.serverConfig?.settings.hiddenPullRequests ?? []) - .map((url) => [url.toLowerCase(), url] as const), - ).values(), - ]; + /** Older servers drop these settings, and a standard pairing cannot write settings. */ + const canWrite = (environmentId: EnvironmentId) => + environments.find((environment) => environment.environmentId === environmentId)?.serverConfig + ?.environment.capabilities.pullRequestFeed === true && + readEnvironmentScope(environmentId, AuthSettingsWriteScope); + const holders = (url: string) => + environments.filter( + (environment) => + canWrite(environment.environmentId) && + isPullRequestHidden(hiddenPullRequestUrls([environment.serverConfig?.settings]), url), + ); const hide = (entry: Pick) => runPlan( @@ -72,7 +78,7 @@ export function usePullRequestFeed() { // Every environment that holds the link hides it, so unhiding clears them all. const unhide = (url: string) => - runPlan(environments, (current) => + runPlan(holders(url), (current) => planEnvironmentSettingsPatch(current, (settings) => { const next = withoutHiddenPullRequest(settings.hiddenPullRequests, url); return next.length === settings.hiddenPullRequests.length @@ -102,19 +108,22 @@ export function usePullRequestFeed() { if (!api) return; const isHidden = isPullRequestHidden(hidden, entry.url); const rule = ruleFor(entry); - const rulesSupported = - environments.find((environment) => environment.environmentId === entry.environmentId) - ?.serverConfig?.environment.capabilities.projectSettingsOverrides === true; + const writable = canWrite(entry.environmentId); const items: ContextMenuItem[] = [ { id: "copy-link", label: "Copy link", icon: "copy" }, { id: "open-external", label: openLabel }, isHidden - ? { id: "unhide", label: "Show in feed", separatorBefore: true } - : { id: "hide", label: "Hide from feed", separatorBefore: true }, + ? { + id: "unhide", + label: "Show in feed", + separatorBefore: true, + disabled: holders(entry.url).length === 0, + } + : { id: "hide", label: "Hide from feed", separatorBefore: true, disabled: !writable }, { id: "rule:all", label: `Feed for ${entry.projectTitle}`, - disabled: !rulesSupported, + disabled: !writable, children: PULL_REQUEST_FEED_RULES.map((option) => ({ id: `rule:${option.value}` as const, label: option.label, @@ -144,5 +153,7 @@ export function usePullRequestFeed() { void openRowMenu(entry, openLabel, position); }); - return { hidden, hiddenUrls, ruleFor, unhide, showRowMenu }; + const canUnhide = (url: string) => holders(url).length > 0; + + return { hidden, hiddenUrls, ruleFor, unhide, canUnhide, showRowMenu }; } diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx index 8270619899c62..48022143d92d9 100644 --- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx +++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx @@ -106,6 +106,10 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting const mixedAgentCredits = useScopedSettingsMixed(["removeAgentCreditsOnMerge"]); const mixedMergeMethod = useScopedSettingsMixed(["pullRequestMergeMethod"]); const mixedPullRequestFeed = useScopedSettingsMixed(["pullRequestFeed"]); + // Older servers drop the rule, so offer it only where every selected server stores it. + const pullRequestFeedSupported = connectedEnvironments.every( + (environment) => environment.serverConfig?.environment.capabilities.pullRequestFeed === true, + ); const modelSource = useScopedSettingSource(["defaultModelSelection"]); const isProjectScope = scope.kind === "project" || scope.kind === "checkout"; const unavailable = connectedEnvironments.length === 0; @@ -520,52 +524,54 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting } /> - - updateSettings({ pullRequestFeed: DEFAULT_SERVER_SETTINGS.pullRequestFeed }) - } - /> - ) : null - } - control={ - - } - /> + /> + ) : null + } + control={ + + } + /> + ) : null} )} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index b3c67850503b5..2e48467ca1556 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -1658,7 +1658,7 @@ export function DiffsSettingsPanel() { } function HiddenPullRequestsSetting() { - const { hiddenUrls, unhide } = usePullRequestFeed(); + const { hiddenUrls, unhide, canUnhide } = usePullRequestFeed(); return ( {link ? `${link.repository} #${link.number}` : url} - diff --git a/packages/client-runtime/src/pullRequestFeed.test.ts b/packages/client-runtime/src/pullRequestFeed.test.ts index a21c707875952..44b11e370dbde 100644 --- a/packages/client-runtime/src/pullRequestFeed.test.ts +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -3,6 +3,7 @@ import { DEFAULT_SERVER_SETTINGS, ProjectId, type PullRequestFeedRule } from "@t import { filterPullRequestFeed, + hiddenPullRequestList, pullRequestFeedGroup, pullRequestFeedRule, pullRequestFeedShows, @@ -69,19 +70,32 @@ describe("pull request feed rules", () => { expect(filterPullRequestFeed(groups, { ...options, scopedToProject: false })).toEqual({ groups: [groups[0]], hiddenCount: 1, + ruledOutCount: 1, }); expect( filterPullRequestFeed(groups, { ...options, scopedToProject: false, showHidden: true }), ).toEqual({ groups: [groups[0], { key: "others", entries: [row(projectB, "https://H/B/3")] }], hiddenCount: 1, + ruledOutCount: 1, }); expect(filterPullRequestFeed(groups, { ...options, scopedToProject: true })).toEqual({ groups: [groups[0], { key: "others", entries: [row(projectA, "https://h/a/2")] }], hiddenCount: 1, + ruledOutCount: 0, }); }); + it("lists each hidden link once across environments, in its first spelling", () => { + expect( + hiddenPullRequestList([ + { hiddenPullRequests: ["https://H/A/1"] }, + null, + { hiddenPullRequests: ["https://h/a/1", "https://h/b/2"] }, + ]), + ).toEqual(["https://H/A/1", "https://h/b/2"]); + }); + it("hides and unhides by URL regardless of case", () => { const hidden = withHiddenPullRequest(["https://h/a/1"], "https://H/A/1"); expect(hidden).toEqual(["https://H/A/1"]); diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts index 11dc987119aad..5e6f92f3f0aa5 100644 --- a/packages/client-runtime/src/pullRequestFeed.ts +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -67,15 +67,22 @@ export function pullRequestFeedShows( } } -/** Every environment's hidden list counts, so a pull request stays hidden when another serves it. */ -export function hiddenPullRequestUrls( - settings: Iterable | null | undefined>, -): ReadonlySet { - const urls = new Set(); +type HiddenSettings = Pick | null | undefined; + +/** Every environment's hidden links, once each in their first spelling, oldest first. */ +export function hiddenPullRequestList(settings: Iterable): ReadonlyArray { + const urls = new Map(); for (const entry of settings) { - for (const url of entry?.hiddenPullRequests ?? []) urls.add(url.toLowerCase()); + for (const url of entry?.hiddenPullRequests ?? []) { + if (!urls.has(url.toLowerCase())) urls.set(url.toLowerCase(), url); + } } - return urls; + return [...urls.values()]; +} + +/** Every environment's hidden list counts, so a pull request stays hidden when another serves it. */ +export function hiddenPullRequestUrls(settings: Iterable): ReadonlySet { + return new Set(hiddenPullRequestList(settings).map((url) => url.toLowerCase())); } export function isPullRequestHidden(hidden: ReadonlySet, url: string): boolean { @@ -131,18 +138,24 @@ export function filterPullRequestFeed< >( groups: ReadonlyArray, options: PullRequestFeedOptions & { readonly showHidden?: boolean }, -): { readonly groups: ReadonlyArray; readonly hiddenCount: number } { +): { + readonly groups: ReadonlyArray; + readonly hiddenCount: number; + readonly ruledOutCount: number; +} { let hiddenCount = 0; + let ruledOutCount = 0; let changed = false; const next = groups.flatMap((group) => { const entries = group.entries.filter((entry) => { const visibility = pullRequestFeedVisibility(entry, group.key, options); if (visibility === "hidden") hiddenCount += 1; + if (visibility === "rule") ruledOutCount += 1; return visibility === "shown" || (visibility === "hidden" && options.showHidden === true); }); if (entries.length === group.entries.length) return [group]; changed = true; return entries.length === 0 ? [] : [{ ...group, entries }]; }); - return { groups: changed ? next : groups, hiddenCount }; + return { groups: changed ? next : groups, hiddenCount, ruledOutCount }; } diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 603b6c6cc862d..2b55ea959eebf 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -117,6 +117,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ threadAutoSettlementScope: Schema.optionalKey(Schema.Boolean), threadRestartContinuation: Schema.optionalKey(Schema.Boolean), projectSettingsOverrides: Schema.optionalKey(Schema.Boolean), + /** Stores `pullRequestFeed` and `hiddenPullRequests`; older servers drop them. */ + pullRequestFeed: Schema.optionalKey(Schema.Boolean), /** Hide the switch when absent; older servers silently drop per-project provider patches. */ projectProviderInstanceOverrides: Schema.optionalKey(Schema.Boolean), threadSnooze: Schema.optionalKey(Schema.Boolean), From ba998d2a8cf96b8e8e7164e191e65c51e9c5baa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:33:57 +0200 Subject: [PATCH 16/48] fix(pull-requests): feed rules keep later pages and hide every repository copy Review round 1 on #31: - F1: a row a later page brings lands in Others when the first-page authored and review-requested reads miss it, so an authored-only or waiting-on-me project dropped its own rows. The feed filter now also admits a row by its own classification (`groupOf`). - F2: the Load more footer counted the main list's rows, so it vanished when rules removed all of them while partition rows still showed. It now counts the rows on screen. - F3: mobile merges copies of a pull request across environments before the rules run, so a repository hidden on one environment still came through its copy on another. Mobile now rules out every copy of a repository that some environment's hidden project lists, matched on host and repository. Co-Authored-By: Claude Opus 5.5 --- .../pull-requests/PullRequestsScreen.tsx | 5 ++ .../pullRequest/PullRequestsPage.tsx | 3 +- .../pullRequest/pullRequestList.logic.test.ts | 29 ++++++++++++ .../pullRequestListGroups.logic.ts | 8 +++- .../src/pullRequestFeed.test.ts | 46 +++++++++++++++++++ .../client-runtime/src/pullRequestFeed.ts | 36 +++++++++++++-- 6 files changed, 119 insertions(+), 8 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index ef89200390f3a..0df613fcff1ee 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -34,9 +34,11 @@ import { usePullRequestListControls } from "./usePullRequestListControls"; import { usePullRequestListActions } from "./usePullRequestListActions"; import { usePullRequestFeed } from "./usePullRequestFeed"; import { + hiddenPullRequestRepositories, isPullRequestHidden, pullRequestFeedGroup, pullRequestFeedVisibility, + pullRequestRepositoryKey, } from "@t3tools/client-runtime/pull-request-feed"; import { filterPullRequestList, @@ -199,6 +201,8 @@ export function PullRequestsScreen( const feed = usePullRequestFeed(); const [showHidden, setShowHidden] = useState(false); const viewers = result.data?.viewers ?? {}; + // Read before the list merges copies, so a repository hidden on one environment leaves them all. + const hiddenRepositories = hiddenPullRequestRepositories(result.entries, feed.ruleFor); const visibilities = entries.map((entry) => pullRequestFeedVisibility( entry, @@ -208,6 +212,7 @@ export function PullRequestsScreen( involvement: controls.involvement, ruleFor: feed.ruleFor, hidden: feed.hidden, + repositoryHidden: (row) => hiddenRepositories.has(pullRequestRepositoryKey(row)), }, ), ); diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index 6ec330174a076..edbd4a6ea95de 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -756,7 +756,6 @@ export function PullRequestsPage() { const feed = usePullRequestFeed(); const [showHidden, setShowHidden] = useState(false); const { - entries, listedPullRequestTabStatuses, groups, hiddenCount, @@ -1322,7 +1321,7 @@ export function PullRequestsPage() {
) : null} - {listData?.truncated && entries.length > 0 ? ( + {listData?.truncated && shownCount > 0 ? (
{loadingMore ? ( diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts index 3a4705a3fe479..675cc44019fca 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts @@ -719,6 +719,35 @@ describe("the priority groups against a paginated feed", () => { expect(combined.heldPullRequestsBySurface.size).toBe(2); expect(groupsFor(true).entries.map((row) => row.number)).toEqual([2, 1, 3]); }); + + it("keeps an authored-only project's own row that a later page puts in Others", () => { + const fromLaterPage = authoredRow(7001, "2026-08-11T08:00:00Z"); + const { entries } = pullRequestGroups({ + known: [fromLaterPage, entry({ number: 7002 })], + baseline: undefined, + providers: [], + viewers: VIEWERS, + involvement: "all", + localFilters: {}, + hasLocalFilters: false, + text: "", + answeredLocally: false, + baselineEmpty: false, + held: undefined, + // The first-page partitions do not hold the row the feed's later page brought. + authored: [], + reviewing: [], + partitionsWanted: true, + feed: { + scopedToProject: false, + ruleFor: () => "authored", + hidden: new Set(), + showHidden: false, + }, + }); + + expect(entries.map((row) => row.number)).toEqual([7001]); + }); }); describe("pull request list overrides", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts b/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts index 6dbf8fe31558e..25465e1edc39c 100644 --- a/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts @@ -1,5 +1,6 @@ import { filterPullRequestFeed, + pullRequestFeedGroup, type PullRequestFeedOptions, } from "@t3tools/client-runtime/pull-request-feed"; import type { @@ -122,7 +123,12 @@ export function pullRequestGroups({ const { groups, hiddenCount, ruledOutCount } = feed === undefined ? { groups: grouped, hiddenCount: 0, ruledOutCount: 0 } - : filterPullRequestFeed(grouped, { ...feed, involvement }); + : filterPullRequestFeed(grouped, { + ...feed, + involvement, + // Rows a later page brings land in Others when the first-page partitions miss them. + groupOf: (entry) => pullRequestFeedGroup(entry, pullRequestEntryViewer(entry, viewers)), + }); const entries = groups === grouped ? searched diff --git a/packages/client-runtime/src/pullRequestFeed.test.ts b/packages/client-runtime/src/pullRequestFeed.test.ts index 44b11e370dbde..26da8b9ebfa65 100644 --- a/packages/client-runtime/src/pullRequestFeed.test.ts +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -4,6 +4,9 @@ import { DEFAULT_SERVER_SETTINGS, ProjectId, type PullRequestFeedRule } from "@t import { filterPullRequestFeed, hiddenPullRequestList, + hiddenPullRequestRepositories, + pullRequestFeedVisibility, + pullRequestRepositoryKey, pullRequestFeedGroup, pullRequestFeedRule, pullRequestFeedShows, @@ -86,6 +89,49 @@ describe("pull request feed rules", () => { }); }); + it.each<[string, PullRequestFeedRule, PullRequestFeedGroup, PullRequestFeedGroup, boolean]>([ + ["admits a row its own group admits", "authored", "others", "authored", true], + ["admits a row its list group admits", "reviewing", "reviewRequested", "others", true], + ["drops a row neither group admits", "authored", "others", "reviewRequested", false], + ])("%s", (_, rule, listGroup, ownGroup, shown) => { + expect( + pullRequestFeedVisibility({ url: "https://h/a/1" }, listGroup, { + scopedToProject: false, + involvement: "all", + ruleFor: () => rule, + hidden: new Set(), + groupOf: () => ownGroup, + }), + ).toBe(shown ? "shown" : "rule"); + }); + + it("rules out every environment's copy of a repository one environment hides", () => { + const rows = [ + { environmentId: "env-1", host: "github.com", repository: "X/A", url: "https://h/a/1" }, + { environmentId: "env-2", host: "GitHub.com", repository: "x/a", url: "https://h/a/2" }, + { environmentId: "env-2", host: "github.com", repository: "x/b", url: "https://h/b/3" }, + ]; + const hiddenRepositories = hiddenPullRequestRepositories(rows, (row) => + row.environmentId === "env-1" ? "hidden" : "all", + ); + const options = { + scopedToProject: false, + involvement: "all" as const, + ruleFor: () => "all" as const, + hidden: new Set(), + repositoryHidden: (row: (typeof rows)[number]) => + hiddenRepositories.has(pullRequestRepositoryKey(row)), + }; + expect(rows.map((row) => pullRequestFeedVisibility(row, "others", options))).toEqual([ + "rule", + "rule", + "shown", + ]); + expect( + pullRequestFeedVisibility(rows[1]!, "others", { ...options, scopedToProject: true }), + ).toBe("shown"); + }); + it("lists each hidden link once across environments, in its first spelling", () => { expect( hiddenPullRequestList([ diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts index 5e6f92f3f0aa5..e01116daea394 100644 --- a/packages/client-runtime/src/pullRequestFeed.ts +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -112,6 +112,29 @@ export interface PullRequestFeedOptions { readonly involvement: PullRequestInvolvement; readonly ruleFor: (entry: Entry) => PullRequestFeedRule; readonly hidden: ReadonlySet; + /** The row's own group, when the list may file it under another one. */ + readonly groupOf?: (entry: Entry) => PullRequestFeedGroup; + /** A repository another environment's project hides, read before copies merge. */ + readonly repositoryHidden?: (entry: Entry) => boolean; +} + +export const pullRequestRepositoryKey = (entry: { + readonly host: string; + readonly repository: string; +}): string => `${entry.host.toLowerCase()} ${entry.repository.toLowerCase()}`; + +/** Repositories some environment's `hidden` project lists, keyed by host and repository. */ +export function hiddenPullRequestRepositories< + Entry extends { readonly host: string; readonly repository: string }, +>( + entries: ReadonlyArray, + ruleFor: (entry: Entry) => PullRequestFeedRule, +): ReadonlySet { + return new Set( + entries.flatMap((entry) => + ruleFor(entry) === "hidden" ? [pullRequestRepositoryKey(entry)] : [], + ), + ); } /** `rule` drops the row silently; `hidden` is a row the user hid and can show again. */ @@ -120,11 +143,14 @@ export function pullRequestFeedVisibility, ): "shown" | "rule" | "hidden" { - if ( - !options.scopedToProject && - !pullRequestFeedShows(options.ruleFor(entry), group, options.involvement) - ) { - return "rule"; + if (!options.scopedToProject) { + const rule = options.ruleFor(entry); + const admitted = + options.repositoryHidden?.(entry) !== true && + (pullRequestFeedShows(rule, group, options.involvement) || + (options.groupOf !== undefined && + pullRequestFeedShows(rule, options.groupOf(entry), options.involvement))); + if (!admitted) return "rule"; } return isPullRequestHidden(options.hidden, entry.url) ? "hidden" : "shown"; } From ddcb8a96324e0a8d7ba0df9fd9fddb79573da8fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:43:12 +0200 Subject: [PATCH 17/48] fix(mobile): hide every copy of a hidden repository by its project key Mobile learned hidden repositories from loaded rows, so a repository hidden on one environment still showed through another environment's copy when the hiding environment had returned no row for it (a truncated page or an offline environment). The shared `pullRequestRepositoryHidden` now matches the projects' repository keys, as the web query assignment does. This also removes the per-row scan on each render and the second repository key. Co-Authored-By: Claude Opus 5.5 --- .../pull-requests/PullRequestsScreen.tsx | 12 +++--- .../src/pullRequestFeed.test.ts | 30 ++++++++----- .../client-runtime/src/pullRequestFeed.ts | 42 ++++++++++++------- 3 files changed, 52 insertions(+), 32 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index 0df613fcff1ee..f8b68dff5733f 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -34,11 +34,10 @@ import { usePullRequestListControls } from "./usePullRequestListControls"; import { usePullRequestListActions } from "./usePullRequestListActions"; import { usePullRequestFeed } from "./usePullRequestFeed"; import { - hiddenPullRequestRepositories, isPullRequestHidden, pullRequestFeedGroup, pullRequestFeedVisibility, - pullRequestRepositoryKey, + pullRequestRepositoryHidden, } from "@t3tools/client-runtime/pull-request-feed"; import { filterPullRequestList, @@ -201,8 +200,11 @@ export function PullRequestsScreen( const feed = usePullRequestFeed(); const [showHidden, setShowHidden] = useState(false); const viewers = result.data?.viewers ?? {}; - // Read before the list merges copies, so a repository hidden on one environment leaves them all. - const hiddenRepositories = hiddenPullRequestRepositories(result.entries, feed.ruleFor); + const repositoryHidden = pullRequestRepositoryHidden( + allProjects, + (project) => + feed.ruleFor({ environmentId: project.environmentId, projectId: project.id }) === "hidden", + ); const visibilities = entries.map((entry) => pullRequestFeedVisibility( entry, @@ -212,7 +214,7 @@ export function PullRequestsScreen( involvement: controls.involvement, ruleFor: feed.ruleFor, hidden: feed.hidden, - repositoryHidden: (row) => hiddenRepositories.has(pullRequestRepositoryKey(row)), + repositoryHidden, }, ), ); diff --git a/packages/client-runtime/src/pullRequestFeed.test.ts b/packages/client-runtime/src/pullRequestFeed.test.ts index 26da8b9ebfa65..4e0ccb591ca08 100644 --- a/packages/client-runtime/src/pullRequestFeed.test.ts +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -4,9 +4,8 @@ import { DEFAULT_SERVER_SETTINGS, ProjectId, type PullRequestFeedRule } from "@t import { filterPullRequestFeed, hiddenPullRequestList, - hiddenPullRequestRepositories, pullRequestFeedVisibility, - pullRequestRepositoryKey, + pullRequestRepositoryHidden, pullRequestFeedGroup, pullRequestFeedRule, pullRequestFeedShows, @@ -106,22 +105,31 @@ describe("pull request feed rules", () => { }); it("rules out every environment's copy of a repository one environment hides", () => { - const rows = [ - { environmentId: "env-1", host: "github.com", repository: "X/A", url: "https://h/a/1" }, - { environmentId: "env-2", host: "GitHub.com", repository: "x/a", url: "https://h/a/2" }, - { environmentId: "env-2", host: "github.com", repository: "x/b", url: "https://h/b/3" }, - ]; - const hiddenRepositories = hiddenPullRequestRepositories(rows, (row) => - row.environmentId === "env-1" ? "hidden" : "all", + const project = (environmentId: string, id: string, canonicalKey: string) => ({ + id: ProjectId.make(id), + environmentId, + repositoryIdentity: { canonicalKey }, + }); + const repositoryHidden = pullRequestRepositoryHidden( + [ + project("env-1", "a1", "github.com/X/A"), + project("env-2", "a2", "github.com/x/a"), + project("env-2", "b2", "github.com/x/b"), + ], + (candidate) => candidate.environmentId === "env-1" && candidate.id === "a1", ); const options = { scopedToProject: false, involvement: "all" as const, ruleFor: () => "all" as const, hidden: new Set(), - repositoryHidden: (row: (typeof rows)[number]) => - hiddenRepositories.has(pullRequestRepositoryKey(row)), + repositoryHidden, }; + const rows = [ + { environmentId: "env-1", projectId: ProjectId.make("a1"), url: "https://h/a/1" }, + { environmentId: "env-2", projectId: ProjectId.make("a2"), url: "https://h/a/2" }, + { environmentId: "env-2", projectId: ProjectId.make("b2"), url: "https://h/b/3" }, + ]; expect(rows.map((row) => pullRequestFeedVisibility(row, "others", options))).toEqual([ "rule", "rule", diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts index e01116daea394..b6effa252df13 100644 --- a/packages/client-runtime/src/pullRequestFeed.ts +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -118,23 +118,33 @@ export interface PullRequestFeedOptions { readonly repositoryHidden?: (entry: Entry) => boolean; } -export const pullRequestRepositoryKey = (entry: { - readonly host: string; - readonly repository: string; -}): string => `${entry.host.toLowerCase()} ${entry.repository.toLowerCase()}`; - -/** Repositories some environment's `hidden` project lists, keyed by host and repository. */ -export function hiddenPullRequestRepositories< - Entry extends { readonly host: string; readonly repository: string }, +/** + * Whether a row's repository is one some environment's project hides, matched on the projects' + * repository keys like the web query assignment, so every environment's copy leaves the feed. + */ +export function pullRequestRepositoryHidden< + Project extends { + readonly id: ProjectId; + readonly environmentId: string; + readonly repositoryIdentity?: { readonly canonicalKey?: string | undefined } | null | undefined; + }, >( - entries: ReadonlyArray, - ruleFor: (entry: Entry) => PullRequestFeedRule, -): ReadonlySet { - return new Set( - entries.flatMap((entry) => - ruleFor(entry) === "hidden" ? [pullRequestRepositoryKey(entry)] : [], - ), - ); + projects: ReadonlyArray, + isHidden: (project: Project) => boolean, +): (entry: { readonly environmentId: string; readonly projectId: ProjectId }) => boolean { + const keys = new Map(); + const hidden = new Set(); + for (const project of projects) { + const key = project.repositoryIdentity?.canonicalKey?.toLowerCase(); + if (!key) continue; + keys.set(`${project.environmentId} ${project.id}`, key); + if (isHidden(project)) hidden.add(key); + } + return (entry) => { + if (hidden.size === 0) return false; + const key = keys.get(`${entry.environmentId} ${entry.projectId}`); + return key !== undefined && hidden.has(key); + }; } /** `rule` drops the row silently; `hidden` is a row the user hid and can show again. */ From 99cfdee25b51e98c31936e759607287e39185298 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:59:47 +0200 Subject: [PATCH 18/48] fix(pull-requests): feed rules reach every repository copy and keep unsaved hides Review round 2 on #31: - C1: the row menu wrote the feed rule only for the row's project, so other environments' copies of the repository kept the old rule. It now writes every project that shares the repository key, as Settings does. - X1: the web feed also rules out rows whose repository any environment's project hides, and with no projects left to read the list shows no carried rows. - X2: the search empty state offers Load more while the results have more pages. - X3: mobile keeps a successful hidden-list save as the base for the next hide or unhide until the settings subscription replaces the stored list. - X4: the web empty state counts as filtered when a project is hidden. Co-Authored-By: Claude Opus 5.5 --- .../pendingHiddenPullRequests.test.ts | 15 +++++++ .../pendingHiddenPullRequests.ts | 15 +++++++ .../pull-requests/usePullRequestFeed.ts | 39 +++++++++++++------ .../features/settings/useSettingsWriter.ts | 3 ++ .../pullRequest/PullRequestListEmptyState.tsx | 5 +++ .../pullRequest/PullRequestsPage.tsx | 13 +++++-- .../pullRequest/usePullRequestFeed.ts | 32 +++++++++++---- .../src/components/settings/scopedSettings.ts | 6 +-- 8 files changed, 103 insertions(+), 25 deletions(-) create mode 100644 apps/mobile/src/features/pull-requests/pendingHiddenPullRequests.test.ts create mode 100644 apps/mobile/src/features/pull-requests/pendingHiddenPullRequests.ts diff --git a/apps/mobile/src/features/pull-requests/pendingHiddenPullRequests.test.ts b/apps/mobile/src/features/pull-requests/pendingHiddenPullRequests.test.ts new file mode 100644 index 0000000000000..6e5836adb9b7b --- /dev/null +++ b/apps/mobile/src/features/pull-requests/pendingHiddenPullRequests.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { shownHiddenList } from "./pendingHiddenPullRequests"; + +describe("hidden pull request saves", () => { + const stored = ["https://h/a/1"]; + const saved = ["https://h/a/1", "https://h/a/2"]; + + it("keeps a successful save until the subscription replaces the stored list", () => { + expect(shownHiddenList(stored, { list: saved })).toBe(saved); + expect(shownHiddenList(stored, { list: saved, savedOver: stored })).toBe(saved); + const echoed = [...saved]; + expect(shownHiddenList(echoed, { list: saved, savedOver: stored })).toBe(echoed); + }); +}); diff --git a/apps/mobile/src/features/pull-requests/pendingHiddenPullRequests.ts b/apps/mobile/src/features/pull-requests/pendingHiddenPullRequests.ts new file mode 100644 index 0000000000000..5299784f1ca80 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/pendingHiddenPullRequests.ts @@ -0,0 +1,15 @@ +/** A save of an environment's hidden list, which replaces the whole list. */ +export interface PendingHiddenList { + readonly list: ReadonlyArray; + /** The stored list when the save succeeded; until the subscription replaces it, the save is newer. */ + readonly savedOver?: ReadonlyArray; +} + +/** The list later hides and unhides build on: a save in flight or not yet echoed wins. */ +export function shownHiddenList( + stored: ReadonlyArray, + pending: PendingHiddenList | undefined, +): ReadonlyArray { + if (pending === undefined) return stored; + return pending.savedOver === undefined || pending.savedOver === stored ? pending.list : stored; +} diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts index 663eef62ab597..93a253153cc05 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts @@ -1,4 +1,4 @@ -import { useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { hiddenPullRequestList, hiddenPullRequestUrls, @@ -8,22 +8,25 @@ import { withoutHiddenPullRequest, } from "@t3tools/client-runtime/pull-request-feed"; import { AuthSettingsWriteScope, type EnvironmentId, type ProjectId } from "@t3tools/contracts"; -import { useState } from "react"; +import { use, useState } from "react"; import { readEnvironmentScope } from "../../state/session"; import { environmentServerConfigsAtom } from "../../state/server"; import { useSettingsWriter } from "../settings/useSettingsWriter"; +import { shownHiddenList, type PendingHiddenList } from "./pendingHiddenPullRequests"; /** Per-project feed rules and hidden pull requests, read from every environment's settings. */ export function usePullRequestFeed() { const configs = useAtomValue(environmentServerConfigsAtom); const writeSettings = useSettingsWriter(); - // A write replaces the whole list, so the next one must build on it before the server echoes. - const [pending, setPending] = useState>>( + const registry = use(RegistryContext); + const [pending, setPending] = useState>( () => new Map(), ); + const storedOf = (environmentId: EnvironmentId) => + configs.get(environmentId)?.settings.hiddenPullRequests ?? []; const hiddenOf = (environmentId: EnvironmentId) => - pending.get(environmentId) ?? configs.get(environmentId)?.settings.hiddenPullRequests ?? []; + shownHiddenList(storedOf(environmentId), pending.get(environmentId)); const lists = [...configs.keys()].map((environmentId) => ({ hiddenPullRequests: hiddenOf(environmentId), })); @@ -42,22 +45,34 @@ export function usePullRequestFeed() { const write = (next: ReadonlyMap>) => { if (next.size === 0) return; - setPending((current) => new Map([...current, ...next])); + setPending((current) => { + const updated = new Map(current); + for (const [environmentId, list] of next) updated.set(environmentId, { list }); + return updated; + }); void writeSettings( [], [...next].map(([environmentId, hiddenPullRequests]) => ({ environmentId, patch: { hiddenPullRequests }, })), - ).finally(() => + ).then((failed) => { + // Read now: this render's settings may already be older than the reply. + const latest = registry.get(environmentServerConfigsAtom); setPending((current) => { - const settled = new Map(current); + const updated = new Map(current); for (const [environmentId, list] of next) { - if (settled.get(environmentId) === list) settled.delete(environmentId); + if (updated.get(environmentId)?.list !== list) continue; + if (failed.includes(environmentId)) updated.delete(environmentId); + else + updated.set(environmentId, { + list, + savedOver: latest.get(environmentId)?.settings.hiddenPullRequests ?? [], + }); } - return settled; - }), - ); + return updated; + }); + }); }; const hide = (entry: { readonly environmentId: EnvironmentId; readonly url: string }) => { diff --git a/apps/mobile/src/features/settings/useSettingsWriter.ts b/apps/mobile/src/features/settings/useSettingsWriter.ts index aebd453c2ce26..7b95eeedc1109 100644 --- a/apps/mobile/src/features/settings/useSettingsWriter.ts +++ b/apps/mobile/src/features/settings/useSettingsWriter.ts @@ -40,5 +40,8 @@ export function useSettingsWriter() { if (failures.length > 0) { Dialog.alert("Could not save settings", failures.join("\n\n")); } + return writes.flatMap((entry, index) => + outcomes[index] === null ? [] : [entry.environmentId], + ); }; } diff --git a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx index 4454d8cd0f441..391b7de0e5807 100644 --- a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx @@ -110,6 +110,11 @@ export function PullRequestListEmptyState({
+ {canLoadMore ? ( + + ) : null}
) : null} - {listData?.truncated && shownCount > 0 ? ( + {/* The error view replaces an emptied page, so it keeps this footer's way to more pages. */} + {listData?.truncated && (shownCount > 0 || listError !== null) ? (
{loadingMore ? ( diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts index 675cc44019fca..3eaf8d6ebe1d6 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts @@ -706,7 +706,7 @@ describe("the priority groups against a paginated feed", () => { partitionsWanted: false, feed: { scopedToProject, - ruleFor: (row) => (row.projectId === "project-1" ? "authored" : "all"), + rulesFor: (row) => [row.projectId === "project-1" ? "authored" : "all"], hidden: new Set([hiddenRow.url]), showHidden: false, }, @@ -740,7 +740,7 @@ describe("the priority groups against a paginated feed", () => { partitionsWanted: true, feed: { scopedToProject: false, - ruleFor: () => "authored", + rulesFor: () => ["authored"], hidden: new Set(), showHidden: false, }, diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index a5e6d8378afeb..fd5c63bcdfb7d 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -7,6 +7,7 @@ import { pullRequestFeedRule, pullRequestProjectHidesRepository, pullRequestRepositoryHidden, + pullRequestRepositoryRules, } from "@t3tools/client-runtime/pull-request-feed"; import { AuthSettingsWriteScope, @@ -76,6 +77,13 @@ export function usePullRequestFeed() { ); // A repository one environment hides leaves every environment's copy, including carried rows. const repositoryHidden = pullRequestRepositoryHidden(projects, hidesRepository); + // A row shows when any connected copy of its repository allows it, as on mobile. + const rulesFor = pullRequestRepositoryRules( + projects, + (project) => ruleFor({ environmentId: project.environmentId, projectId: project.id }), + (project) => connected.has(project.environmentId), + ruleFor, + ); // Every environment that holds the link hides it, so all of them must be able to clear it. const holders = (url: string) => environments.filter((environment) => @@ -191,6 +199,7 @@ export function usePullRequestFeed() { hidden, hiddenUrls, ruleFor, + rulesFor, hidesRepository, repositoryHidden, unhide, diff --git a/packages/client-runtime/src/pullRequestFeed.test.ts b/packages/client-runtime/src/pullRequestFeed.test.ts index 4564449bf9993..5cf4303b2fd75 100644 --- a/packages/client-runtime/src/pullRequestFeed.test.ts +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -9,6 +9,7 @@ import { pullRequestFeedVisibility, pullRequestProjectHidesRepository, pullRequestRepositoryHidden, + pullRequestRepositoryRules, pullRequestFeedGroup, pullRequestFeedRule, pullRequestFeedShows, @@ -66,7 +67,7 @@ describe("pull request feed rules", () => { const rules: Record = { [projectA]: "authored" }; const options = { involvement: "all" as const, - ruleFor: (entry: { projectId: ProjectId }) => rules[entry.projectId] ?? "all", + rulesFor: (entry: { projectId: ProjectId }) => [rules[entry.projectId] ?? "all"], hidden: new Set(["https://h/b/3"]), }; @@ -98,7 +99,7 @@ describe("pull request feed rules", () => { pullRequestFeedVisibility({ url: "https://h/a/1" }, listGroup, { scopedToProject: false, involvement: "all", - ruleFor: () => rule, + rulesFor: () => [rule], hidden: new Set(), groupOf: () => ownGroup, }), @@ -130,7 +131,7 @@ describe("pull request feed rules", () => { const options = { scopedToProject: false, involvement: "all" as const, - ruleFor: () => "all" as const, + rulesFor: () => ["all" as const], hidden: new Set(), repositoryHidden, }; @@ -149,6 +150,30 @@ describe("pull request feed rules", () => { ).toBe("shown"); }); + it("shows a row when any copy of its repository allows it", () => { + const project = (environmentId: string, id: string) => ({ + id: ProjectId.make(id), + environmentId, + repositoryIdentity: { canonicalKey: "github.com/x/a" }, + }); + const rulesFor = pullRequestRepositoryRules( + [project("env-1", "a1"), project("env-2", "a2")], + (candidate) => (candidate.environmentId === "env-1" ? "authored" : "all"), + () => true, + () => "authored", + ); + const row = { environmentId: "env-1", projectId: ProjectId.make("a1"), url: "https://h/a/9" }; + // Another author's pull request, read through the authored-only copy. + expect( + pullRequestFeedVisibility(row, "others", { + scopedToProject: false, + involvement: "all", + rulesFor, + hidden: new Set(), + }), + ).toBe("shown"); + }); + it("reads every environment's hidden links, regardless of case", () => { const settings = [ { hiddenPullRequests: { "https://h/a/1": "https://H/A/1" } }, diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts index 72b01fce4b578..b4e99e8b30f14 100644 --- a/packages/client-runtime/src/pullRequestFeed.ts +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -99,7 +99,8 @@ export interface PullRequestFeedOptions { /** Rules apply only to the combined feed, not when the list shows one project. */ readonly scopedToProject: boolean; readonly involvement: PullRequestInvolvement; - readonly ruleFor: (entry: Entry) => PullRequestFeedRule; + /** The rules of the row's copies; the row shows when any of them shows it. */ + readonly rulesFor: (entry: Entry) => ReadonlyArray; readonly hidden: ReadonlySet; /** The row's own group, when the list may file it under another one. */ readonly groupOf?: (entry: Entry) => PullRequestFeedGroup; @@ -122,13 +123,7 @@ export function pullRequestProjectHidesRepository( * Whether a row's repository is one some environment's project hides, matched on the projects' * repository keys like the web query assignment, so every environment's copy leaves the feed. */ -export function pullRequestRepositoryHidden< - Project extends { - readonly id: ProjectId; - readonly environmentId: string; - readonly repositoryIdentity?: { readonly canonicalKey?: string | undefined } | null | undefined; - }, ->( +export function pullRequestRepositoryHidden( projects: ReadonlyArray, isHidden: (project: Project) => boolean, ): (entry: { readonly environmentId: string; readonly projectId: ProjectId }) => boolean { @@ -147,6 +142,42 @@ export function pullRequestRepositoryHidden< }; } +type RepositoryProject = { + readonly id: ProjectId; + readonly environmentId: string; + readonly repositoryIdentity?: { readonly canonicalKey?: string | undefined } | null | undefined; +}; + +/** + * A row's own rule plus the rules of every counted copy of its repository, matched on the same + * repository key as `pullRequestRepositoryHidden`, so a row shows when any copy's rule allows it. + */ +export function pullRequestRepositoryRules< + Project extends RepositoryProject, + Entry extends { readonly environmentId: string; readonly projectId: ProjectId }, +>( + projects: ReadonlyArray, + ruleOf: (project: Project) => PullRequestFeedRule, + counts: (project: Project) => boolean, + ownRuleOf: (entry: Entry) => PullRequestFeedRule, +): (entry: Entry) => ReadonlyArray { + const keys = new Map(); + const rules = new Map(); + for (const project of projects) { + const key = project.repositoryIdentity?.canonicalKey?.toLowerCase(); + if (!key) continue; + keys.set(`${project.environmentId} ${project.id}`, key); + if (!counts(project)) continue; + const held = rules.get(key); + if (held === undefined) rules.set(key, [ruleOf(project)]); + else held.push(ruleOf(project)); + } + return (entry) => { + const key = keys.get(`${entry.environmentId} ${entry.projectId}`); + return [ownRuleOf(entry), ...(key === undefined ? [] : (rules.get(key) ?? []))]; + }; +} + /** `rule` drops the row silently; `hidden` is a row the user hid and can show again. */ export function pullRequestFeedVisibility( entry: Entry, @@ -154,12 +185,16 @@ export function pullRequestFeedVisibility, ): "shown" | "rule" | "hidden" { if (!options.scopedToProject) { - const rule = options.ruleFor(entry); + const ownGroup = options.groupOf?.(entry); const admitted = options.repositoryHidden?.(entry) !== true && - (pullRequestFeedShows(rule, group, options.involvement) || - (options.groupOf !== undefined && - pullRequestFeedShows(rule, options.groupOf(entry), options.involvement))); + options + .rulesFor(entry) + .some( + (rule) => + pullRequestFeedShows(rule, group, options.involvement) || + (ownGroup !== undefined && pullRequestFeedShows(rule, ownGroup, options.involvement)), + ); if (!admitted) return "rule"; } return isPullRequestHidden(options.hidden, entry.url) ? "hidden" : "shown"; From 406487405e8994e0769df78b7a4f6956ee7f4d5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:06:31 +0200 Subject: [PATCH 29/48] fix(pull-requests): only copies the user can change admit a pull request Review of the round 7 fix: - A copy's rule now counts toward a row only when its environment is connected, can store the rule and is in the list's scope, the same copies the row menu's rule write reaches. An older server's or a read-only pairing's default "all", or a copy outside an environment-scoped list, can no longer override the user's rule. - The Load more footer beside an error shows only while more pages can load, and never under the unsupported state. - The own-group check runs only when the list group does not already admit the row; tests cover a copy that does not count and a keyless row. - The user guide says that any copy's rule can admit a pull request. Co-Authored-By: Claude Opus 5.5 --- .../features/pull-requests/PullRequestsScreen.tsx | 6 ++++-- .../features/pull-requests/usePullRequestFeed.ts | 6 +++++- .../components/pullRequest/PullRequestsPage.tsx | 13 +++++++++++-- .../components/pullRequest/usePullRequestFeed.ts | 13 ++++--------- docs/user/source-control.md | 4 +++- .../client-runtime/src/pullRequestFeed.test.ts | 11 +++++++++++ packages/client-runtime/src/pullRequestFeed.ts | 14 ++++++-------- 7 files changed, 44 insertions(+), 23 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index 672539105cd84..fcf45a5e56033 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -202,11 +202,13 @@ export function PullRequestsScreen( const [showHidden, setShowHidden] = useState(false); const viewers = result.data?.viewers ?? {}; const repositoryHidden = pullRequestRepositoryHidden(allProjects, feed.hidesRepository); - // A pull request shows when any connected copy of its repository allows it, as on web. + // A pull request shows when any copy in the list's scope allows it, as on web. const rulesFor = pullRequestRepositoryRules( allProjects, (project) => feed.ruleFor({ environmentId: project.environmentId, projectId: project.id }), - (project) => feed.isConnected(project.environmentId), + (project) => + feed.ruleCounts(project.environmentId) && + targets.some((target) => target.environmentId === project.environmentId), feed.ruleFor, ); const visibilities = entries.map((entry) => diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts index b120671d307d7..e74f0a84d5230 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts @@ -64,6 +64,10 @@ export function usePullRequestFeed() { environment.environmentId === environmentId && environment.connectionState === "connected", ); + /** A copy's rule counts toward a row only where this device could also change it. */ + const ruleCounts = (environmentId: EnvironmentId) => + isConnected(environmentId) && canHide(environmentId); + /** The one rule for which projects hide their repository, the same as on web. */ const hidesRepository = (project: { readonly environmentId: EnvironmentId; @@ -155,7 +159,7 @@ export function usePullRequestFeed() { hidden, hiddenUrls, ruleFor, - isConnected, + ruleCounts, hidesRepository, canHide, canUnhide, diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index fa9361a644c80..07b414007dc98 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -68,6 +68,7 @@ import { INVOLVEMENT_TABS, SORT_OPTIONS, STATE_TABS } from "./pullRequestListOpt import { PullRequestsColumn } from "./PullRequestsColumn"; import { PullRequestListGroups } from "./PullRequestListGroups"; import { usePullRequestFeed } from "./usePullRequestFeed"; +import { pullRequestRepositoryRules } from "@t3tools/client-runtime/pull-request-feed"; import { pullRequestPanelReference } from "./usePullRequestDetail"; import { usePullRequestIntentPrefetch } from "./usePullRequestIntentPrefetch"; import { @@ -791,7 +792,13 @@ export function PullRequestsPage() { partitionsWanted, feed: { scopedToProject: scopedProjectId !== undefined, - rulesFor: feed.rulesFor, + // Only copies in the list's scope: a row shows when any of their rules allows it. + rulesFor: pullRequestRepositoryRules( + projects, + (project) => feed.ruleFor({ environmentId: project.environmentId, projectId: project.id }), + (project) => feed.ruleCounts(project.environmentId), + feed.ruleFor, + ), hidden: feed.hidden, repositoryHidden: feed.repositoryHidden, showHidden, @@ -1329,7 +1336,9 @@ export function PullRequestsPage() {
) : null} {/* The error view replaces an emptied page, so it keeps this footer's way to more pages. */} - {listData?.truncated && (shownCount > 0 || listError !== null) ? ( + {pullRequestsSupported && + listData?.truncated && + (shownCount > 0 || (listError !== null && (canContinue || pageSize < MAX_PAGE_SIZE))) ? (
{loadingMore ? ( diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index fd5c63bcdfb7d..0a8efcfc10eaf 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -7,7 +7,6 @@ import { pullRequestFeedRule, pullRequestProjectHidesRepository, pullRequestRepositoryHidden, - pullRequestRepositoryRules, } from "@t3tools/client-runtime/pull-request-feed"; import { AuthSettingsWriteScope, @@ -77,13 +76,9 @@ export function usePullRequestFeed() { ); // A repository one environment hides leaves every environment's copy, including carried rows. const repositoryHidden = pullRequestRepositoryHidden(projects, hidesRepository); - // A row shows when any connected copy of its repository allows it, as on mobile. - const rulesFor = pullRequestRepositoryRules( - projects, - (project) => ruleFor({ environmentId: project.environmentId, projectId: project.id }), - (project) => connected.has(project.environmentId), - ruleFor, - ); + /** A copy's rule counts toward a row only where the row menu's rule write reaches it too. */ + const ruleCounts = (environmentId: EnvironmentId) => + connected.has(environmentId) && canWrite(environmentId); // Every environment that holds the link hides it, so all of them must be able to clear it. const holders = (url: string) => environments.filter((environment) => @@ -199,7 +194,7 @@ export function usePullRequestFeed() { hidden, hiddenUrls, ruleFor, - rulesFor, + ruleCounts, hidesRepository, repositoryHidden, unhide, diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 4b274ac173f73..46e45f6dfee1d 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -250,7 +250,9 @@ When the list shows all projects, each project adds pull requests by its **Pull rule: **All pull requests**, **Waiting on me** (your review is requested), **Authored by me**, or **Hidden**. Set the default in Settings → Source control, and override it for a project with the project selector there. On web and desktop you can also right-click a pull request and choose a -rule for its project. Picking one project in the list's project filter shows all its pull +rule for its project. When the same repository is a project on several connected environments, +the list shows a pull request if any of their rules allows it, and **Hidden** on any of them +hides the repository. Picking one project in the list's project filter shows all its pull requests. To hide one pull request, right-click it on web and desktop, or touch and hold it on mobile, and diff --git a/packages/client-runtime/src/pullRequestFeed.test.ts b/packages/client-runtime/src/pullRequestFeed.test.ts index 5cf4303b2fd75..5b828dc3c10bb 100644 --- a/packages/client-runtime/src/pullRequestFeed.test.ts +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -172,6 +172,17 @@ describe("pull request feed rules", () => { hidden: new Set(), }), ).toBe("shown"); + // A copy that does not count, such as an offline one, adds no rule; a keyless row keeps its own. + const counted = pullRequestRepositoryRules( + [project("env-1", "a1"), project("env-2", "a2")], + (candidate) => (candidate.environmentId === "env-1" ? "authored" : "all"), + (candidate) => candidate.environmentId === "env-1", + () => "authored", + ); + expect(counted(row)).toEqual(["authored", "authored"]); + expect(counted({ environmentId: "env-3", projectId: ProjectId.make("x") })).toEqual([ + "authored", + ]); }); it("reads every environment's hidden links, regardless of case", () => { diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts index b4e99e8b30f14..7b74da46fddc4 100644 --- a/packages/client-runtime/src/pullRequestFeed.ts +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -185,16 +185,14 @@ export function pullRequestFeedVisibility, ): "shown" | "rule" | "hidden" { if (!options.scopedToProject) { - const ownGroup = options.groupOf?.(entry); + let ownGroup: PullRequestFeedGroup | undefined; const admitted = options.repositoryHidden?.(entry) !== true && - options - .rulesFor(entry) - .some( - (rule) => - pullRequestFeedShows(rule, group, options.involvement) || - (ownGroup !== undefined && pullRequestFeedShows(rule, ownGroup, options.involvement)), - ); + options.rulesFor(entry).some((rule) => { + if (pullRequestFeedShows(rule, group, options.involvement)) return true; + ownGroup ??= options.groupOf?.(entry); + return ownGroup !== undefined && pullRequestFeedShows(rule, ownGroup, options.involvement); + }); if (!admitted) return "rule"; } return isPullRequestHidden(options.hidden, entry.url) ? "hidden" : "shown"; From b9803ad8d7f4cbcb139884886ddc992a249b6204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:37:29 +0200 Subject: [PATCH 30/48] fix(client-runtime): a copy outside the feed no longer widens a narrower rule The row's own rule was always counted, so a non-counting copy's default "all" defeated a narrower rule on a counted copy. Use the own rule only when no copy of the repository counts. Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/pullRequestFeed.test.ts | 8 ++++++-- packages/client-runtime/src/pullRequestFeed.ts | 8 +++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/client-runtime/src/pullRequestFeed.test.ts b/packages/client-runtime/src/pullRequestFeed.test.ts index 5b828dc3c10bb..45354a525fda5 100644 --- a/packages/client-runtime/src/pullRequestFeed.test.ts +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -177,9 +177,13 @@ describe("pull request feed rules", () => { [project("env-1", "a1"), project("env-2", "a2")], (candidate) => (candidate.environmentId === "env-1" ? "authored" : "all"), (candidate) => candidate.environmentId === "env-1", - () => "authored", + (entry) => (entry.environmentId === "env-2" ? "all" : "authored"), ); - expect(counted(row)).toEqual(["authored", "authored"]); + expect(counted(row)).toEqual(["authored"]); + // The row's own copy does not count, so its default "all" must not widen a counted narrower rule. + expect(counted({ environmentId: "env-2", projectId: ProjectId.make("a2") })).toEqual([ + "authored", + ]); expect(counted({ environmentId: "env-3", projectId: ProjectId.make("x") })).toEqual([ "authored", ]); diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts index 7b74da46fddc4..439a51d26ccb7 100644 --- a/packages/client-runtime/src/pullRequestFeed.ts +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -149,8 +149,9 @@ type RepositoryProject = { }; /** - * A row's own rule plus the rules of every counted copy of its repository, matched on the same - * repository key as `pullRequestRepositoryHidden`, so a row shows when any copy's rule allows it. + * The rules of every counted copy of a row's repository, matched on the same repository key as + * `pullRequestRepositoryHidden`, so a row shows when any copy's rule allows it. The row's own rule + * applies only when no copy counts. */ export function pullRequestRepositoryRules< Project extends RepositoryProject, @@ -174,7 +175,8 @@ export function pullRequestRepositoryRules< } return (entry) => { const key = keys.get(`${entry.environmentId} ${entry.projectId}`); - return [ownRuleOf(entry), ...(key === undefined ? [] : (rules.get(key) ?? []))]; + const counted = key === undefined ? undefined : rules.get(key); + return counted ?? [ownRuleOf(entry)]; }; } From 6af11b426d6eeaa9efec2333673946b0a77cb270 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:41:13 +0200 Subject: [PATCH 31/48] fix(web): the row menu shows and edits the feed rule that decides the row The menu checked the row's own rule and was disabled when the row's own environment could not write, although the rule in effect now comes from the counted copies. It now checks those rules and stays enabled while any copy of the repository can take the write. Also pin the keyed fallback in a test and update the rulesFor doc. Co-Authored-By: Claude Opus 5.5 --- .../pullRequest/usePullRequestFeed.ts | 41 +++++++++++++------ .../src/pullRequestFeed.test.ts | 8 ++++ .../client-runtime/src/pullRequestFeed.ts | 2 +- 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index 0a8efcfc10eaf..73277d4a493ed 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -7,6 +7,7 @@ import { pullRequestFeedRule, pullRequestProjectHidesRepository, pullRequestRepositoryHidden, + pullRequestRepositoryRules, } from "@t3tools/client-runtime/pull-request-feed"; import { AuthSettingsWriteScope, @@ -110,11 +111,15 @@ export function usePullRequestFeed() { ); }; - // Like Settings' project scope, every environment's copy of the repository gets the rule. - const setProjectRule = ( - project: { environmentId: EnvironmentId; projectId: ProjectId }, - rule: PullRequestFeedRule, - ) => { + const rowRules = pullRequestRepositoryRules( + projects, + (project) => ruleFor({ environmentId: project.environmentId, projectId: project.id }), + (project) => ruleCounts(project.environmentId), + ruleFor, + ); + + // Like Settings' project scope, every writable copy of the repository gets the rule. + const ruleMembers = (project: { environmentId: EnvironmentId; projectId: ProjectId }) => { const repositoryKeyOf = (candidate: (typeof projects)[number] | undefined) => candidate?.repositoryIdentity?.canonicalKey?.toLowerCase(); const key = repositoryKeyOf( @@ -123,11 +128,21 @@ export function usePullRequestFeed() { candidate.environmentId === project.environmentId && candidate.id === project.projectId, ), ); - const members = key - ? projects.filter( - (candidate) => repositoryKeyOf(candidate) === key && canWrite(candidate.environmentId), - ) - : [{ id: project.projectId, environmentId: project.environmentId }]; + if (key) { + return projects.filter( + (candidate) => repositoryKeyOf(candidate) === key && canWrite(candidate.environmentId), + ); + } + return canWrite(project.environmentId) + ? [{ id: project.projectId, environmentId: project.environmentId }] + : []; + }; + + const setProjectRule = ( + project: { environmentId: EnvironmentId; projectId: ProjectId }, + rule: PullRequestFeedRule, + ) => { + const members = ruleMembers(project); runPlan(environments, (current) => planProjectOverridePatch(current, members, { pullRequestFeed: rule }), ); @@ -141,7 +156,7 @@ export function usePullRequestFeed() { const api = readLocalApi(); if (!api) return; const isHidden = isPullRequestHidden(hidden, entry.url); - const rule = ruleFor(entry); + const rules = rowRules(entry); const writable = canWrite(entry.environmentId); const items: ContextMenuItem[] = [ { id: "copy-link", label: "Copy link", icon: "copy" }, @@ -160,11 +175,11 @@ export function usePullRequestFeed() { { id: "rule:all", label: `Feed for ${entry.projectTitle}`, - disabled: !writable, + disabled: ruleMembers(entry).length === 0, children: PULL_REQUEST_FEED_RULES.map((option) => ({ id: `rule:${option.value}` as const, label: option.label, - checked: option.value === rule, + checked: rules.includes(option.value), })), }, ]; diff --git a/packages/client-runtime/src/pullRequestFeed.test.ts b/packages/client-runtime/src/pullRequestFeed.test.ts index 45354a525fda5..d34f6e45ff1d7 100644 --- a/packages/client-runtime/src/pullRequestFeed.test.ts +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -187,6 +187,14 @@ describe("pull request feed rules", () => { expect(counted({ environmentId: "env-3", projectId: ProjectId.make("x") })).toEqual([ "authored", ]); + // A keyed repository with no counted copy falls back to the row's own rule, not to no rule. + const uncounted = pullRequestRepositoryRules( + [project("env-1", "a1"), project("env-2", "a2")], + () => "authored", + () => false, + () => "reviewing", + ); + expect(uncounted(row)).toEqual(["reviewing"]); }); it("reads every environment's hidden links, regardless of case", () => { diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts index 439a51d26ccb7..c6cc05ab9d4c3 100644 --- a/packages/client-runtime/src/pullRequestFeed.ts +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -99,7 +99,7 @@ export interface PullRequestFeedOptions { /** Rules apply only to the combined feed, not when the list shows one project. */ readonly scopedToProject: boolean; readonly involvement: PullRequestInvolvement; - /** The rules of the row's copies; the row shows when any of them shows it. */ + /** The rules of the row's counted copies, else its own; the row shows when any of them shows it. */ readonly rulesFor: (entry: Entry) => ReadonlyArray; readonly hidden: ReadonlySet; /** The row's own group, when the list may file it under another one. */ From d15bdd382abf0a14667ea078311a0491371155fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:44:22 +0200 Subject: [PATCH 32/48] fix(web): the row menu reads the page's rules and writes only counted copies The menu built its own rules from every project, while the page decides rows from the projects in its scope, so the checkmarks could still differ. The page now passes its rulesFor to the menu. The rule write and the menu's enabled state use the same connected, writable copies that count, so a pick always reaches every rule that decides the row. Co-Authored-By: Claude Opus 5.5 --- .../pullRequest/PullRequestsPage.tsx | 23 +++++++++++-------- .../pullRequest/usePullRequestFeed.ts | 21 +++++------------ 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index 07b414007dc98..0f33a9604f7ab 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -80,7 +80,7 @@ import { import { pullRequestGroups, pullRequestListEntryId } from "./pullRequestListGroups.logic"; import { PullRequestListEmptyState } from "./PullRequestListEmptyState"; import { PullRequestListGhost } from "./PullRequestGhosts"; -import { type PullRequestRowTarget } from "./PullRequestRow"; +import { type PullRequestRowMenu, type PullRequestRowTarget } from "./PullRequestRow"; import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState"; import { RightPanelTabs } from "../RightPanelTabs"; import { isCommandPaletteOpen } from "~/commandPaletteBus"; @@ -758,6 +758,17 @@ export function PullRequestsPage() { const shownHeldReviewing = usePendingListEntries(overlayInput, heldPartitions?.reviewing); const scrollRef = useRef(null); const [showHidden, setShowHidden] = useState(false); + // Only copies in the list's scope: a row shows when any of their rules allows it. + const rulesFor = pullRequestRepositoryRules( + projects, + (project) => feed.ruleFor({ environmentId: project.environmentId, projectId: project.id }), + (project) => feed.ruleCounts(project.environmentId), + feed.ruleFor, + ); + // The menu checks the same rules that decide the row. + const showRowMenu: PullRequestRowMenu = useStableCallback((entry, openLabel, position) => + feed.showRowMenu(entry, openLabel, position, rulesFor(entry)), + ); const { listedPullRequestTabStatuses, groups, @@ -792,13 +803,7 @@ export function PullRequestsPage() { partitionsWanted, feed: { scopedToProject: scopedProjectId !== undefined, - // Only copies in the list's scope: a row shows when any of their rules allows it. - rulesFor: pullRequestRepositoryRules( - projects, - (project) => feed.ruleFor({ environmentId: project.environmentId, projectId: project.id }), - (project) => feed.ruleCounts(project.environmentId), - feed.ruleFor, - ), + rulesFor, hidden: feed.hidden, repositoryHidden: feed.repositoryHidden, showHidden, @@ -1316,7 +1321,7 @@ export function PullRequestsPage() { closingKeys={closingKeys} sweepingKeys={closeSweepKeys} onCloseSweepStart={startCloseSweep} - onRowMenu={feed.showRowMenu} + onRowMenu={showRowMenu} /> )} {hiddenCount > 0 ? ( diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index 73277d4a493ed..f37adbb8cd7d1 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -7,7 +7,6 @@ import { pullRequestFeedRule, pullRequestProjectHidesRepository, pullRequestRepositoryHidden, - pullRequestRepositoryRules, } from "@t3tools/client-runtime/pull-request-feed"; import { AuthSettingsWriteScope, @@ -34,7 +33,6 @@ import { import { useRunScopedPlan } from "../settings/useScopedSettings"; import { runPullRequestLinkAction } from "./pullRequestLinkContextMenu"; import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic"; -import type { PullRequestRowMenu } from "./PullRequestRow"; type FeedMenuAction = | "copy-link" @@ -111,14 +109,7 @@ export function usePullRequestFeed() { ); }; - const rowRules = pullRequestRepositoryRules( - projects, - (project) => ruleFor({ environmentId: project.environmentId, projectId: project.id }), - (project) => ruleCounts(project.environmentId), - ruleFor, - ); - - // Like Settings' project scope, every writable copy of the repository gets the rule. + // Like Settings' project scope, every counted copy of the repository gets the rule. const ruleMembers = (project: { environmentId: EnvironmentId; projectId: ProjectId }) => { const repositoryKeyOf = (candidate: (typeof projects)[number] | undefined) => candidate?.repositoryIdentity?.canonicalKey?.toLowerCase(); @@ -130,10 +121,10 @@ export function usePullRequestFeed() { ); if (key) { return projects.filter( - (candidate) => repositoryKeyOf(candidate) === key && canWrite(candidate.environmentId), + (candidate) => repositoryKeyOf(candidate) === key && ruleCounts(candidate.environmentId), ); } - return canWrite(project.environmentId) + return ruleCounts(project.environmentId) ? [{ id: project.projectId, environmentId: project.environmentId }] : []; }; @@ -152,11 +143,11 @@ export function usePullRequestFeed() { entry: EnvironmentPullRequestEntry, openLabel: string, position: { readonly x: number; readonly y: number }, + rules: ReadonlyArray, ) => { const api = readLocalApi(); if (!api) return; const isHidden = isPullRequestHidden(hidden, entry.url); - const rules = rowRules(entry); const writable = canWrite(entry.environmentId); const items: ContextMenuItem[] = [ { id: "copy-link", label: "Copy link", icon: "copy" }, @@ -201,8 +192,8 @@ export function usePullRequestFeed() { } }; - const showRowMenu: PullRequestRowMenu = useStableCallback((entry, openLabel, position) => { - void openRowMenu(entry, openLabel, position); + const showRowMenu = useStableCallback((...args: Parameters) => { + void openRowMenu(...args); }); return { From bf39a25e21241e49da4416d551d3d2eb0eb266b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:46:56 +0200 Subject: [PATCH 33/48] fix(web): the row menu writes every writable copy again The previous commit limited the rule write to connected copies, so a writable copy that was briefly offline kept its old rule and brought hidden rows back when it reconnected. Write every writable copy, as Settings does; a disconnected one warns and the user can retry. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/pullRequest/usePullRequestFeed.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index f37adbb8cd7d1..0339645b7e666 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -109,7 +109,7 @@ export function usePullRequestFeed() { ); }; - // Like Settings' project scope, every counted copy of the repository gets the rule. + // Like Settings' project scope, every writable copy gets the rule; a disconnected one warns. const ruleMembers = (project: { environmentId: EnvironmentId; projectId: ProjectId }) => { const repositoryKeyOf = (candidate: (typeof projects)[number] | undefined) => candidate?.repositoryIdentity?.canonicalKey?.toLowerCase(); @@ -121,10 +121,10 @@ export function usePullRequestFeed() { ); if (key) { return projects.filter( - (candidate) => repositoryKeyOf(candidate) === key && ruleCounts(candidate.environmentId), + (candidate) => repositoryKeyOf(candidate) === key && canWrite(candidate.environmentId), ); } - return ruleCounts(project.environmentId) + return canWrite(project.environmentId) ? [{ id: project.projectId, environmentId: project.environmentId }] : []; }; From bcc77b3fb861360de2ac5dbeed95e3a425be15c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:47:58 +0200 Subject: [PATCH 34/48] docs(web): say that the row menu skips offline copies Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/pullRequest/usePullRequestFeed.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index 0339645b7e666..c4d78224908dd 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -109,7 +109,7 @@ export function usePullRequestFeed() { ); }; - // Like Settings' project scope, every writable copy gets the rule; a disconnected one warns. + // Like Settings' project scope: an offline copy is skipped and keeps its rule until written again. const ruleMembers = (project: { environmentId: EnvironmentId; projectId: ProjectId }) => { const repositoryKeyOf = (candidate: (typeof projects)[number] | undefined) => candidate?.repositoryIdentity?.canonicalKey?.toLowerCase(); From f5ac3398bbca7edc4d13ee8be3ce0472a2de6a16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:06:06 +0200 Subject: [PATCH 35/48] fix(client): every connected copy's rule counts, and the row menu writes the list's scope A copy's feed rule counted only where this device could write settings, so the same saved settings gave different feeds on two devices. Now every connected copy that supports the feed counts; write access only enables the controls. The row menu reads its checkmarks and writes its rule on the same scoped copies as the list, so a filtered list no longer overwrites environments it does not show. Co-Authored-By: Claude Opus 5.5 --- .../pull-requests/usePullRequestFeed.ts | 5 ++- .../pullRequest/PullRequestsPage.tsx | 3 +- .../pullRequest/usePullRequestFeed.ts | 41 ++++++++++++------- 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts index e74f0a84d5230..c1507bb12f1f7 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestFeed.ts @@ -64,9 +64,10 @@ export function usePullRequestFeed() { environment.environmentId === environmentId && environment.connectionState === "connected", ); - /** A copy's rule counts toward a row only where this device could also change it. */ + /** Every connected copy's rule counts, so the same settings give the same feed on any device. */ const ruleCounts = (environmentId: EnvironmentId) => - isConnected(environmentId) && canHide(environmentId); + isConnected(environmentId) && + configs.get(environmentId)?.environment.capabilities.pullRequestFeed === true; /** The one rule for which projects hide their repository, the same as on web. */ const hidesRepository = (project: { diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index 0f33a9604f7ab..522494c655585 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -765,9 +765,8 @@ export function PullRequestsPage() { (project) => feed.ruleCounts(project.environmentId), feed.ruleFor, ); - // The menu checks the same rules that decide the row. const showRowMenu: PullRequestRowMenu = useStableCallback((entry, openLabel, position) => - feed.showRowMenu(entry, openLabel, position, rulesFor(entry)), + feed.showRowMenu(entry, openLabel, position, projects), ); const { listedPullRequestTabStatuses, diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index c4d78224908dd..793a64e357cd7 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -7,6 +7,7 @@ import { pullRequestFeedRule, pullRequestProjectHidesRepository, pullRequestRepositoryHidden, + pullRequestRepositoryRules, } from "@t3tools/client-runtime/pull-request-feed"; import { AuthSettingsWriteScope, @@ -75,9 +76,11 @@ export function usePullRequestFeed() { ); // A repository one environment hides leaves every environment's copy, including carried rows. const repositoryHidden = pullRequestRepositoryHidden(projects, hidesRepository); - /** A copy's rule counts toward a row only where the row menu's rule write reaches it too. */ + /** Every connected copy's rule counts, so the same settings give the same feed on any device. */ const ruleCounts = (environmentId: EnvironmentId) => - connected.has(environmentId) && canWrite(environmentId); + connected.has(environmentId) && + environments.find((environment) => environment.environmentId === environmentId)?.serverConfig + ?.environment.capabilities.pullRequestFeed === true; // Every environment that holds the link hides it, so all of them must be able to clear it. const holders = (url: string) => environments.filter((environment) => @@ -109,18 +112,22 @@ export function usePullRequestFeed() { ); }; - // Like Settings' project scope: an offline copy is skipped and keeps its rule until written again. - const ruleMembers = (project: { environmentId: EnvironmentId; projectId: ProjectId }) => { - const repositoryKeyOf = (candidate: (typeof projects)[number] | undefined) => + type ScopeProject = (typeof projects)[number]; + // The writable copies in the list's scope; an offline one is skipped and keeps its rule. + const ruleMembers = ( + project: { environmentId: EnvironmentId; projectId: ProjectId }, + scope: ReadonlyArray, + ) => { + const repositoryKeyOf = (candidate: ScopeProject | undefined) => candidate?.repositoryIdentity?.canonicalKey?.toLowerCase(); const key = repositoryKeyOf( - projects.find( + scope.find( (candidate) => candidate.environmentId === project.environmentId && candidate.id === project.projectId, ), ); if (key) { - return projects.filter( + return scope.filter( (candidate) => repositoryKeyOf(candidate) === key && canWrite(candidate.environmentId), ); } @@ -129,11 +136,7 @@ export function usePullRequestFeed() { : []; }; - const setProjectRule = ( - project: { environmentId: EnvironmentId; projectId: ProjectId }, - rule: PullRequestFeedRule, - ) => { - const members = ruleMembers(project); + const setProjectRule = (members: ReturnType, rule: PullRequestFeedRule) => { runPlan(environments, (current) => planProjectOverridePatch(current, members, { pullRequestFeed: rule }), ); @@ -143,11 +146,19 @@ export function usePullRequestFeed() { entry: EnvironmentPullRequestEntry, openLabel: string, position: { readonly x: number; readonly y: number }, - rules: ReadonlyArray, + scope: ReadonlyArray, ) => { const api = readLocalApi(); if (!api) return; const isHidden = isPullRequestHidden(hidden, entry.url); + // The same scope as the list, so the checkmarks and the write cover the same copies. + const rules = pullRequestRepositoryRules( + scope, + (project) => ruleFor({ environmentId: project.environmentId, projectId: project.id }), + (project) => ruleCounts(project.environmentId), + ruleFor, + )(entry); + const members = ruleMembers(entry, scope); const writable = canWrite(entry.environmentId); const items: ContextMenuItem[] = [ { id: "copy-link", label: "Copy link", icon: "copy" }, @@ -166,7 +177,7 @@ export function usePullRequestFeed() { { id: "rule:all", label: `Feed for ${entry.projectTitle}`, - disabled: ruleMembers(entry).length === 0, + disabled: members.length === 0, children: PULL_REQUEST_FEED_RULES.map((option) => ({ id: `rule:${option.value}` as const, label: option.label, @@ -188,7 +199,7 @@ export function usePullRequestFeed() { unhide(entry.url); } else { const picked = PULL_REQUEST_FEED_RULES.find((option) => action === `rule:${option.value}`); - if (picked) setProjectRule(entry, picked.value); + if (picked) setProjectRule(members, picked.value); } }; From ab4a4a066866a6511449e868097bb03314e4eef0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:09:51 +0200 Subject: [PATCH 36/48] fix(web): a carried row outside the list's scope writes no feed rule Co-Authored-By: Claude Opus 5.5 --- .../components/pullRequest/usePullRequestFeed.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index 793a64e357cd7..68f047e13acd7 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -120,20 +120,19 @@ export function usePullRequestFeed() { ) => { const repositoryKeyOf = (candidate: ScopeProject | undefined) => candidate?.repositoryIdentity?.canonicalKey?.toLowerCase(); - const key = repositoryKeyOf( - scope.find( - (candidate) => - candidate.environmentId === project.environmentId && candidate.id === project.projectId, - ), + const own = scope.find( + (candidate) => + candidate.environmentId === project.environmentId && candidate.id === project.projectId, ); + // A carried row from outside the scope writes nothing the list does not show. + if (own === undefined) return []; + const key = repositoryKeyOf(own); if (key) { return scope.filter( (candidate) => repositoryKeyOf(candidate) === key && canWrite(candidate.environmentId), ); } - return canWrite(project.environmentId) - ? [{ id: project.projectId, environmentId: project.environmentId }] - : []; + return canWrite(own.environmentId) ? [own] : []; }; const setProjectRule = (members: ReturnType, rule: PullRequestFeedRule) => { From 858519cf867322b04a05db1cdeb6bd753421eac5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Lappetel=C3=A4inen?= <38039015+pnupu@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:56:22 +0200 Subject: [PATCH 37/48] feat(pull-requests): an Involving me feed rule shows PRs you are part of A project on the new `involved` feed rule adds the pull requests the viewer opened, is asked to review, or (on GitHub) is assigned to, mentioned in, or commented on. GitHub narrows `involved` with the `involves:` search qualifier. Hosts without such a filter are read as `all`, and the service keeps the rows the viewer wrote or must review. Web and mobile read the `involved` listing only for environments with a project on that rule. The rule is offered only where every server sends the new `pullRequestFeedInvolved` capability, and an unknown stored rule now decodes to the default instead of failing the settings. Co-Authored-By: Claude Opus 5.5 --- .../pull-requests/PullRequestsScreen.tsx | 30 ++++++++++++++- .../SettingsServerControlsRouteScreen.tsx | 8 +++- .../src/persistence/mobile-preferences.ts | 3 +- .../src/environment/ServerEnvironment.ts | 1 + .../pullRequest/PullRequestService.test.ts | 38 +++++++++++++++++++ .../src/pullRequest/PullRequestService.ts | 20 ++++++++-- .../pullRequest/PullRequestsPage.tsx | 33 ++++++++++++++-- .../pullRequest/usePullRequestFeed.ts | 8 +++- .../settings/ProjectDefaultsSettings.tsx | 12 ++++-- docs/user/source-control.md | 6 ++- .../src/pullRequestFeed.test.ts | 29 +++++++++++--- .../client-runtime/src/pullRequestFeed.ts | 31 +++++++++++++-- packages/contracts/src/environment.ts | 2 + packages/contracts/src/pullRequest.ts | 11 +++++- packages/contracts/src/settings.test.ts | 13 +++++++ packages/contracts/src/settings.ts | 14 ++++++- .../src/server/AzureDevOpsPullRequestCli.ts | 2 + .../src/server/PullRequestProvider.ts | 5 +++ .../src/server/GitHubPullRequestApi.test.ts | 14 +++++++ .../src/server/GitHubPullRequestApi.ts | 13 +++++-- .../src/server/GitHubPullRequestProvider.ts | 1 + .../src/server/GitLabPullRequestCli.ts | 2 + 22 files changed, 263 insertions(+), 33 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index fcf45a5e56033..d466cb73d4e82 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -171,6 +171,34 @@ export function PullRequestsScreen( [environments, environmentId, configs, controls, query], ); const result = usePullRequestList(targets); + const feed = usePullRequestFeed(); + // As on web: only environments with a project on the `involved` rule read that listing. + const involvedEnvironmentIds = controls.projectId + ? "" + : [ + ...new Set( + allProjects.flatMap((project) => + feed.ruleFor({ environmentId: project.environmentId, projectId: project.id }) === + "involved" + ? [project.environmentId] + : [], + ), + ), + ].join("\n"); + const involvedTargets = useMemo( + () => + controls.involvement !== "all" + ? [] + : targets.flatMap((target) => + involvedEnvironmentIds.split("\n").includes(target.environmentId) + ? [{ ...target, input: { ...target.input, involvement: "involved" as const } }] + : [], + ), + [controls.involvement, involvedEnvironmentIds, targets], + ); + const involvedUrls = new Set( + usePullRequestList(involvedTargets).entries.map((entry) => entry.url), + ); const connectedTargets = targets.filter((target) => environments.some( (environment) => @@ -198,7 +226,6 @@ export function PullRequestsScreen( ), [result.entries, controls, query, result.data, connectedKey], ); - const feed = usePullRequestFeed(); const [showHidden, setShowHidden] = useState(false); const viewers = result.data?.viewers ?? {}; const repositoryHidden = pullRequestRepositoryHidden(allProjects, feed.hidesRepository); @@ -221,6 +248,7 @@ export function PullRequestsScreen( rulesFor, hidden: feed.hidden, repositoryHidden, + involved: (row) => involvedUrls.has(row.url), }, ), ); diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 4a3d6f8995784..dd19180d7938d 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -42,7 +42,7 @@ import { } from "./settings-scoped-server"; import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs"; import { usePullRequestFeed } from "../pull-requests/usePullRequestFeed"; -import { PULL_REQUEST_FEED_RULES } from "@t3tools/client-runtime/pull-request-feed"; +import { pullRequestFeedRuleOptions } from "@t3tools/client-runtime/pull-request-feed"; import { AutoSettleSettingsRows } from "./ThreadSettingsSections"; import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings"; import { isSourceControlProviderOffered } from "@t3tools/client-runtime/operations/projects"; @@ -469,7 +469,11 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { ) : null } > - {PULL_REQUEST_FEED_RULES.map((option, index) => ( + {pullRequestFeedRuleOptions( + targets.map( + (target) => target.environment.serverConfig.environment.capabilities, + ), + ).map((option, index) => ( + Effect.gen(function* () { + const asked: string[] = []; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getViewer: () => Effect.succeed("bilal"), + listChangeRequests: (input) => + Effect.sync(() => { + asked.push(input.involvement); + return { + items: [ + { ...changeRequest(1, "2026-07-03T00:00:00Z"), author: null }, + { + ...changeRequest(2, "2026-07-02T00:00:00Z"), + author: { login: "Bilal", name: null, avatarUrl: null }, + }, + { ...changeRequest(3, "2026-07-01T00:00:00Z"), reviewRequestLogins: ["bilal"] }, + ], + truncated: false, + continues: true, + }; + }), + }), + ], + }); + + const result = yield* service.list({ state: "open", involvement: "involved" }); + + assert.deepStrictEqual(asked, ["all"]); + assert.deepStrictEqual( + result.entries.map((entry) => entry.number), + [2, 3], + ); + }), +); + it.effect("a listing narrowed to some projects is its own cache entry", () => Effect.gen(function* () { const asked: ReadonlyArray[] = []; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 592bfb92ce7cd..40868dfd54eb4 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -546,6 +546,7 @@ function withRateLimitBackoff( ? {} : { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }), ...(api.batchesReads === undefined ? {} : { batchesReads: api.batchesReads }), + ...(api.listsInvolved === undefined ? {} : { listsInvolved: api.listsInvolved }), getViewer: options?.viewerAllowsPause === true ? interactive("getViewer", api.getViewer) @@ -1436,6 +1437,14 @@ export const make = Effect.gen(function* () { const cursorOf = (project: SupportedProject): ListCursor | undefined => continuation?.get(project.cursorKey); + // lean: a host that cannot narrow `involved` is read as `all` and narrowed here, which can + // leave a short page. Revisit if pages on those hosts come back sparse. + const narrowsInvolved = (project: SupportedProject) => + involvement === "involved" && project.api.listsInvolved !== true; + const involvesViewer = (item: ProviderChangeRequest, viewer: string) => + item.author?.login.toLowerCase() === viewer.toLowerCase() || + item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer.toLowerCase()); + const readSlice = ( project: SupportedProject, cursor: ListCursor | undefined, @@ -1443,13 +1452,14 @@ export const make = Effect.gen(function* () { { const viewer = viewers[project.host]!; const key = project.cursorKey; + const narrowed = narrowsInvolved(project); return project.api .listChangeRequests({ cwd: project.project.workspaceRoot, repository: project.repository, host: project.host, state: input.state, - involvement, + involvement: narrowed ? "all" : involvement, viewer, limit, query: input.query, @@ -1482,7 +1492,11 @@ export const make = Effect.gen(function* () { return { key, entries: items - .filter((item) => matchesRowFilters(item, input.filters, viewer)) + .filter( + (item) => + matchesRowFilters(item, input.filters, viewer) && + (!narrowed || involvesViewer(item, viewer)), + ) .map((item) => toEntry({ project, item, viewer, observedAt })), errors: [], truncated: page.truncated, @@ -1553,7 +1567,7 @@ export const make = Effect.gen(function* () { const readAcross = first.api.listChangeRequestsAcross; const separately = () => Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY }); - if (readAcross === undefined) return separately(); + if (readAcross === undefined || narrowsInvolved(first)) return separately(); const viewer = viewers[first.host]!; const cursor = cursorOf(first); return readAcross({ diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index 522494c655585..0a438f014c674 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -431,6 +431,18 @@ export function PullRequestsPage() { }, })); const partitionsWanted = search.involvement === "all" && typedQuery.length === 0; + // Only a server that stores the `involved` rule can hold a project on it, so older servers and + // feeds without the rule never get this read. + const involvedEnvironments = new Set( + scopedProjectId !== undefined + ? [] + : projects.flatMap((project) => + feed.ruleFor({ environmentId: project.environmentId, projectId: project.id }) === + "involved" + ? [project.environmentId] + : [], + ), + ); const partitionTargets = (() => { // The main list goes first. Besides putting the visible rows on screen sooner, it proves // which repositories the host search indexes, so an empty partition does not trigger the @@ -440,10 +452,10 @@ export function PullRequestsPage() { baselineQuery.data === null || baselineQuery.data.entries.length === 0 ) { - return { authored: NO_LIST_TARGETS, reviewing: NO_LIST_TARGETS }; + return { authored: NO_LIST_TARGETS, reviewing: NO_LIST_TARGETS, involved: NO_LIST_TARGETS }; } - const targetsFor = (involvement: PullRequestInvolvement) => - environmentQueries.map(({ environmentId, projectIds }) => ({ + const targetsFor = (involvement: PullRequestInvolvement, queries = environmentQueries) => + queries.map(({ environmentId, projectIds }) => ({ environmentId, input: { state: search.state, @@ -455,10 +467,18 @@ export function PullRequestsPage() { ...(menuFiltered ? { filters: menuFilters } : {}), } satisfies PullRequestListInput, })); - return { authored: targetsFor("authored"), reviewing: targetsFor("reviewing") }; + return { + authored: targetsFor("authored"), + reviewing: targetsFor("reviewing"), + involved: targetsFor( + "involved", + environmentQueries.filter(({ environmentId }) => involvedEnvironments.has(environmentId)), + ), + }; })(); const authoredQuery = usePullRequestHostList(partitionTargets.authored); const reviewingQuery = usePullRequestHostList(partitionTargets.reviewing); + const involvedQuery = usePullRequestHostList(partitionTargets.involved); const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false }); const [detailRefreshToken, setDetailRefreshToken] = useState(0); const [invalidating, setInvalidating] = useState(false); @@ -702,6 +722,7 @@ export function PullRequestsPage() { ...facetTargets, ...partitionTargets.authored, ...partitionTargets.reviewing, + ...partitionTargets.involved, ] : [] ).filter( @@ -756,6 +777,9 @@ export function PullRequestsPage() { ); const shownHeldAuthored = usePendingListEntries(overlayInput, heldPartitions?.authored); const shownHeldReviewing = usePendingListEntries(overlayInput, heldPartitions?.reviewing); + const involvedUrls = new Set( + (partitionsWanted ? involvedQuery.data?.entries : undefined)?.map((entry) => entry.url), + ); const scrollRef = useRef(null); const [showHidden, setShowHidden] = useState(false); // Only copies in the list's scope: a row shows when any of their rules allows it. @@ -805,6 +829,7 @@ export function PullRequestsPage() { rulesFor, hidden: feed.hidden, repositoryHidden: feed.repositoryHidden, + involved: (entry) => involvedUrls.has(entry.url), showHidden, }, }); diff --git a/apps/web/src/components/pullRequest/usePullRequestFeed.ts b/apps/web/src/components/pullRequest/usePullRequestFeed.ts index 68f047e13acd7..d2e34830898f0 100644 --- a/apps/web/src/components/pullRequest/usePullRequestFeed.ts +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -5,6 +5,7 @@ import { isPullRequestHidden, PULL_REQUEST_FEED_RULES, pullRequestFeedRule, + pullRequestFeedRuleOptions, pullRequestProjectHidesRepository, pullRequestRepositoryHidden, pullRequestRepositoryRules, @@ -76,6 +77,9 @@ export function usePullRequestFeed() { ); // A repository one environment hides leaves every environment's copy, including carried rows. const repositoryHidden = pullRequestRepositoryHidden(projects, hidesRepository); + const capabilitiesOf = (environmentId: EnvironmentId) => + environments.find((environment) => environment.environmentId === environmentId)?.serverConfig + ?.environment.capabilities; /** Every connected copy's rule counts, so the same settings give the same feed on any device. */ const ruleCounts = (environmentId: EnvironmentId) => connected.has(environmentId) && @@ -177,7 +181,9 @@ export function usePullRequestFeed() { id: "rule:all", label: `Feed for ${entry.projectTitle}`, disabled: members.length === 0, - children: PULL_REQUEST_FEED_RULES.map((option) => ({ + children: pullRequestFeedRuleOptions( + members.map((member) => capabilitiesOf(member.environmentId)), + ).map((option) => ({ id: `rule:${option.value}` as const, label: option.label, checked: rules.includes(option.value), diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx index 48022143d92d9..ce483d18470b7 100644 --- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx +++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx @@ -5,7 +5,10 @@ import { managedRuntimeModeDenial, } from "@t3tools/contracts"; import { createModelSelection, pickModelSelection } from "@t3tools/shared/model"; -import { PULL_REQUEST_FEED_RULES } from "@t3tools/client-runtime/pull-request-feed"; +import { + PULL_REQUEST_FEED_RULES, + pullRequestFeedRuleOptions, +} from "@t3tools/client-runtime/pull-request-feed"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { useNavigate } from "@tanstack/react-router"; @@ -110,6 +113,9 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting const pullRequestFeedSupported = connectedEnvironments.every( (environment) => environment.serverConfig?.environment.capabilities.pullRequestFeed === true, ); + const pullRequestFeedRules = pullRequestFeedRuleOptions( + connectedEnvironments.map((environment) => environment.serverConfig?.environment.capabilities), + ); const modelSource = useScopedSettingSource(["defaultModelSelection"]); const isProjectScope = scope.kind === "project" || scope.kind === "checkout"; const unavailable = connectedEnvironments.length === 0; @@ -549,7 +555,7 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting