diff --git a/.github/workflows/fork-release.yml b/.github/workflows/fork-release.yml new file mode 100644 index 0000000000000..8e09f58ef613c --- /dev/null +++ b/.github/workflows/fork-release.yml @@ -0,0 +1,341 @@ +# 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-24.04 + 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-24.04 + 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-24.04 + 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 + # 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 + 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-24.04 + 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-24.04 + 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/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index d0672f064064a..11363d38ed3fe 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -1,4 +1,5 @@ import { usePaneRole } from "../../components/ui/Pane"; +import { ProjectId } from "@t3tools/contracts"; import { Button } from "../../components/ui/Button"; import { applyPullRequestDraftFilterChange, @@ -32,6 +33,15 @@ import { import { usePullRequestList } from "./usePullRequestList"; import { usePullRequestListControls } from "./usePullRequestListControls"; import { usePullRequestListActions } from "./usePullRequestListActions"; +import { usePullRequestFeed } from "./usePullRequestFeed"; +import { + isPullRequestHidden, + pullRequestListedGroup, + pullRequestFeedVisibility, + pullRequestInvolvedMatcher, + pullRequestRepositoryHidden, + pullRequestRepositoryRules, +} from "@t3tools/client-runtime/pull-request-feed"; import { filterPullRequestList, pullRequestListFacets, @@ -82,6 +92,10 @@ function PullRequestListError(props: { readonly message: string }) { ); } +// lean: Involving me reads one page of each of its lists, the same 99 rows web reads, so older +// involved pull requests stay hidden. Revisit if users need their older involved pull requests. +const INVOLVED_LIST_LIMIT = 99; + export function PullRequestsScreen( props: { readonly sidebar?: boolean; @@ -163,6 +177,84 @@ export function PullRequestsScreen( [environments, environmentId, configs, controls, query], ); const result = usePullRequestList(targets); + const feed = usePullRequestFeed(); + // As on web: only the projects on the `involved` rule read that listing, after the main list + // answers, and not while searching, when the rule shows every pull request. + const involvedProjectKey = + controls.projectId || controls.involvement !== "all" || query.trim().length > 0 + ? "" + : allProjects + .flatMap((project) => + feed.ruleFor({ environmentId: project.environmentId, projectId: project.id }) === + "involved" + ? [`${project.environmentId} ${project.id}`] + : [], + ) + .join("\n"); + const mainAnswered = result.entries.length > 0; + const involvedTargets = useMemo(() => { + if (!mainAnswered || involvedProjectKey === "") return []; + const ruled = involvedProjectKey.split("\n"); + return targets.flatMap((target) => { + const projectIds = ruled.flatMap((key) => { + const [environmentId, projectId] = key.split(" "); + return environmentId === target.environmentId && projectId + ? [ProjectId.make(projectId)] + : []; + }); + return projectIds.length === 0 + ? [] + : [ + { + ...target, + input: { + ...target.input, + involvement: "involved" as const, + projectIds, + limit: INVOLVED_LIST_LIMIT, + }, + }, + ]; + }); + }, [mainAnswered, involvedProjectKey, targets]); + const involvedList = usePullRequestList(involvedTargets); + // As on web's partitions, the authored and review lists join the candidates: `involves:` leaves + // out a pull request only waiting on the viewer's review, and a host without `listsInvolved` + // answers `involved` with nothing. Each reads one page, as the involved list does. + const partitionTargets = useMemo( + () => + (["authored", "reviewing"] as const).map((involvement) => + involvedTargets.map((target) => ({ ...target, input: { ...target.input, involvement } })), + ), + [involvedTargets], + ); + const authoredList = usePullRequestList(partitionTargets[0]!); + const reviewingList = usePullRequestList(partitionTargets[1]!); + // As on web: a project's listing is ready once its environment answered and the project was + // read without error; until then its rows show as under the All rule. + const involved = pullRequestInvolvedMatcher( + involvedTargets.length === 0 + ? null + : { + entries: involvedList.entries, + ready: (entry: { + readonly url: string; + readonly environmentId: string; + readonly projectId: string; + }) => + involvedList.data.answered.has(entry.environmentId) && + involvedTargets.some( + (target) => + target.environmentId === entry.environmentId && + target.input.projectIds.some((id) => id === entry.projectId), + ) && + !involvedList.data.errors.some( + (error) => + error.environmentId === entry.environmentId && + (!("projectId" in error) || error.projectId === entry.projectId), + ), + }, + ); const connectedTargets = targets.filter((target) => environments.some( (environment) => @@ -181,14 +273,72 @@ export function PullRequestsScreen( const entries = useMemo( () => filterPullRequestList( - result.entries, + // Involved rows the main list has not reached yet join it, as on web. + involvedTargets.length === 0 + ? result.entries + : [ + ...result.entries, + ...involvedList.entries, + ...authoredList.entries, + ...reviewingList.entries, + ], controls, result.data?.viewers ?? {}, query, result.data.localSearchHosts, new Set(connectedKey.split("\n")), ), - [result.entries, controls, query, result.data, connectedKey], + [ + result.entries, + involvedTargets, + involvedList.entries, + authoredList.entries, + reviewingList.entries, + controls, + query, + result.data, + connectedKey, + ], + ); + const [showHidden, setShowHidden] = useState(false); + const viewers = result.data?.viewers ?? {}; + const repositoryHidden = pullRequestRepositoryHidden(allProjects, feed.hidesRepository); + // 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.ruleCounts(project.environmentId) && + targets.some((target) => target.environmentId === project.environmentId), + feed.ruleFor, + ); + const listedGroups = useMemo( + () => ({ + authored: new Set(authoredList.entries.map((entry) => entry.url)), + reviewing: new Set(reviewingList.entries.map((entry) => entry.url)), + }), + [authoredList.entries, reviewingList.entries], + ); + const visibilities = entries.map((entry) => + pullRequestFeedVisibility( + entry, + pullRequestListedGroup(entry, viewers[`${entry.environmentId} ${entry.host}`], listedGroups), + { + scopedToProject: Boolean(controls.projectId), + involvement: controls.involvement, + rulesFor, + hidden: feed.hidden, + repositoryHidden, + involved, + }, + ), + ); + const hiddenCount = visibilities.filter((visibility) => visibility === "hidden").length; + // With nothing hidden anywhere, the next hide must not stay shown with no toggle to undo it. + if (showHidden && feed.hidden.size === 0) setShowHidden(false); + 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 }); @@ -261,8 +411,31 @@ export function PullRequestsScreen( [ + ...actions(entry), + ...(isPullRequestHidden(feed.hidden, entry.url) + ? feed.canUnhide(entry.url) + ? [{ id: "unhide", title: "Show in feed", image: "eye" }] + : feed.unhideBlockedBy(entry.url) === null + ? [] + : [ + { + id: "unhide", + title: "Show in feed", + subtitle: `Hidden by ${feed.unhideBlockedBy(entry.url)}`, + image: "eye", + attributes: { disabled: true }, + }, + ] + : feed.canHide(entry.environmentId) + ? [{ 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 +445,7 @@ export function PullRequestsScreen( void result.onRefresh()} + onRefresh={() => { + result.onRefresh(); + involvedList.onRefresh(); + authoredList.onRefresh(); + reviewingList.onRefresh(); + }} // The list already accounts for the navigation header in its content inset. progressViewOffset={Platform.OS === "ios" ? 60 : undefined} /> @@ -320,6 +498,16 @@ export function PullRequestsScreen( ListHeaderComponent={ <> + {hiddenCount > 0 ? ( + + @@ -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/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..c54d12f03af6d --- /dev/null +++ b/apps/web/src/components/chat/ThreadDetailsUsageRings.tsx @@ -0,0 +1,171 @@ +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 { barColor } from "../usage/UsageLimits"; +import { ThreadDetailsSection } from "./ThreadDetailsSection"; +import { PACE_LABEL } from "./ThreadDetailsUsage"; + +const MAX_RINGS = 4; + +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); + const color = barColor(pool.driver); + return displayLimitWindows(pool) + .filter((window) => window.kind === "weekly") + .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}`, + // 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, + })); + }) + // lean: more than four rings leave no room in the center; revisit if a fifth weekly pool matters. + .slice(0, MAX_RINGS); + 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; + return ( + + + {left > 0 ? ( + = 100 + ? 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} + + ); + })} + +
+ {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, 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 ( + + + } + > + + {ring.name} + + {left}% + + + +
+ + {ring.title}: {left}% left + + {reset ? ( + + {refill ? `+${refill.restoresPercent}% in ` : "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; diff --git a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx index 4454d8cd0f441..fc59a58275873 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} {listError && shownCount > 0 ? (
@@ -1301,20 +1416,18 @@ export function PullRequestsPage() {
) : null} - {listData?.truncated && entries.length > 0 ? ( + {/* The error view replaces an emptied page, so it keeps this footer's way to more pages. */} + {pullRequestsSupported && + loadMorePlan.footer !== null && + (shownCount > 0 || (listError !== null && loadMorePlan.footer !== "narrow")) ? (
- {loadingMore ? ( + {loadMorePlan.footer === "loading" ? ( {sentCursors === null ? "Updating pull requests" : "Loading more"} - ) : canContinue || pageSize < MAX_PAGE_SIZE ? ( - ) : ( 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..83f25c0670012 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts @@ -369,6 +369,17 @@ describe("partitioning with the hosts' own priority reads", () => { expect(groups.map((group) => group.key)).toEqual(["authored", "others"]); expect(groups[1]!.entries.map((item) => item.number)).toEqual([2, 1]); expect(groups[0]!.entries.map((item) => item.number)).toEqual([3]); + + // An involved row the list has not reached joins Others once, in recency order. + const mentioned = entry({ number: 4, updatedAt: "2026-07-05T12:00:00Z" }); + const withInvolved = partitionPullRequestsWithPriority( + [newer, older, mine], + [mine], + [], + [mentioned, older, mine], + ); + expect(withInvolved[1]!.entries.map((item) => item.number)).toEqual([2, 4, 1]); + expect(withInvolved[0]!.entries.map((item) => item.number)).toEqual([3]); }); it("gives authored precedence over review-requested and orders partitions by recency", () => { @@ -682,6 +693,72 @@ 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, + rulesFor: (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]); + }); + + 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, + rulesFor: () => ["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/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.ts index 0345e5fd82d07..231c8b6cdc855 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts @@ -452,6 +452,8 @@ export function partitionPullRequestsWithPriority, authored: ReadonlyArray, reviewRequested: ReadonlyArray, + /** Rows the list may not have reached yet; they join Others. */ + involved: ReadonlyArray = [], ): ReadonlyArray> { // Matched by URL: each list may hold the pull request under a different environment. const authoredByKey = new Map(authored.map((entry) => [entry.url, entry])); @@ -461,6 +463,14 @@ export function partitionPullRequestsWithPriority entry.url)); + const withInvolved = (rows: ReadonlyArray) => { + const added = involved.filter( + (entry) => + !listed.has(entry.url) && !authoredByKey.has(entry.url) && !reviewByKey.has(entry.url), + ); + return added.length === 0 ? rows : [...rows, ...added].toSorted(comparePullRequestsByRecency); + }; for (const entry of entries) { const key = entry.url; if (authoredByKey.has(key)) { @@ -481,7 +491,7 @@ export function partitionPullRequestsWithPriority group.entries.length > 0) diff --git a/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts b/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts index 31f02978c918d..a08ad1ae30c04 100644 --- a/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestListGroups.logic.ts @@ -1,3 +1,8 @@ +import { + filterPullRequestFeed, + pullRequestFeedGroup, + type PullRequestFeedOptions, +} from "@t3tools/client-runtime/pull-request-feed"; import type { PullRequestInvolvement, PullRequestListFilters, @@ -38,7 +43,9 @@ export function pullRequestGroups({ held, authored, reviewing, + involved, partitionsWanted, + feed, }: { known: ReadonlyArray; /** The text-free rows already loaded, or undefined when the typed filters cannot vet them. */ @@ -54,7 +61,13 @@ export function pullRequestGroups({ held: PullRequestPartitionsSnapshot | undefined; authored: ReadonlyArray | undefined; reviewing: ReadonlyArray | undefined; + /** The host's `involved` rows, added to the list like the authored and reviewing partitions. */ + involved?: 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 +82,7 @@ export function pullRequestGroups({ : involvementEntries; }; - const entries = (() => { + const searched = (() => { const narrowedEntries = narrowRows(known); if (text.length === 0) { return narrowedEntries.toSorted(comparePullRequestsByRecency); @@ -89,20 +102,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 +116,57 @@ 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); + // The involved rows still join while an authored or reviewing read has no answer. + const listed = new Set(searched.map((entry) => entry.url)); + const added = (narrow(involved) ?? []).filter((entry) => !listed.has(entry.url)); + return groupPullRequestsByInvolvement( + added.length === 0 + ? searched + : [...searched, ...added].toSorted(comparePullRequestsByRecency), + viewers, + ); } - return partitionPullRequestsWithPriority(entries, narrowedAuthored, narrowedReviewing); + // Rows only the involved listing brings join the group their own author and requests give. + const extra = narrow(involved) ?? []; + const groupOfExtra = (entry: EnvironmentPullRequestEntry) => + pullRequestFeedGroup(entry, pullRequestEntryViewer(entry, viewers)); + return partitionPullRequestsWithPriority( + searched, + [...narrowedAuthored, ...extra.filter((entry) => groupOfExtra(entry) === "authored")], + [...narrowedReviewing, ...extra.filter((entry) => groupOfExtra(entry) === "reviewRequested")], + extra.filter((entry) => groupOfExtra(entry) === "others"), + ); })(); + // 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, ruledOutCount } = + feed === undefined + ? { groups: grouped, hiddenCount: 0, ruledOutCount: 0 } + : 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 + : (() => { + 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 +181,8 @@ export function pullRequestGroups({ entries, listedPullRequestTabStatuses, groups, + hiddenCount, + ruledOutCount, entriesByStatsKey, heldPullRequestsBySurface, }; diff --git a/apps/web/src/components/pullRequest/pullRequestLoadMore.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestLoadMore.logic.test.ts new file mode 100644 index 0000000000000..cb00c30ece0a0 --- /dev/null +++ b/apps/web/src/components/pullRequest/pullRequestLoadMore.logic.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + mainReadState, + pullRequestLoadMore, + type PullRequestReadState, +} from "./pullRequestLoadMore.logic"; + +describe("pullRequestLoadMore", () => { + it.each<[string, PullRequestReadState, boolean, string | null]>([ + ["a truncated list grows", "truncated", true, "button"], + ["a failed page is asked for again", "failed", true, "button"], + ["a complete list offers nothing", "complete", false, null], + ["a capped list asks for a narrower search", "capped", false, "narrow"], + // A page in flight is not restarted by another click. + ["a page in flight spins", "pending", false, "loading"], + ])("%s", (_, main, grow, footer) => { + expect(pullRequestLoadMore(main)).toEqual({ grow, footer }); + }); + + it.each<[string, boolean, boolean, boolean, PullRequestReadState]>([ + // One environment's failure does not stop the others from paging. + ["one failed environment, others continue", true, true, true, "truncated"], + ["no environment can continue after a failure", true, false, true, "failed"], + ["nothing failed", false, true, true, "truncated"], + ["no cursor and no larger page", false, false, false, "capped"], + ])("main list: %s", (_, failed, canContinue, canGrow, state) => { + expect(mainReadState({ truncated: true, loading: false, canContinue, canGrow, failed })).toBe( + state, + ); + }); +}); diff --git a/apps/web/src/components/pullRequest/pullRequestLoadMore.logic.ts b/apps/web/src/components/pullRequest/pullRequestLoadMore.logic.ts new file mode 100644 index 0000000000000..bd967b3e7e068 --- /dev/null +++ b/apps/web/src/components/pullRequest/pullRequestLoadMore.logic.ts @@ -0,0 +1,35 @@ +/** + * Where the main list stands. `truncated` can still grow; `capped` has more rows but no way to + * reach them; `pending` is a page in flight; `failed` is a page that can be asked for again. + */ +export type PullRequestReadState = "pending" | "complete" | "truncated" | "capped" | "failed"; + +export interface PullRequestLoadMorePlan { + /** Load more asks for the next page, or again after it failed. */ + readonly grow: boolean; + readonly footer: "loading" | "button" | "narrow" | null; +} + +/** + * The main list's state. One environment's failed read does not stop the others: the list is + * `failed` only when no environment can continue, and then Load more asks again. + */ +export function mainReadState(input: { + readonly truncated: boolean; + readonly loading: boolean; + readonly canContinue: boolean; + readonly canGrow: boolean; + readonly failed: boolean; +}): PullRequestReadState { + if (!input.truncated) return "complete"; + if (input.loading) return "pending"; + if (!input.canGrow) return "capped"; + return input.failed && !input.canContinue ? "failed" : "truncated"; +} + +/** What Load more does and what the footer shows. A page in flight is never restarted. */ +export function pullRequestLoadMore(main: PullRequestReadState): PullRequestLoadMorePlan { + if (main === "pending") return { grow: false, footer: "loading" }; + const grow = main === "truncated" || main === "failed"; + return { grow, footer: grow ? "button" : main === "capped" ? "narrow" : null }; +} diff --git a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts index 7b8da285376f4..3d84488a7fedc 100644 --- a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts @@ -159,6 +159,35 @@ 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([]); + // 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"] }]); + }); }); 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..a264d9fabcf4b 100644 --- a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts @@ -181,12 +181,24 @@ 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 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( - projects, + kept, 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..d2e34830898f0 --- /dev/null +++ b/apps/web/src/components/pullRequest/usePullRequestFeed.ts @@ -0,0 +1,227 @@ +import { + hiddenPullRequestKey, + hiddenPullRequestLinks, + hiddenPullRequestUrls, + isPullRequestHidden, + PULL_REQUEST_FEED_RULES, + pullRequestFeedRule, + pullRequestFeedRuleOptions, + pullRequestProjectHidesRepository, + pullRequestRepositoryHidden, + pullRequestRepositoryRules, +} from "@t3tools/client-runtime/pull-request-feed"; +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 { useProjects } from "~/state/entities"; +import { useEnvironments } from "~/state/environments"; +import { readEnvironmentScope } from "~/state/session"; + +import { + applyPendingScopedWrites, + isConnectedWithConfig, + pendingScopedWritesAtom, + planEnvironmentSettingsPatch, + planProjectOverridePatch, +} from "../settings/scopedSettings"; +import { useRunScopedPlan } from "../settings/useScopedSettings"; +import { runPullRequestLinkAction } from "./pullRequestLinkContextMenu"; +import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic"; + +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 allSettings = environments.map((environment) => environment.serverConfig?.settings); + const hidden = hiddenPullRequestUrls(allSettings); + const hiddenUrls = [...hiddenPullRequestLinks(allSettings).values()]; + + const ruleFor = (entry: { environmentId: EnvironmentId; projectId: ProjectId }) => + pullRequestFeedRule(settingsOf(entry.environmentId), entry.projectId); + const projects = useProjects(); + /** 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 connected = new Set( + environments.flatMap((environment) => + isConnectedWithConfig(environment) ? [environment.environmentId] : [], + ), + ); + /** The one rule for which projects hide their repository, shared by queries and rows. */ + const hidesRepository = (project: { environmentId: EnvironmentId; id: ProjectId }) => + pullRequestProjectHidesRepository( + ruleFor({ environmentId: project.environmentId, projectId: project.id }), + { connected: connected.has(project.environmentId) }, + ); + // 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) && + 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) => + isPullRequestHidden(hiddenPullRequestUrls([environment.serverConfig?.settings]), url), + ); + /** The environment that keeps the link hidden because this client cannot clear it there. */ + const unhideBlockedBy = (url: string) => + holders(url).find( + (environment) => !isConnectedWithConfig(environment) || !canWrite(environment.environmentId), + )?.label ?? null; + const canUnhide = (url: string) => holders(url).length > 0 && unhideBlockedBy(url) === null; + + // One key per write, so concurrent hides and unhides from anywhere cannot erase each other. + const hide = (entry: Pick) => + runPlan( + environments.filter((environment) => environment.environmentId === entry.environmentId), + (current) => + planEnvironmentSettingsPatch(current, { + hiddenPullRequests: { [hiddenPullRequestKey(entry.url)]: entry.url }, + }), + ); + + const unhide = (url: string) => { + if (!canUnhide(url)) return; + runPlan(holders(url), (current) => + planEnvironmentSettingsPatch(current, { + hiddenPullRequests: { [hiddenPullRequestKey(url)]: null }, + }), + ); + }; + + 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 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(own.environmentId) ? [own] : []; + }; + + const setProjectRule = (members: ReturnType, rule: PullRequestFeedRule) => { + runPlan(environments, (current) => + planProjectOverridePatch(current, members, { pullRequestFeed: rule }), + ); + }; + + const openRowMenu = async ( + entry: EnvironmentPullRequestEntry, + openLabel: string, + position: { readonly x: number; readonly y: number }, + 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" }, + { id: "open-external", label: openLabel }, + isHidden + ? { + id: "unhide", + label: "Show in feed", + separatorBefore: true, + disabled: !canUnhide(entry.url), + ...(unhideBlockedBy(entry.url) === null + ? {} + : { detail: `Hidden by ${unhideBlockedBy(entry.url)}` }), + } + : { id: "hide", label: "Hide from feed", separatorBefore: true, disabled: !writable }, + { + id: "rule:all", + label: `Feed for ${entry.projectTitle}`, + disabled: members.length === 0, + children: pullRequestFeedRuleOptions( + members.map((member) => capabilitiesOf(member.environmentId)), + ).map((option) => ({ + id: `rule:${option.value}` as const, + label: option.label, + checked: rules.includes(option.value), + })), + }, + ]; + 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(members, picked.value); + } + }; + + const showRowMenu = useStableCallback((...args: Parameters) => { + void openRowMenu(...args); + }); + + return { + hidden, + hiddenUrls, + ruleFor, + ruleCounts, + hidesRepository, + repositoryHidden, + unhide, + canUnhide, + unhideBlockedBy, + showRowMenu, + }; +} diff --git a/apps/web/src/components/pullRequest/usePullRequestListView.ts b/apps/web/src/components/pullRequest/usePullRequestListView.ts index 7b9e128f12b66..2d4ac15208fb8 100644 --- a/apps/web/src/components/pullRequest/usePullRequestListView.ts +++ b/apps/web/src/components/pullRequest/usePullRequestListView.ts @@ -67,6 +67,8 @@ const UNREACHABLE_PHASES: ReadonlySet = new Set([ export function usePullRequestScope( search: PullRequestsSearch, hostAvailability: PullRequestHostAvailability, + /** Projects whose `hidden` feed rule leaves their repository out of every query. */ + hidesRepository: (project: { environmentId: EnvironmentId; id: ProjectId }) => boolean, ) { const { environments } = useEnvironments(); const allProjects = useProjects(); @@ -141,7 +143,13 @@ 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, + hidesRepository, + ); }; 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/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/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx index 97c9ca0483ab8..ce483d18470b7 100644 --- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx +++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx @@ -5,6 +5,10 @@ import { managedRuntimeModeDenial, } from "@t3tools/contracts"; import { createModelSelection, pickModelSelection } from "@t3tools/shared/model"; +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"; @@ -104,6 +108,14 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting const mixedAutoPull = useScopedSettingsMixed(["defaultAutoPull"]); 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 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; @@ -518,6 +530,54 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting } /> + {pullRequestFeedSupported ? ( + + updateSettings({ pullRequestFeed: DEFAULT_SERVER_SETTINGS.pullRequestFeed }) + } + /> + ) : null + } + control={ + + } + /> + ) : null} )} 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..7fa439745f509 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,50 @@ export function DiffsSettingsPanel() { } /> + ); } +function HiddenPullRequestsSetting() { + const { hiddenUrls, unhide, canUnhide, unhideBlockedBy } = usePullRequestFeed(); + return ( + + {hiddenUrls.length === 0 ? null : ( +
    + {hiddenUrls.toReversed().map((url) => { + const link = sourceControlClients.parseChangeRequestUrl(url)?.link; + return ( +
  • + + {link ? `${link.repository} #${link.number}` : url} + {unhideBlockedBy(url) === null ? null : ` · Hidden by ${unhideBlockedBy(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..bb90ff5d20394 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,45 @@ 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, +}); + +/** A project's override, written from outside Settings, such as a list row. */ +export function planProjectOverridePatch( + environments: readonly ScopedSettingsEnvironment[], + members: readonly { readonly id: ProjectId; readonly environmentId: EnvironmentId }[], + patch: ProjectSettingsOverrides, +): ScopedSettingsPlan { + return unavailablePlan( + projectOverrideWrites(members, environments, (current) => ({ ...current, ...patch })), + "Connect this project's environment to save its setting.", + ); +} + +/** One environment-wide patch for each connected environment. */ +export function planEnvironmentSettingsPatch( + environments: readonly ScopedSettingsEnvironment[], + patch: ServerSettingsPatch, +): ScopedSettingsPlan { + return unavailablePlan( + environments.flatMap((environment) => { + const previous = environment.serverConfig?.settings; + if (!previous || environment.connection.phase !== "connected") return []; + return [ + { 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/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); } } diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.ts index 06abb20717212..516cd76b3da9b 100644 --- a/apps/web/src/state/pullRequests.ts +++ b/apps/web/src/state/pullRequests.ts @@ -612,6 +612,8 @@ interface MergedEnvironmentQueryView { readonly observations: ReadonlyArray; readonly values: ReadonlyArray; readonly error: EnvironmentQueryError | null; + /** Every environment whose read failed; `error` names only the first. */ + readonly failed: ReadonlyArray; readonly isPending: boolean; } @@ -651,12 +653,14 @@ function createMergedEnvironmentQuery( const values: Array = []; const observations: Array = []; const pendingEnvironments = new Set(); + const failed: EnvironmentId[] = []; let error: EnvironmentQueryError | null = null; let isPending = false; for (const target of targets) { const result = get(atomFor(target)); isPending ||= result.waiting; if (result.waiting) pendingEnvironments.add(target.environmentId); + if (result._tag === "Failure") failed.push(target.environmentId); if (result._tag === "Failure" && error === null) { error = { environmentId: target.environmentId, @@ -677,6 +681,7 @@ function createMergedEnvironmentQuery( return { values, error, + failed, isPending, // Another batch can still find a readable checkout on this environment. observations: observations.filter( @@ -689,6 +694,7 @@ function createMergedEnvironmentQuery( observations: [], values: [], error: null, + failed: [], isPending: false, }).pipe(Atom.withLabel(`${label}:empty`)); return function useMergedQuery(targets: ReadonlyArray>) { @@ -749,6 +755,9 @@ export function usePullRequestTurnRefresh(environmentId: EnvironmentId): number export interface MergedPullRequestListView { readonly data: MergedPullRequestList | null; + /** The environments whose answer `data` holds, and those whose latest read failed. */ + readonly answered: ReadonlyArray; + readonly failed: ReadonlyArray; readonly error: EnvironmentQueryError | null; readonly isPending: boolean; readonly observations: ReadonlyArray; @@ -764,6 +773,8 @@ export function usePullRequestList( const data = mergePullRequestLists(query.values); return { data, + answered: query.values.map(([environmentId]) => environmentId), + failed: query.failed, error: query.error, isPending: query.isPending, observations: query.observations, @@ -778,6 +789,8 @@ export function usePullRequestHostList( const data = mergePullRequestLists(query.values); return { data, + answered: query.values.map(([environmentId]) => environmentId), + failed: query.failed, error: query.error, isPending: query.isPending, observations: query.observations, 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 diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 2f068d8827494..f14a812748653 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -244,6 +244,27 @@ 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**, **Involving me**, **Waiting on me** (your review is requested), +**Authored by me**, or **Hidden**. **Involving me** suits a large repository: it shows the pull +requests you opened or are asked to review, and on GitHub also the ones that assign you, mention +you, or have your comments. Other hosts show only the first two. It shows your most recent +involved pull requests (on GitHub, the newest 99 for each 100 repositories on a server); pick the +project in the list's project filter to see all of its pull requests. While you search, it shows +all of the project's pull requests. 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. 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 +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..2cf91c5cf61ca --- /dev/null +++ b/packages/client-runtime/src/pullRequestFeed.test.ts @@ -0,0 +1,255 @@ +import { describe, expect, it } from "@effect/vitest"; +import { + DEFAULT_SERVER_SETTINGS, + ProjectId, + type PullRequestFeedRule, + type PullRequestInvolvement, +} from "@t3tools/contracts"; + +import { + filterPullRequestFeed, + hiddenPullRequestLinks, + hiddenPullRequestUrls, + isPullRequestHidden, + pullRequestFeedVisibility, + pullRequestProjectHidesRepository, + pullRequestRepositoryHidden, + pullRequestRepositoryRules, + pullRequestFeedGroup, + pullRequestFeedRule, + pullRequestFeedShows, + pullRequestInvolvedMatcher, + pullRequestListedGroup, + 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, PullRequestInvolvement, boolean, 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], + ["involved", "authored", "all", true], + ["involved", "reviewRequested", "all", true], + ["involved", "others", "all", false], + // The host's involved listing holds the row: a comment, mention, or assignment. + ["involved", "others", "all", true, true], + ["involved", "others", "authored", true], + ])("%s shows a %s row under %s: %s", (rule, group, involvement, shown, involved) => { + expect(pullRequestFeedShows(rule, group, involvement, involved)).toBe(shown); + }); + + it("takes an involved project's rows only from its listing, unless it is not ready", () => { + const row = (projectId: string, url: string) => ({ projectId, url }); + // A search, or no read: every row counts, as under the All rule. + expect(pullRequestInvolvedMatcher(null)(row("web", "https://h/a/1"))).toBe(true); + const involved = pullRequestInvolvedMatcher({ + entries: [row("web", "https://h/a/1")], + ready: (entry: { readonly url: string; readonly projectId: string }) => + entry.projectId !== "failed", + }); + expect(involved(row("web", "https://h/a/1"))).toBe(true); + expect(involved(row("web", "https://h/a/2"))).toBe(false); + // A failed, pending, or unindexed listing shows the project's rows. + expect(involved(row("failed", "https://h/b/1"))).toBe(true); + }); + + 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"); + // GitCafe lists a synced pull request as authored by actor, under a login not the viewer's. + const synced = { + url: "https://h/a/1", + author: { login: "github-me" }, + viewerReviewRequested: false, + }; + const listed = { authored: new Set([synced.url]), reviewing: new Set() }; + expect(pullRequestListedGroup(synced, "cafe-me", listed)).toBe("authored"); + }); + + 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, + rulesFor: (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, + 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.each< + [string, PullRequestFeedRule, PullRequestFeedGroup, PullRequestFeedGroup, boolean, 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], + ["admits an Others row the host lists as involved", "involved", "others", "others", true, true], + ["drops an Others row the host does not list", "involved", "others", "others", false, false], + ])("%s", (_, rule, listGroup, ownGroup, shown, involved) => { + expect( + pullRequestFeedVisibility({ url: "https://h/a/1" }, listGroup, { + scopedToProject: false, + involvement: "all", + rulesFor: () => [rule], + hidden: new Set(), + groupOf: () => ownGroup, + involved: () => involved === true, + }), + ).toBe(shown ? "shown" : "rule"); + }); + + it.each<[string, PullRequestFeedRule, boolean, boolean]>([ + ["a connected holder hides", "hidden", true, true], + ["an offline holder does not", "hidden", false, false], + ["another rule does not", "authored", true, false], + ])("%s its repository", (_, rule, connected, hides) => { + expect(pullRequestProjectHidesRepository(rule, { connected })).toBe(hides); + }); + + it("rules out every environment's copy of a repository one environment hides", () => { + 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, + rulesFor: () => ["all" as const], + hidden: new Set(), + 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", + "shown", + ]); + expect( + pullRequestFeedVisibility(rows[1]!, "others", { ...options, scopedToProject: true }), + ).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"); + // 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", + (entry) => (entry.environmentId === "env-2" ? "all" : "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", + ]); + // 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", () => { + const settings = [ + { hiddenPullRequests: { "https://h/a/1": "https://H/A/1" } }, + null, + { + hiddenPullRequests: { "https://H/A/1": "https://h/a/1", "https://h/b/2": "https://h/b/2" }, + }, + ]; + expect([...hiddenPullRequestLinks(settings)]).toEqual([ + ["https://h/a/1", "https://H/A/1"], + ["https://h/b/2", "https://h/b/2"], + ]); + expect(isPullRequestHidden(hiddenPullRequestUrls(settings), "https://h/A/1")).toBe(true); + }); +}); diff --git a/packages/client-runtime/src/pullRequestFeed.ts b/packages/client-runtime/src/pullRequestFeed.ts new file mode 100644 index 0000000000000..ac8bee49b0b6a --- /dev/null +++ b/packages/client-runtime/src/pullRequestFeed.ts @@ -0,0 +1,288 @@ +import type { + ProjectId, + PullRequestFeedRule, + PullRequestInvolvement, + 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: "involved", label: "Involving me" }, + { value: "reviewing", label: "Waiting on me" }, + { value: "authored", label: "Authored by me" }, + { value: "hidden", label: "Hidden" }, +]; + +/** The rules every server to write can store; servers without `pullRequestFeedInvolved` refuse it. */ +export function pullRequestFeedRuleOptions( + capabilities: Iterable<{ readonly pullRequestFeedInvolved?: boolean } | undefined>, +): typeof PULL_REQUEST_FEED_RULES { + for (const capability of capabilities) { + if (capability?.pullRequestFeedInvolved !== true) { + return PULL_REQUEST_FEED_RULES.filter((option) => option.value !== "involved"); + } + } + return PULL_REQUEST_FEED_RULES; +} + +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 row an authored or review-requested listing returned keeps that group even when its author + * login is not the viewer's: the host matched it another way, as GitCafe does by actor. The server + * already checks the rows of hosts that ignore those listings. + */ +export function pullRequestListedGroup( + entry: Parameters[0] & { readonly url: string }, + viewer: string | null | undefined, + listed: { readonly authored: ReadonlySet; readonly reviewing: ReadonlySet }, +): PullRequestFeedGroup { + if (listed.authored.has(entry.url)) return "authored"; + const own = pullRequestFeedGroup(entry, viewer); + return own === "others" && listed.reviewing.has(entry.url) ? "reviewRequested" : own; +} + +/** + * A narrowed involvement tab holds one group of that kind, whatever its key says. `involved` says + * the host lists the viewer as taking part in an Others row, by a comment, mention, or assignment. + */ +export function pullRequestFeedShows( + rule: PullRequestFeedRule, + group: PullRequestFeedGroup, + involvement: PullRequestInvolvement = "all", + involved = false, +): boolean { + const kind = + involvement === "authored" + ? "authored" + : involvement === "reviewing" + ? "reviewRequested" + : group; + switch (rule) { + case "all": + return true; + case "hidden": + return false; + case "involved": + return kind !== "others" || involved; + case "authored": + return kind === "authored"; + case "reviewing": + return kind === "reviewRequested"; + } +} + +/** + * For `PullRequestFeedOptions.involved`: a row is involved when its project's involved listing + * holds it. With no answer (a search, or no read), or for a project whose listing is not ready + * (not read, pending, failed, or unindexed), every row counts, as under the All rule. + */ +export function pullRequestInvolvedMatcher( + answer: { + readonly entries: ReadonlyArray<{ readonly url: string }>; + readonly ready: (entry: Row) => boolean; + } | null, +): (entry: Row) => boolean { + if (answer === null) return () => true; + const urls = new Set(answer.entries.map((entry) => entry.url)); + return (entry) => urls.has(entry.url) || !answer.ready(entry); +} + +type HiddenSettings = Pick | null | undefined; + +/** The key a hidden link is stored under; hiding or unhiding patches only this key. */ +export const hiddenPullRequestKey = (url: string): string => url.toLowerCase(); + +/** + * Every environment's hidden links, keyed by `hiddenPullRequestKey`, each in the spelling it was + * hidden with, so a pull request stays hidden when another environment serves it. + */ +export function hiddenPullRequestLinks( + settings: Iterable, +): ReadonlyMap { + const links = new Map(); + for (const entry of settings) { + for (const [key, url] of Object.entries(entry?.hiddenPullRequests ?? {})) { + if (!links.has(hiddenPullRequestKey(key))) links.set(hiddenPullRequestKey(key), url); + } + } + return links; +} + +export function hiddenPullRequestUrls(settings: Iterable): ReadonlySet { + return new Set(hiddenPullRequestLinks(settings).keys()); +} + +export function isPullRequestHidden(hidden: ReadonlySet, url: string): boolean { + return hidden.size > 0 && hidden.has(hiddenPullRequestKey(url)); +} + +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 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. */ + readonly groupOf?: (entry: Entry) => PullRequestFeedGroup; + /** Whether the host's `involved` listing holds the row; absent counts only the row's group. */ + readonly involved?: (entry: Entry) => boolean; + /** A repository another environment's project hides, read before copies merge. */ + readonly repositoryHidden?: (entry: Entry) => boolean; +} + +/** + * Whether a project's `hidden` rule removes its repository from every environment's list. Only a + * connected environment counts, so an offline one's cached rule cannot trap the repository. + */ +export function pullRequestProjectHidesRepository( + rule: PullRequestFeedRule, + environment: { readonly connected: boolean }, +): boolean { + return rule === "hidden" && environment.connected; +} + +/** + * 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( + 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); + }; +} + +type RepositoryProject = { + readonly id: ProjectId; + readonly environmentId: string; + readonly repositoryIdentity?: { readonly canonicalKey?: string | undefined } | null | undefined; +}; + +/** + * 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, + 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}`); + const counted = key === undefined ? undefined : rules.get(key); + return counted ?? [ownRuleOf(entry)]; + }; +} + +/** `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) { + let ownGroup: PullRequestFeedGroup | undefined; + const admitted = + options.repositoryHidden?.(entry) !== true && + options.rulesFor(entry).some((rule) => { + const involved = rule === "involved" && options.involved?.(entry) === true; + if (pullRequestFeedShows(rule, group, options.involvement, involved)) return true; + ownGroup ??= options.groupOf?.(entry); + return ( + ownGroup !== undefined && + pullRequestFeedShows(rule, ownGroup, options.involvement, involved) + ); + }); + if (!admitted) 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; + 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, ruledOutCount }; +} diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 603b6c6cc862d..00bb4dbe6de79 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -117,6 +117,10 @@ 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), + /** Stores the `involved` feed rule and lists `involved` pull requests; hide the rule where absent. */ + pullRequestFeedInvolved: 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), 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"])), diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index d438080369a40..95b91e1fe1743 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -14,7 +14,8 @@ import { } from "./baseSchemas.ts"; import { SourceControlProviderKind } from "./sourceControl.ts"; -export const PullRequestInvolvement = Schema.Literals(["all", "reviewing", "authored"]); +/** `involved` also takes in pull requests the viewer is assigned to, mentioned in, or commented on. */ +export const PullRequestInvolvement = Schema.Literals(["all", "reviewing", "authored", "involved"]); export type PullRequestInvolvement = typeof PullRequestInvolvement.Type; export const PullRequestState = Schema.Literals(["open", "closed", "merged"]); @@ -63,6 +64,29 @@ 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", + "involved", + "reviewing", + "authored", + "hidden", +]); +export type PullRequestFeedRule = typeof PullRequestFeedRule.Type; + +const HiddenPullRequestUrl = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(2048)); +/** + * Pull requests hidden from the feed: the lowercased URL maps to the URL as the user hid it. A + * record, not a list, so each hide or unhide patches one key and writers cannot erase each other. + */ +export const HiddenPullRequests = Schema.Record(HiddenPullRequestUrl, HiddenPullRequestUrl); +export type HiddenPullRequests = typeof HiddenPullRequests.Type; +/** A URL hides that link, `null` shows it again. */ +export const HiddenPullRequestsPatch = Schema.Record( + HiddenPullRequestUrl, + Schema.NullOr(HiddenPullRequestUrl), +); + export const PullRequestAction = Schema.Literals([ "merge", "ready", diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index e7cea79c7663e..e57010c4f8df1 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -416,6 +416,30 @@ describe("ServerSettings environment icon", () => { }); }); +describe("ServerSettings pull request feed", () => { + it("reads a rule from a newer server as the default instead of failing the snapshot", () => { + const projectId = ProjectId.make("project-a"); + const settings = decodeServerSettings({ + pullRequestFeed: "starred", + projectSettingsOverrides: { [projectId]: { pullRequestFeed: "starred" } }, + }); + expect(settings.pullRequestFeed).toBe("all"); + expect(settings.projectSettingsOverrides[projectId]?.pullRequestFeed).toBeUndefined(); + expect(decodeServerSettings({ pullRequestFeed: "involved" }).pullRequestFeed).toBe("involved"); + // A write keeps the strict rule, so a bad value fails instead of clearing the override. + expect(() => + decodeServerSettingsPatch({ + projectSettingsOverrides: { [projectId]: { pullRequestFeed: "starred" } }, + }), + ).toThrow(); + expect( + decodeServerSettingsPatch({ + projectSettingsOverrides: { [projectId]: { pullRequestFeed: "involved" } }, + }).projectSettingsOverrides?.[projectId], + ).toEqual({ pullRequestFeed: "involved" }); + }); +}); + const decodeDeviceHostSettings = Schema.decodeSync(ServerSettings); // `deviceHosts` as it was decoded before Expo hosts existed: an SSH host needs a target. diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 0013e288983e0..eec3d96bfc921 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -53,7 +53,12 @@ import { ProviderInstanceId, ProviderDriverKind, } from "./providerInstance.ts"; -import { PullRequestMergeMethod } from "./pullRequest.ts"; +import { + HiddenPullRequests, + HiddenPullRequestsPatch, + PullRequestFeedRule, + PullRequestMergeMethod, +} from "./pullRequest.ts"; import { CloudSpeechModelId, SpeechAcceleration, @@ -1191,6 +1196,7 @@ export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [ "branchNamePrefix", "branchNameInstructions", "pullRequestMergeMethod", + "pullRequestFeed", "sidebarAutoSettleOnMerge", "sidebarAutoSettleAfterDays", "sidebarAutoSettleKeepPullRequests", @@ -1229,6 +1235,7 @@ export const ProjectSettingsOverrides = Schema.Struct({ branchNamePrefix: Schema.optionalKey(TrimmedString), branchNameInstructions: Schema.optionalKey(TrimmedString), pullRequestMergeMethod: Schema.optionalKey(Schema.NullOr(PullRequestMergeMethod)), + pullRequestFeed: ForwardCompatibleOptional(PullRequestFeedRule), sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean), sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)), sidebarAutoSettleKeepPullRequests: Schema.optionalKey(Schema.Boolean), @@ -1559,6 +1566,18 @@ export const ServerSettings = Schema.Struct({ pullRequestMergeMethod: Schema.NullOr(PullRequestMergeMethod).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), + /** A rule from a newer version reads as `all`, so one unknown value cannot fail the settings. */ + pullRequestFeed: ForwardCompatibleNullable(PullRequestFeedRule).pipe( + Schema.decodeTo( + PullRequestFeedRule, + SchemaTransformation.transform({ + decode: (rule) => rule ?? "all", + encode: (rule) => rule, + }), + ), + 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( @@ -1882,6 +1901,8 @@ export const ServerSettingsPatch = Schema.Struct({ keepUnknownOverrideKeys( Schema.Struct({ ...ProjectSettingsOverrides.fields, + // A write names a rule this server knows; only stored snapshots read unknown ones. + pullRequestFeed: Schema.optionalKey(Schema.UndefinedOr(PullRequestFeedRule)), sourceControlWritingStyle: Schema.optionalKey(SourceControlWritingStyleSettings), }), ), @@ -1947,6 +1968,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(HiddenPullRequestsPatch), observability: Schema.optionalKey( Schema.Struct({ otlpTracesUrl: Schema.optionalKey(TrimmedString), 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/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 023c6eb74333e..4fa7400f2ca4c 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -235,6 +235,9 @@ function mergeModelSelectionOptionsById(input: { return [...merged.entries()].map(([id, value]) => ({ id, value })); } +const lowercaseKeys = (record: Readonly>) => + Object.fromEntries(Object.entries(record).map(([key, value]) => [key.toLowerCase(), value])); + function mergeSettingsEntries( current: Readonly>, patch: Readonly>, @@ -407,6 +410,7 @@ export function applyServerSettingsPatch( sourceControlHosts: sourceControlHostsPatch, usagePriceOverrides: usagePriceOverridesPatch, usageModelAliases: usageModelAliasesPatch, + hiddenPullRequests: hiddenPullRequestsPatch, // Entry replacement: deepMerge would keep keys the client meant to clear. projectSettingsOverrides: projectSettingsOverridesPatch, projectAgentBrowserAccessOverrides: _legacyBrowserAccess, @@ -642,6 +646,16 @@ export function applyServerSettingsPatch( ), } : {}), + // lean: the record holds only hidden links, unbounded until users hide thousands of them. + ...(hiddenPullRequestsPatch !== undefined + ? { + // Keys are lowercased on both sides, so any spelling of a stored link can be cleared. + hiddenPullRequests: mergeSettingsEntries( + lowercaseKeys(current.hiddenPullRequests), + lowercaseKeys(hiddenPullRequestsPatch), + ), + } + : {}), ...(patch.sourceControlWriterModelSelection !== undefined ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection } : {}), diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts index 7ed77ab5a4ec7..aad9ff60cca5c 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts @@ -265,6 +265,8 @@ function involvementArgs(input: { return ["--creator", input.viewer]; case "reviewing": return ["--reviewer", input.viewer]; + // Azure DevOps has no filter for every pull request the viewer takes part in; see `listsInvolved`. + case "involved": case "all": return []; } diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts index 9d5015ca68096..49d2c2fc1b978 100644 --- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts +++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts @@ -175,6 +175,7 @@ export const make = Effect.gen(function* () { servesHost, unavailableRequirement: UNAVAILABLE_REQUIREMENT, readsPublicHostWithoutCheckout: true, + ignoresInvolvement: ["authored", "reviewing"], getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))), diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index cf4d30d2ccaee..52e986ac1c890 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -337,6 +337,13 @@ export interface PullRequestProviderApi { readonly readsPublicHostWithoutCheckout?: boolean; /** Concurrent summary reads share requests, so callers may keep many in flight. */ readonly batchesReads?: boolean; + /** + * Narrows `involved` on the host, comments and mentions included. Other providers answer + * `involved` with nothing; clients use the authored and review-requested reads instead. + */ + readonly listsInvolved?: boolean; + /** Listings it answers with every row although the caller asked for them narrowed. */ + readonly ignoresInvolvement?: ReadonlyArray<"authored" | "reviewing">; /** * Absent means every host detected as this kind is read. A host it refuses is listed as one that * cannot be browsed here, and nothing is sent for it. diff --git a/packages/source-control-cursor-origin/src/server/OriginPullRequestProvider.ts b/packages/source-control-cursor-origin/src/server/OriginPullRequestProvider.ts index 502730d97ad28..546fa59aef1e9 100644 --- a/packages/source-control-cursor-origin/src/server/OriginPullRequestProvider.ts +++ b/packages/source-control-cursor-origin/src/server/OriginPullRequestProvider.ts @@ -583,6 +583,7 @@ export const make = Effect.gen(function* () { const provider: PullRequestProviderApi = { kind: SourceControlProviderKind.make("cursor-origin"), capabilities: CAPABILITIES, + ignoresInvolvement: ["reviewing"], getViewer: Effect.fn("OriginPullRequestProvider.getViewer")( function* (input) { diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts index 70114b9fe45dd..1f77fed74403f 100644 --- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts @@ -289,6 +289,7 @@ export const make = Effect.gen(function* () { capabilities: CAPABILITIES, unavailableRequirement: UNAVAILABLE_REQUIREMENT, readsPublicHostWithoutCheckout: true, + ignoresInvolvement: ["authored", "reviewing"], getViewer, listChangeRequests: Effect.fn("ForgejoPullRequestProvider.listChangeRequests")( function* (input) { diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts index 314fc30902751..4a3caeb846eca 100644 --- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts +++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts @@ -794,6 +794,9 @@ export const make = Effect.gen(function* () { const provider: PullRequestProviderApi = { kind: SourceControlProviderKind.make("gitcafe"), capabilities: CAPABILITIES, + // Without the principal the listing comes back unnarrowed. A narrowed review answer already + // names the viewer among reviewers; its authored answer matches by actor, not by login. + ignoresInvolvement: ["reviewing"], getViewer: (input) => read( "getViewer", diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index 5668eedceb69f..432e1e0476397 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -1563,6 +1563,20 @@ layer("GitHubPullRequestApi.layer", (it) => { 'is:pr is:closed is:unmerged review-requested:bilal "pull requests page" ' + "updated:<=2026-07-02T00:00:00Z sort:updated-desc repo:acme/web repo:pingdotgg/t3code", ); + + yield* cli.searchPullRequests({ + cwd: "/w", + host: "github.com", + repositories: ["acme/web"], + state: "open", + involvement: "involved", + viewer: "bilal", + limit: 10, + }); + assert.strictEqual( + searchQueryOfCall(1), + "is:pr is:open involves:bilal sort:updated-desc repo:acme/web", + ); }), ); @@ -2196,6 +2210,46 @@ layer("GitHubPullRequestApi.layer", (it) => { expect(batch.items.map((item) => item.number)).toEqual([1, 2]); expect(searchOfCall(1)).toBeUndefined(); assert.isFalse(batch.continues); + + // The listing cannot see mentions or comments, so `involved` does not read it. + mockedExecute.mockReturnValueOnce(Effect.succeed(emptySearch())); + const involved = yield* cli.listPullRequests({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + state: "open", + involvement: "involved", + viewer: "bilal", + limit: 10, + }); + expect(involved).toMatchObject({ items: [], truncated: false, continues: false }); + assert.strictEqual(mockedExecute.mock.calls.length, 3); + + // An empty page that has rows it could not hand over cannot be continued, so it fails. + // Rows GitHub sent but this client cannot read still count toward the page. + mockedExecute.mockReturnValueOnce( + Effect.succeed( + output( + encodeJson({ + data: { + search: { pageInfo: lastPage, nodes: Array.from({ length: 11 }, () => ({})) }, + }, + }), + ), + ), + ); + const stopped = yield* Effect.flip( + cli.listPullRequests({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + state: "open", + involvement: "involved", + viewer: "bilal", + limit: 10, + }), + ); + assert.strictEqual(stopped._tag, "GitHubPullRequestReadError"); }), ); diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index 5454926281fcc..b022e8d2342ee 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -919,6 +919,7 @@ function matchesUnsortedListing( ): boolean { const matchesState = input.state === "all" || item.state === input.state; const viewer = input.viewer.toLowerCase(); + // `involved` never reaches this listing: `listPullRequests` does not fall back for it. const matchesInvolvement = input.involvement === "all" || (input.involvement === "authored" @@ -951,6 +952,7 @@ function searchQuery(input: { ...(input.state === "merged" ? ["is:merged"] : []), ...(input.involvement === "authored" ? [`author:${input.viewer}`] : []), ...(input.involvement === "reviewing" ? [`review-requested:${input.viewer}`] : []), + ...(input.involvement === "involved" ? [`involves:${input.viewer}`] : []), ...(query.length === 0 ? [] : [searchPhrase(query)]), ...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]), ...filterQualifiers(input.filters, input.viewer), @@ -1959,7 +1961,21 @@ export const make = Effect.gen(function* () { const listed = read(true).pipe( Effect.filterOrElse( (batch) => batch.items.length > 0 || input.cursor !== undefined || hasQuery, - () => read(false), + // The listing has no comments, mentions, or assignees, so it cannot answer `involved`; + // the provider tells an empty answer from an unindexed repository. + // A truncated empty page has rows it could not hand over, and no cursor to reach them. + (batch) => + input.involvement !== "involved" + ? read(false) + : batch.truncated + ? Effect.fail( + new GitHubPullRequestReadError({ + cwd: input.cwd, + operation: "listPullRequests", + cause: new Error("The involved search stopped before its first row."), + }), + ) + : Effect.succeed({ items: [], truncated: false, continues: false }), ), Effect.filterOrElse( (batch) => !stacks || batch.items.length === 0, diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts index 5911bd3c3a117..59c70fe6a6361 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts @@ -987,6 +987,37 @@ describe("listChangeRequestsAcross", () => { }), ); + it.effect("answers an empty involved read only where search covers the repository", () => + Effect.gen(function* () { + const provider = yield* make.pipe( + Effect.provide( + Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({ + listPullRequests: () => + Effect.succeed({ items: [], truncated: false, continues: false }), + searchPullRequests: (search: Search) => + Effect.succeed({ + items: search.repositories[0] === "acme/web" ? [searched("acme/web")] : [], + truncated: false, + }), + }), + ), + ); + const read = (repository: string) => + provider.listChangeRequests({ + cwd: "/w", + host: "github.com", + repository, + state: "open", + involvement: "involved", + viewer: "viewer", + limit: 50, + }); + expect((yield* read("acme/web")).truncated).toBe(false); + // The caller files a failed read as one it cannot rule on. + expect((yield* Effect.flip(read("acme/renamed"))).reason).toBe("failed"); + }), + ); + it.effect("leaves a repository search does not cover to be read on its own", () => Effect.gen(function* () { const read = yield* providerAnswering({ diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index 447ee691c3897..96eb26426b0db 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -275,7 +275,10 @@ export const make = Effect.gen(function* () { timeToLive: (exit) => (Exit.isSuccess(exit) ? SEARCH_COVERAGE_TTL : Duration.zero), }); const coverageOf = ( - input: Parameters>[0], + input: Pick< + Parameters>[0], + "cwd" | "host" | "viewer" + >, repository: string, ) => new SearchCoverage( @@ -401,6 +404,7 @@ export const make = Effect.gen(function* () { unavailableRequirement: UNAVAILABLE_REQUIREMENT, readsPublicHostWithoutCheckout: true, batchesReads: true, + listsInvolved: true, mergeMessageRewrite: removeAgentCredits, getRoutingIdentity: (input) => cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))), @@ -430,6 +434,30 @@ export const make = Effect.gen(function* () { }) .pipe( Effect.mapError(fail("listChangeRequests")), + // An empty `involved` search is an answer only where search covers the repository; + // elsewhere the read fails, so the caller cannot rule on that repository's rows. + Effect.filterOrElse( + (page) => + input.involvement !== "involved" || + page.items.length > 0 || + input.cursor !== undefined, + (page) => + Cache.get(searchCoverage, coverageOf(input, input.repository)).pipe( + Effect.orElseSucceed(() => false), + Effect.filterOrFail( + (covered) => covered, + () => + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation: "listChangeRequests", + reason: "failed", + detail: + "Search does not index this repository, so it cannot list involved pull requests.", + }), + ), + Effect.as(page), + ), + ), Effect.map((page) => ({ ...page, items: page.items.map((item) => ({ diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts index b8ad433c96df7..154587bf64171 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts @@ -795,6 +795,8 @@ function involvementParams(input: { return [["author_username", input.viewer]]; case "reviewing": return [["reviewer_username", input.viewer]]; + // GitLab has no filter for every merge request the viewer takes part in; see `listsInvolved`. + case "involved": case "all": return []; } 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." 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") ?? "" ]