merge main into usage environment filters
# Conflicts: # apps/mobile/src/features/usage/UsageRouteScreen.tsx # apps/mobile/src/state/usage.ts # apps/web/src/components/usage/UsagePage.tsx # apps/web/src/state/usage.ts
This commit is contained in:
commit
845cd352de
280 files changed
+40167
-2188
No files matched your search
@@ -5,6 +5,25 @@ name: Mobile EAS Production
|
||||
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
|
||||
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
|
||||
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
|
||||
#
|
||||
# Every merge to main that touches the mobile app reconciles, per platform:
|
||||
# 1. Store builds: if the latest production build's version differs from
|
||||
# app.config.ts, cut a new build and submit it (TestFlight + Play internal
|
||||
# track). Bumping `version` is therefore all it takes to
|
||||
# start the next release train — the first build of a version enters
|
||||
# external-TestFlight beta review immediately, and later builds of the
|
||||
# same version auto-approve until that version is released. After App
|
||||
# Store approval, Apple closes the release train and `version` must be
|
||||
# bumped before another iOS build can be submitted. Releasing to the App
|
||||
# Store stays a manual App Store Connect step.
|
||||
# 2. OTA: publish a production-channel update for each platform where at
|
||||
# least one finished production build matches the current native
|
||||
# fingerprint. Old-version binaries with a matching fingerprint receive
|
||||
# it too. When native drift means no binary could install the update,
|
||||
# it is skipped and flagged in the job summary instead of published
|
||||
# into the void.
|
||||
# workflow_dispatch remains as a manual override for both modes (e.g. to
|
||||
# retry an errored build or force an OTA).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
@@ -25,14 +44,38 @@ on:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
version:
|
||||
description: "Optional build version override (blank uses app.config.ts; an override is committed before building)"
|
||||
required: false
|
||||
type: string
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- apps/mobile/**
|
||||
- packages/client-runtime/**
|
||||
- packages/contracts/**
|
||||
- packages/shared/**
|
||||
- assets/**
|
||||
- scripts/**
|
||||
- patches/**
|
||||
- pnpm-lock.yaml
|
||||
- pnpm-workspace.yaml
|
||||
- .github/workflows/mobile-eas-production.yml
|
||||
|
||||
# Serialize runs so OTAs publish in merge order. GitHub keeps at most one
|
||||
# queued run per group, so a burst of merges collapses into one run of the
|
||||
# newest commit — intermediate commits don't need their own OTA.
|
||||
concurrency:
|
||||
group: mobile-eas-production
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
name: EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -52,11 +95,21 @@ jobs:
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- id: version_app_token
|
||||
name: Mint release app token for version override
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != ''
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.version_app_token.outputs.token || github.token }}
|
||||
# No sparse-checkout here: it makes actions/checkout fetch with
|
||||
# --filter=blob:none, and eas-cli archives the project via
|
||||
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
|
||||
@@ -98,15 +151,74 @@ jobs:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
|
||||
- name: Apply manual version override
|
||||
if: steps.version_app_token.outcome == 'success'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.version_app_token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }}
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
if [ "$GITHUB_REF_TYPE" != "branch" ]; then
|
||||
echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then
|
||||
echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node --input-type=module -e '
|
||||
import fs from "node:fs";
|
||||
const path = "apps/mobile/app.config.ts";
|
||||
const source = fs.readFileSync(path, "utf8");
|
||||
const next = source.replace(
|
||||
/^( version: ")[^"]+(".*)$/m,
|
||||
`$1${process.env.RELEASE_VERSION}$2`,
|
||||
);
|
||||
if (next === source && !source.includes(` version: "${process.env.RELEASE_VERSION}"`)) {
|
||||
throw new Error("Could not update app version");
|
||||
}
|
||||
fs.writeFileSync(path, next);
|
||||
'
|
||||
vp fmt apps/mobile/app.config.ts
|
||||
|
||||
if git diff --quiet -- apps/mobile/app.config.ts; then
|
||||
echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
|
||||
git config user.name "${APP_SLUG}[bot]"
|
||||
git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com"
|
||||
git add apps/mobile/app.config.ts
|
||||
git commit \
|
||||
-m "chore(mobile): bump app version to $RELEASE_VERSION" \
|
||||
-m "Co-authored-by: codex <[email protected]>"
|
||||
git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}"
|
||||
|
||||
- name: Summarize manual build version
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
run: |
|
||||
version="$(npx expo config --json --type public | jq -r '.version')"
|
||||
{
|
||||
echo "## Manual production build"
|
||||
echo
|
||||
echo "- App version: \`$version\`"
|
||||
echo "- Platform: \`${{ inputs.platform }}\`"
|
||||
echo
|
||||
echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version."
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Build and submit (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
|
||||
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
- name: Publish OTA update (manual)
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
@@ -117,3 +229,62 @@ jobs:
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
|
||||
# No --status filter on build:list: an in-queue/in-progress build must
|
||||
# count as existing, or every merge during the build window would cut a
|
||||
# duplicate. After an errored build, retry via workflow_dispatch
|
||||
# mode=build — pushes won't re-trigger it until the app version changes.
|
||||
- id: store_builds
|
||||
name: Ensure store builds exist for the current app version
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
|
||||
continue-on-error: true
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
failed=0
|
||||
version="$(npx expo config --json --type public | jq -r '.version')"
|
||||
for platform in ios android; do
|
||||
latest="$(eas build:list --platform "$platform" --build-profile production --limit 1 --json --non-interactive | jq -r '.[0].appVersion // "none"')"
|
||||
if [ "$latest" = "$version" ]; then
|
||||
echo "$platform: production build for $version already exists (or is in progress)"
|
||||
continue
|
||||
fi
|
||||
echo "$platform: latest production build is $latest, app.config.ts says $version — building"
|
||||
if eas build --platform "$platform" --profile production --auto-submit --non-interactive --no-wait; then
|
||||
echo ":building_construction: $platform: scheduled production build and submission for $version" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
failed=1
|
||||
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
done
|
||||
exit "$failed"
|
||||
|
||||
- name: Publish fingerprint-gated OTA
|
||||
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))"
|
||||
for platform in ios android; do
|
||||
# eas-cli prints an environment-loaded notice to stdout before the
|
||||
# JSON even with --json, so discard everything before the document.
|
||||
hash="$(eas fingerprint:generate --platform "$platform" --environment production --json --non-interactive | sed -n '/^{/,$p' | jq -er '.hash | select(type == "string" and length > 0)')"
|
||||
matching="$(eas build:list --platform "$platform" --build-profile production --status finished --fingerprint-hash "$hash" --limit 1 --json --non-interactive | jq 'length')"
|
||||
if [ "$matching" -gt 0 ]; then
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform "$platform" \
|
||||
--message "$message" \
|
||||
--non-interactive
|
||||
echo ":white_check_mark: $platform: OTA published to production (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo ":warning: $platform: no finished production build matches fingerprint \`$hash\` — OTA skipped; JS changes reach $platform only once a matching build ships" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Propagate store build failure
|
||||
if: steps.store_builds.outcome == 'failure'
|
||||
run: exit 1
|
||||
@@ -0,0 +1,205 @@
|
||||
name: Mobile Fingerprint Check
|
||||
|
||||
# Detects whether a PR changes the native fingerprint — i.e. whether merging
|
||||
# it would leave main un-OTA-able until a new store build ships. Native-change
|
||||
# PRs get the "📱 Native Change" label so they can be held and merged as a
|
||||
# batch right before the next store submission, keeping main OTA-able for
|
||||
# everything else in between. (Once one native PR merges, every later merge
|
||||
# inherits the drifted fingerprint and loses OTA reach too — that is why the
|
||||
# signal has to fire before merge, not after.)
|
||||
#
|
||||
# The check is advisory: it always passes, the label is the signal. Both
|
||||
# fingerprints are computed in this one job (same OS, same corepack-pinned
|
||||
# pnpm), so the comparison is self-consistent; no EXPO_TOKEN needed.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- apps/mobile/**
|
||||
- packages/client-runtime/**
|
||||
- packages/contracts/**
|
||||
- packages/shared/**
|
||||
- assets/**
|
||||
- scripts/**
|
||||
- patches/**
|
||||
- pnpm-lock.yaml
|
||||
- pnpm-workspace.yaml
|
||||
- .github/workflows/mobile-fingerprint-check.yml
|
||||
|
||||
concurrency:
|
||||
group: mobile-fingerprint-check-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
fingerprint:
|
||||
name: Native fingerprint diff
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
# Default pull_request checkout is the merge commit (PR applied on
|
||||
# top of base), so the "head" fingerprint is the state main would
|
||||
# actually be in after merging — stale branches compare cleanly.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/mobile...
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Fingerprint merge result
|
||||
working-directory: apps/mobile
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/fp/head" "$RUNNER_TEMP/fp/base"
|
||||
for platform in ios android; do
|
||||
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/head/$platform.json"
|
||||
done
|
||||
|
||||
- name: Fingerprint base
|
||||
run: |
|
||||
git checkout --quiet "${{ github.event.pull_request.base.sha }}"
|
||||
# Re-sync node_modules to the base commit's lockfile before
|
||||
# fingerprinting — a dep-changing PR must not fingerprint the base
|
||||
# against head's installed packages.
|
||||
pnpm install --filter=@t3tools/mobile...
|
||||
cd apps/mobile
|
||||
for platform in ios android; do
|
||||
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/base/$platform.json"
|
||||
done
|
||||
|
||||
- id: compare
|
||||
name: Compare fingerprints
|
||||
run: |
|
||||
changed=""
|
||||
{
|
||||
echo "## Native fingerprint diff"
|
||||
echo
|
||||
for platform in ios android; do
|
||||
head_hash="$(jq -r .hash "$RUNNER_TEMP/fp/head/$platform.json")"
|
||||
base_hash="$(jq -r .hash "$RUNNER_TEMP/fp/base/$platform.json")"
|
||||
if [ "$head_hash" = "$base_hash" ]; then
|
||||
echo "- ✅ **$platform**: unchanged (\`$head_hash\`) — OTA-compatible"
|
||||
continue
|
||||
fi
|
||||
changed="$changed $platform"
|
||||
echo "- 📱 **$platform**: \`$base_hash\` → \`$head_hash\` — merging requires a new native build before OTAs work again"
|
||||
jq -r -n \
|
||||
--slurpfile h "$RUNNER_TEMP/fp/head/$platform.json" \
|
||||
--slurpfile b "$RUNNER_TEMP/fp/base/$platform.json" '
|
||||
($b[0].sources | map({ (.filePath // .id): .hash }) | add // {}) as $bm
|
||||
| $h[0].sources[]
|
||||
| select($bm[(.filePath // .id)] != .hash)
|
||||
| " - \(.type): `\(.filePath // .id)`"'
|
||||
done
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "changed_platforms=${changed# }" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Sync native change label
|
||||
# Fork PRs get a read-only token under pull_request; the check stays
|
||||
# advisory there (summary only). This workflow must not move to
|
||||
# pull_request_target — it installs and runs PR code.
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
CHANGED_PLATFORMS: ${{ steps.compare.outputs.changed_platforms }}
|
||||
with:
|
||||
script: |
|
||||
const managedLabel = {
|
||||
name: "📱 Native Change",
|
||||
color: "d93f0b",
|
||||
description:
|
||||
"Changes the native fingerprint; merging blocks production OTAs until a new store build ships.",
|
||||
};
|
||||
const nativeChanged = (process.env.CHANGED_PLATFORMS ?? "").trim() !== "";
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
|
||||
try {
|
||||
const { data: existing } = await github.rest.issues.getLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
});
|
||||
|
||||
if (
|
||||
existing.color !== managedLabel.color ||
|
||||
(existing.description ?? "") !== managedLabel.description
|
||||
) {
|
||||
await github.rest.issues.updateLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
color: managedLabel.color,
|
||||
description: managedLabel.description,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
name: managedLabel.name,
|
||||
color: managedLabel.color,
|
||||
description: managedLabel.description,
|
||||
});
|
||||
} catch (createError) {
|
||||
if (createError.status !== 422) {
|
||||
throw createError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const hasLabel = currentLabels.some((label) => label.name === managedLabel.name);
|
||||
|
||||
if (nativeChanged && !hasLabel) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: [managedLabel.name],
|
||||
});
|
||||
} else if (!nativeChanged && hasLabel) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
name: managedLabel.name,
|
||||
});
|
||||
} catch (removeError) {
|
||||
if (removeError.status !== 404) {
|
||||
throw removeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
core.info(
|
||||
`PR #${issueNumber}: native fingerprint ${nativeChanged ? `changed (${process.env.CHANGED_PLATFORMS})` : "unchanged"}`,
|
||||
);
|
||||
@@ -746,7 +746,7 @@ jobs:
|
||||
needs: [preflight, build, publish_cli]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.32",
|
||||
"version": "0.0.33",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -28,70 +28,6 @@ describe("ElectronDialog", () => {
|
||||
showErrorBoxMock.mockReset();
|
||||
});
|
||||
|
||||
it.effect("returns false without opening a confirm dialog for empty messages", () =>
|
||||
Effect.gen(function* () {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: " ",
|
||||
owner: Option.none(),
|
||||
});
|
||||
|
||||
assert.isFalse(result);
|
||||
assert.equal(showMessageBoxMock.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens a confirm dialog for the owner window", () =>
|
||||
Effect.gen(function* () {
|
||||
const owner = { id: 1 } as BrowserWindow;
|
||||
showMessageBoxMock.mockResolvedValue({ response: 1 });
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: "Delete worktree?",
|
||||
owner: Option.some(owner),
|
||||
});
|
||||
|
||||
assert.isTrue(result);
|
||||
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
|
||||
owner,
|
||||
{
|
||||
type: "question",
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: "Delete worktree?",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("opens an app-level confirm dialog when there is no owner window", () =>
|
||||
Effect.gen(function* () {
|
||||
showMessageBoxMock.mockResolvedValue({ response: 0 });
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const result = yield* dialog.confirm({
|
||||
message: "Delete worktree?",
|
||||
owner: Option.none(),
|
||||
});
|
||||
|
||||
assert.isFalse(result);
|
||||
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
|
||||
{
|
||||
type: "question",
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: "Delete worktree?",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves folder picker request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("folder picker failed");
|
||||
@@ -117,31 +53,6 @@ describe("ElectronDialog", () => {
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves confirmation request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("confirmation failed");
|
||||
const owner = { id: 9 } as BrowserWindow;
|
||||
showMessageBoxMock.mockRejectedValue(cause);
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
dialog.confirm({
|
||||
owner: Option.some(owner),
|
||||
message: " Confirm removal? ",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
|
||||
assert.strictEqual(error.ownerWindowId, 9);
|
||||
assert.strictEqual(error.promptLength, "Confirm removal?".length);
|
||||
assert.notProperty(error, "promptMessage");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.include(error.message, "window 9");
|
||||
assert.notInclude(error.message, "Confirm removal?");
|
||||
assert.notInclude(error.message, cause.message);
|
||||
}).pipe(Effect.provide(ElectronDialog.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves message box request context and cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("message box failed");
|
||||
|
||||
@@ -6,8 +6,6 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
const CONFIRM_BUTTON_INDEX = 1;
|
||||
|
||||
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
|
||||
"ElectronDialogPickFolderError",
|
||||
{
|
||||
@@ -38,20 +36,6 @@ export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<Electr
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
promptLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
|
||||
"ElectronDialogShowMessageBoxError",
|
||||
{
|
||||
@@ -85,7 +69,6 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogPickFilesError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
]);
|
||||
@@ -103,11 +86,6 @@ export interface ElectronDialogPickFilesInput {
|
||||
readonly filters: readonly Electron.FileFilter[];
|
||||
}
|
||||
|
||||
export interface ElectronDialogConfirmInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export class ElectronDialog extends Context.Service<
|
||||
ElectronDialog,
|
||||
{
|
||||
@@ -117,9 +95,6 @@ export class ElectronDialog extends Context.Service<
|
||||
readonly pickFiles: (
|
||||
input: ElectronDialogPickFilesInput,
|
||||
) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
readonly showMessageBox: (
|
||||
options: Electron.MessageBoxOptions,
|
||||
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
|
||||
@@ -188,39 +163,6 @@ export const make = ElectronDialog.of({
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
}),
|
||||
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
|
||||
const normalizedMessage = input.message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
};
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showMessageBox(options),
|
||||
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogConfirmError({
|
||||
ownerWindowId,
|
||||
promptLength: normalizedMessage.length,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return result.response === CONFIRM_BUTTON_INDEX;
|
||||
}),
|
||||
showMessageBox: (options) =>
|
||||
Effect.tryPromise({
|
||||
try: () => Electron.dialog.showMessageBox(options),
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
setUpdateChannel,
|
||||
} from "./methods/updates.ts";
|
||||
import {
|
||||
confirm,
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
@@ -81,7 +80,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(pickThemeFiles);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
|
||||
export const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
|
||||
@@ -220,19 +220,6 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const confirm = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.CONFIRM_CHANNEL,
|
||||
payload: Schema.String,
|
||||
result: Schema.Boolean,
|
||||
handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
return yield* electronWindow.focusedMainOrFirst.pipe(
|
||||
Effect.flatMap((owner) => dialog.confirm({ owner, message })),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
export const setTheme = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.SET_THEME_CHANNEL,
|
||||
payload: DesktopThemeSchema,
|
||||
|
||||
@@ -98,7 +98,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
|
||||
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
|
||||
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
|
||||
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
|
||||
showContextMenu: (items, position) =>
|
||||
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
|
||||
|
||||
@@ -231,6 +231,7 @@ describe("DesktopShellEnvironment", () => {
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.local\\bin",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
|
||||
@@ -207,7 +207,7 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
|
||||
...trimNonEmpty(env.USERPROFILE).pipe(
|
||||
Option.match({
|
||||
onNone: () => [],
|
||||
onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
|
||||
}),
|
||||
),
|
||||
];
|
||||
@@ -379,10 +379,18 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
|
||||
function* (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
|
||||
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
|
||||
loadProfile: true,
|
||||
});
|
||||
// Concurrent, not sequential: these two probes are independent (only their
|
||||
// results are combined below) and each spawns its own PowerShell. Run in
|
||||
// series they sit at offset 0 of desktop.startup, before anything else, and
|
||||
// launch traces measured them at 2718ms then 2066ms — the entire 4.8s
|
||||
// startup span, of which desktop.bootstrap is ~30ms.
|
||||
const [noProfile, profile] = yield* Effect.all(
|
||||
[
|
||||
readWindowsEnvironment(["PATH"], { loadProfile: false }),
|
||||
readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
const mergedPath = mergePaths("win32", [
|
||||
trimNonEmpty(profile.PATH),
|
||||
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
|
||||
|
||||
@@ -53,7 +53,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
|
||||
pickFolder: () => Effect.succeed(Option.none()),
|
||||
pickFiles: () => Effect.succeed([]),
|
||||
confirm: () => Effect.succeed(false),
|
||||
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
|
||||
showErrorBox: () => Effect.void,
|
||||
} satisfies ElectronDialog.ElectronDialog["Service"]);
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "1.0.2",
|
||||
version: "1.0.3",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
@@ -338,6 +338,7 @@ const config: ExpoConfig = {
|
||||
"./plugins/withAndroidModernPopupMenu.cjs",
|
||||
"./plugins/withAndroidModernAlertDialog.cjs",
|
||||
"./plugins/withAndroidPredictiveBackCompat.cjs",
|
||||
"./plugins/withAndroidTabletOrientation.cjs",
|
||||
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
|
||||
],
|
||||
extra: {
|
||||
|
||||
@@ -49,7 +49,7 @@
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/metro-runtime": "~56.0.15",
|
||||
"@expo/ui": "~56.0.18",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@legendapp/list": "catalog:",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
const { withMainActivity } = require("expo/config-plugins");
|
||||
|
||||
// The top-level `orientation: "portrait"` writes android:screenOrientation="portrait"
|
||||
// into the manifest, which locks every Android device — including tablets — to
|
||||
// portrait. iOS doesn't have this problem: iPads must support all orientations
|
||||
// because the app is multitasking-capable, so only iPhones end up portrait-only.
|
||||
// Mirror that split on Android: keep the manifest lock for phones and lift it at
|
||||
// runtime on tablets (smallest width >= 600dp, the standard tablet breakpoint),
|
||||
// since requestedOrientation set at runtime overrides the manifest value.
|
||||
// FULL_USER allows all four orientations while still respecting the user's
|
||||
// auto-rotate lock, matching iPad behavior. Foldables change
|
||||
// smallestScreenWidthDp on fold/unfold without recreating the activity
|
||||
// (smallestScreenSize is in the manifest's configChanges), so the policy is
|
||||
// re-evaluated in onConfigurationChanged: unfolding past the tablet breakpoint
|
||||
// unlocks rotation, and folding back restores the portrait lock.
|
||||
|
||||
const ORIENTATION_METHODS = `
|
||||
// Applied in onCreate and re-applied on fold/unfold; added by
|
||||
// withAndroidTabletOrientation.
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
applyTabletOrientation()
|
||||
}
|
||||
|
||||
private fun applyTabletOrientation() {
|
||||
requestedOrientation = if (resources.configuration.smallestScreenWidthDp >= 600) {
|
||||
ActivityInfo.SCREEN_ORIENTATION_FULL_USER
|
||||
} else {
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const ORIENTATION_ON_CREATE_CALL = `
|
||||
applyTabletOrientation()`;
|
||||
|
||||
function insertAfter(contents, anchor, insertion, description) {
|
||||
const index = contents.indexOf(anchor);
|
||||
if (index === -1) {
|
||||
throw new Error(
|
||||
`withAndroidTabletOrientation: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`,
|
||||
);
|
||||
}
|
||||
const end = index + anchor.length;
|
||||
return contents.slice(0, end) + insertion + contents.slice(end);
|
||||
}
|
||||
|
||||
module.exports = function withAndroidTabletOrientation(config) {
|
||||
return withMainActivity(config, (nextConfig) => {
|
||||
let contents = nextConfig.modResults.contents;
|
||||
if (nextConfig.modResults.language !== "kt") {
|
||||
throw new Error("withAndroidTabletOrientation: MainActivity must be Kotlin.");
|
||||
}
|
||||
if (contents.includes("SCREEN_ORIENTATION_FULL_USER")) {
|
||||
return nextConfig;
|
||||
}
|
||||
|
||||
contents = insertAfter(
|
||||
contents,
|
||||
"import android.os.Bundle",
|
||||
"\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration",
|
||||
"the android.os.Bundle import",
|
||||
);
|
||||
contents = insertAfter(
|
||||
contents,
|
||||
"class MainActivity : ReactActivity() {",
|
||||
ORIENTATION_METHODS,
|
||||
"the MainActivity class declaration",
|
||||
);
|
||||
contents = insertAfter(
|
||||
contents,
|
||||
"super.onCreate(null)",
|
||||
ORIENTATION_ON_CREATE_CALL,
|
||||
"the super.onCreate call",
|
||||
);
|
||||
|
||||
nextConfig.modResults.contents = contents;
|
||||
return nextConfig;
|
||||
});
|
||||
};
|
||||
+20
-13
@@ -18,7 +18,6 @@ import { AppText as Text } from "./components/AppText";
|
||||
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
|
||||
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
|
||||
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
|
||||
@@ -134,7 +133,7 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
|
||||
presentation: "fullScreenModal",
|
||||
};
|
||||
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
const SettingsContentStack = createNativeStackNavigator({
|
||||
initialRouteName: "Settings",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
@@ -198,20 +197,30 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
title: "Usage",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// The outer stack never owns visible chrome. Settings routes render inside a
|
||||
// nested stack whose native header remains mounted, while Clerk owns auth chrome.
|
||||
// Keeping bar visibility invariant avoids iOS 26's headerless-to-headered jump.
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "SettingsContent",
|
||||
screenOptions: {
|
||||
headerShown: false,
|
||||
},
|
||||
screens: {
|
||||
SettingsContent: createNativeStackScreen({
|
||||
screen: SettingsContentStack,
|
||||
linking: "",
|
||||
}),
|
||||
SettingsAuth: createNativeStackScreen({
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "auth",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
SettingsWaitlist: createNativeStackScreen({
|
||||
// Keep the old deep link working after the Connect GA launch.
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "waitlist",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -347,11 +356,9 @@ function RootStackLayout(props: {
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ThreadOutboxDrainWorker />
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
</HardwareKeyboardCommandProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type ComponentProps,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { Platform, Pressable, useColorScheme, View } from "react-native";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
@@ -21,10 +22,31 @@ export function ControlPill(props: {
|
||||
readonly label?: string;
|
||||
readonly accessibilityLabel?: string;
|
||||
readonly onPress?: () => void;
|
||||
readonly activateOnPressIn?: boolean;
|
||||
readonly variant?: "circle" | "pill" | "primary" | "danger";
|
||||
readonly disabled?: boolean;
|
||||
readonly className?: string;
|
||||
}) {
|
||||
const variant = props.variant ?? "circle";
|
||||
const activatedOnPressInRef = useRef(false);
|
||||
|
||||
const handlePressIn = () => {
|
||||
activatedOnPressInRef.current = true;
|
||||
props.onPress?.();
|
||||
};
|
||||
const handlePressOut = () => {
|
||||
// Pressability invokes onPressOut immediately before onPress on release.
|
||||
// Defer the reset so onPress can identify the same physical gesture.
|
||||
setTimeout(() => {
|
||||
activatedOnPressInRef.current = false;
|
||||
}, 0);
|
||||
};
|
||||
const handlePress = () => {
|
||||
if (activatedOnPressInRef.current) {
|
||||
return;
|
||||
}
|
||||
props.onPress?.();
|
||||
};
|
||||
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
@@ -54,6 +76,7 @@ export function ControlPill(props: {
|
||||
: variant === "danger"
|
||||
? "bg-danger"
|
||||
: "bg-subtle",
|
||||
props.className,
|
||||
);
|
||||
const labelClassName = cn(
|
||||
"text-center text-xs font-t3-bold",
|
||||
@@ -68,7 +91,9 @@ export function ControlPill(props: {
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
onPress={props.activateOnPressIn ? handlePress : props.onPress}
|
||||
onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
|
||||
onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
|
||||
disabled={props.disabled}
|
||||
className={containerClassName}
|
||||
>
|
||||
@@ -133,9 +158,25 @@ export function ControlPillMenu(
|
||||
}
|
||||
|
||||
const { className: _className, ...menuProps } = props;
|
||||
let children = menuProps.children;
|
||||
// In long-press mode the wrapped pressable still receives the touch (the
|
||||
// patched MenuView button is touch-transparent) and RN's Fabric touch
|
||||
// handler is never cancelled by the in-tree UIContextMenuInteraction, so a
|
||||
// bare onPress would fire on finger-up even after the menu opened — and
|
||||
// also on a long press released just under the menu threshold. A dispatched
|
||||
// onLongPress makes Pressability swallow the release, so holds past 350ms
|
||||
// (below the ~500ms context-menu threshold) can only open the menu, never
|
||||
// tap through.
|
||||
if (props.shouldOpenOnLongPress && isValidElement(children)) {
|
||||
const child = children as ReactElement<{ onLongPress?: () => void; delayLongPress?: number }>;
|
||||
children = cloneElement(child, {
|
||||
onLongPress: child.props.onLongPress ?? (() => undefined),
|
||||
delayLongPress: child.props.delayLongPress ?? 350,
|
||||
});
|
||||
}
|
||||
return (
|
||||
<MenuView {...menuProps} themeVariant={isDarkMode ? "dark" : "light"}>
|
||||
{menuProps.children}
|
||||
{children}
|
||||
</MenuView>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import { useFocusEffect } from "@react-navigation/native";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { useArchivedThreadListActions } from "../home/useThreadListActions";
|
||||
import {
|
||||
ArchivedThreadsScreen,
|
||||
@@ -18,7 +17,6 @@ import {
|
||||
} from "./useArchivedThreadSnapshots";
|
||||
|
||||
export function ArchivedThreadsRouteScreen() {
|
||||
const { expand } = useClerkSettingsSheetDetent();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
@@ -70,9 +68,8 @@ export function ArchivedThreadsRouteScreen() {
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
expand();
|
||||
refresh();
|
||||
}, [expand, refresh]),
|
||||
}, [refresh]),
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import {
|
||||
createContext,
|
||||
type PropsWithChildren,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
interface ClerkSettingsSheetDetentValue {
|
||||
collapse: () => void;
|
||||
expand: () => void;
|
||||
isExpanded: boolean;
|
||||
}
|
||||
|
||||
const ClerkSettingsSheetDetentContext = createContext<ClerkSettingsSheetDetentValue | null>(null);
|
||||
|
||||
interface ClerkSettingsSheetDetentProviderProps extends PropsWithChildren {
|
||||
initiallyExpanded: boolean;
|
||||
}
|
||||
|
||||
export function ClerkSettingsSheetDetentProvider({
|
||||
children,
|
||||
initiallyExpanded,
|
||||
}: ClerkSettingsSheetDetentProviderProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(initiallyExpanded);
|
||||
const collapse = useCallback(() => setIsExpanded(false), []);
|
||||
const expand = useCallback(() => setIsExpanded(true), []);
|
||||
const value = useMemo(() => ({ collapse, expand, isExpanded }), [collapse, expand, isExpanded]);
|
||||
|
||||
return (
|
||||
<ClerkSettingsSheetDetentContext value={value}>{children}</ClerkSettingsSheetDetentContext>
|
||||
);
|
||||
}
|
||||
|
||||
export function useClerkSettingsSheetDetent(): ClerkSettingsSheetDetentValue {
|
||||
const value = useContext(ClerkSettingsSheetDetentContext);
|
||||
if (!value) {
|
||||
throw new Error(
|
||||
"useClerkSettingsSheetDetent must be used inside ClerkSettingsSheetDetentProvider",
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
|
||||
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
|
||||
|
||||
// Sign-in happens inside the Settings sheet; give its detent/session-state
|
||||
// transitions a beat to settle before presenting another formSheet on top.
|
||||
// Sign-in happens inside the Settings sheet; give its session-state transition
|
||||
// a beat to settle before presenting another formSheet on top.
|
||||
const PRESENT_ONBOARDING_DELAY_MS = 600;
|
||||
|
||||
/**
|
||||
|
||||
@@ -134,7 +134,10 @@ export function HomeRouteScreen() {
|
||||
<NativeStackScreenOptions
|
||||
options={getConnectionAwareBrandHeaderOptions({
|
||||
onOpenEnvironments: () =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
}),
|
||||
})}
|
||||
/>
|
||||
<HomeHeader
|
||||
@@ -148,9 +151,17 @@ export function HomeRouteScreen() {
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
})
|
||||
}
|
||||
onOpenSettings={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
})
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
@@ -161,7 +172,10 @@ export function HomeRouteScreen() {
|
||||
catalogState={catalogState}
|
||||
environments={environments}
|
||||
onAddConnection={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
})
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
@@ -174,7 +188,12 @@ export function HomeRouteScreen() {
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onOpenSettings={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
})
|
||||
}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
|
||||
@@ -429,13 +429,19 @@ function AdaptiveWorkspaceLayoutContent(
|
||||
);
|
||||
|
||||
const handleOpenSettings = useCallback(() => {
|
||||
navigation.navigate("SettingsSheet", { screen: "Settings" });
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "Settings" },
|
||||
});
|
||||
}, [navigation]);
|
||||
|
||||
// Minted here (root stack navigation) so the sidebar pane stays free of
|
||||
// navigation hooks — on iOS it renders inside an independent nav tree.
|
||||
const handleOpenEnvironmentSettings = useCallback(() => {
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironments" },
|
||||
});
|
||||
}, [navigation]);
|
||||
|
||||
const handleNewThreadInProject = useCallback(
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { AuthView, UserProfileView } from "@clerk/expo/native";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { useCallback, useLayoutEffect } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
@@ -10,9 +9,9 @@ import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
export function SettingsAuthRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
|
||||
useEffect(() => {
|
||||
useLayoutEffect(() => {
|
||||
if (!hasCloudPublicConfig()) {
|
||||
navigation.dispatch(StackActions.replace("Settings"));
|
||||
navigation.dispatch(StackActions.replace("SettingsContent"));
|
||||
}
|
||||
}, [navigation]);
|
||||
|
||||
@@ -22,20 +21,20 @@ export function SettingsAuthRouteScreen() {
|
||||
function ConfiguredSettingsAuthRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const navigation = useNavigation();
|
||||
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
|
||||
const handleHostBack = useCallback(
|
||||
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
|
||||
[navigation],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -98,7 +98,10 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
accessibilityLabel: "Add environment",
|
||||
icon: "plus",
|
||||
onPress: () =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }),
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
}),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
@@ -108,7 +111,10 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsEnvironmentNew" },
|
||||
})
|
||||
}
|
||||
separateBackground
|
||||
tintColor={headerIconColor}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useAuth, useUser } from "@clerk/expo";
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import Constants from "expo-constants";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import * as Updates from "expo-updates";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -30,7 +29,6 @@ import {
|
||||
subscribeAgentAwarenessRegistrationStatus,
|
||||
} from "../agent-awareness/remoteRegistration";
|
||||
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
@@ -40,6 +38,7 @@ import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import {
|
||||
type AppUpdateCheckState,
|
||||
isAppUpdateCheckAvailable,
|
||||
registerHiddenUpdateTap,
|
||||
runAppUpdateCheck,
|
||||
} from "../updates/app-updates";
|
||||
@@ -147,7 +146,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
|
||||
const insets = useSafeAreaInsets();
|
||||
const navigation = useNavigation();
|
||||
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
|
||||
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { user } = useUser();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
@@ -436,14 +434,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
|
||||
const openAccount = useCallback(() => {
|
||||
if (!isLoaded) return;
|
||||
if (!isSignedIn) {
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
return;
|
||||
}
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
}, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
|
||||
}, [isLoaded, navigation]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -577,6 +569,7 @@ function AppSettingsSection() {
|
||||
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
|
||||
const variantLabel = variant === "production" ? "" : capitalize(variant);
|
||||
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
|
||||
const updateCheckAvailable = isAppUpdateCheckAvailable();
|
||||
const busy =
|
||||
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
|
||||
|
||||
@@ -604,13 +597,13 @@ function AppSettingsSection() {
|
||||
}, []);
|
||||
|
||||
const handleVersionPress = useCallback(() => {
|
||||
if (!Updates.isEnabled || updateInFlight.current) return;
|
||||
if (!updateCheckAvailable || updateInFlight.current) return;
|
||||
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
|
||||
hiddenUpdateTapCount.current = tap.nextCount;
|
||||
if (tap.shouldCheck) {
|
||||
void checkForUpdate();
|
||||
}
|
||||
}, [checkForUpdate]);
|
||||
}, [checkForUpdate, updateCheckAvailable]);
|
||||
|
||||
const statusLabel =
|
||||
updateState === "checking"
|
||||
@@ -646,7 +639,7 @@ function AppSettingsSection() {
|
||||
<SettingsSection title="App">
|
||||
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
{Updates.isEnabled ? (
|
||||
{updateCheckAvailable ? (
|
||||
<Pressable
|
||||
accessibilityLabel={`Version ${versionLabel}`}
|
||||
accessibilityRole="text"
|
||||
|
||||
@@ -64,7 +64,8 @@ export function SettingsRow(props: {
|
||||
disabled={props.disabled}
|
||||
onPress={() =>
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: target,
|
||||
screen: "SettingsContent",
|
||||
params: { screen: target },
|
||||
})
|
||||
}
|
||||
>
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Keyboard, View } from "react-native";
|
||||
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
|
||||
import {
|
||||
CommonActions,
|
||||
type NavigationState,
|
||||
type PartialState,
|
||||
StackActions,
|
||||
useNavigation,
|
||||
} from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { useConnectionController } from "../connection/useConnectionController";
|
||||
@@ -25,6 +31,8 @@ import { retryShowcaseOperation } from "./showcaseRetry";
|
||||
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
|
||||
const SHOWCASE_THREAD_ID = "remote-command-center";
|
||||
|
||||
type ShowcaseResetRoute = PartialState<NavigationState>["routes"][number];
|
||||
|
||||
function sceneFromPathname(pathname: string): ShowcaseScene | null {
|
||||
const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname;
|
||||
if (routePath === "/settings" || routePath.endsWith("/settings/environments")) {
|
||||
@@ -166,17 +174,21 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
|
||||
navigation.dispatch(StackActions.popToTop());
|
||||
return;
|
||||
}
|
||||
const routes: Array<{
|
||||
name: string;
|
||||
params?: Record<string, unknown>;
|
||||
state?: { index: number; routes: Array<{ name: string }> };
|
||||
}> = [{ name: "Home" }];
|
||||
const routes: ShowcaseResetRoute[] = [{ name: "Home" }];
|
||||
if (requestedScene === "environments") {
|
||||
routes.push({
|
||||
name: "SettingsSheet",
|
||||
state: {
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: "SettingsContent",
|
||||
state: {
|
||||
index: 1,
|
||||
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -2,7 +2,11 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
|
||||
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
|
||||
import {
|
||||
KeyboardAvoidingView,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
@@ -985,14 +989,29 @@ export function NewTaskDraftScreen(props: {
|
||||
// The draft is a thread that doesn't exist yet, so it mirrors the thread
|
||||
// page: in-screen header, empty feed canvas above, and the same floating
|
||||
// composer chrome as ThreadComposer (collapsed pill → expanded card).
|
||||
//
|
||||
// Composer positioning mirrors ThreadDetailScreen's floating overlay
|
||||
// (KeyboardStickyView, absolute bottom overlay) rather than
|
||||
// KeyboardAvoidingView's automaticOffset+padding: automaticOffset
|
||||
// resolves the composer's on-screen frame via a native
|
||||
// viewPositionInWindow measurement, which this app's Android
|
||||
// edge-to-edge setup (KeyboardProvider's native content-view margin
|
||||
// handling neutralizes windowSoftInputMode="adjustResize" while active)
|
||||
// makes unreliable — the composer stayed under the keyboard instead of
|
||||
// translating above it. KeyboardStickyView sticks directly to the
|
||||
// animated keyboard height instead, sidestepping that measurement.
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
|
||||
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
|
||||
<View className="flex-1" />
|
||||
<View className="flex-1" />
|
||||
|
||||
<KeyboardStickyView
|
||||
enabled={isKeyboardVisible}
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View
|
||||
className="px-4 pt-2"
|
||||
style={{
|
||||
@@ -1056,7 +1075,7 @@ export function NewTaskDraftScreen(props: {
|
||||
</ComposerToolbarRow>
|
||||
) : null}
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
</KeyboardStickyView>
|
||||
{settingsSheet}
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -1,18 +1,64 @@
|
||||
import type { ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
|
||||
import Animated, {
|
||||
Easing,
|
||||
FadeInUp,
|
||||
FadeOutDown,
|
||||
LinearTransition,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
|
||||
import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
isPendingUserInputOptionSelected,
|
||||
type PendingUserInput,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingUserInputCardProps {
|
||||
readonly pendingUserInput: PendingUserInput;
|
||||
/**
|
||||
* Constant while a request is pending (it reserves keyboard space), so the
|
||||
* keyboard transition is pure translation; changes only on rare discrete
|
||||
* corrections, which the layout transition smooths.
|
||||
*/
|
||||
readonly maxHeight: number;
|
||||
readonly collapsed: boolean;
|
||||
readonly onToggleCollapsed: () => void;
|
||||
/** Renders a stop control on the collapsed bar, which replaces the composer. */
|
||||
readonly onStopThread?: () => void;
|
||||
/**
|
||||
* 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the
|
||||
* collapsed bar (inside a clipping window) on the UI thread; the host
|
||||
* animates it directly from the tap handler so the card and the feed
|
||||
* inset glide start the same frame.
|
||||
*/
|
||||
readonly cardProgress?: SharedValue<number>;
|
||||
/**
|
||||
* Receives how far the expanded card extends above the bar footprint
|
||||
* (written from onLayout with no re-render); the host adds it to the
|
||||
* thread feed's end inset so the end of the chat stays visible above the
|
||||
* card.
|
||||
*/
|
||||
readonly cardCoverage?: SharedValue<number>;
|
||||
/** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */
|
||||
readonly onInputFocusChange?: (focused: boolean) => void;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string> | null;
|
||||
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
question: UserInputQuestion,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
@@ -23,74 +69,242 @@ export interface PendingUserInputCardProps {
|
||||
readonly onSubmit: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
|
||||
* card is an absolutely-positioned overlay rising above it. The overlay's
|
||||
* measured height (which drives the thread feed's bottom inset) therefore
|
||||
* never changes on collapse/expand, so the transcript stays perfectly still
|
||||
* while the card animates over it.
|
||||
*
|
||||
* Android cannot use the overlay: it does not hit-test touches outside a
|
||||
* parent's bounds, which made everything above the bar-sized wrapper
|
||||
* untouchable. There the expanded card renders in-flow instead (the wrapper
|
||||
* grows with it, and the host skips the coverage inset since the measured
|
||||
* overlay already includes the card).
|
||||
*/
|
||||
const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
|
||||
|
||||
const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
// The surface is opaque on purpose: the card floats over the thread feed
|
||||
// with no blur behind it, so a translucent background renders the questions
|
||||
// on top of whatever message happens to sit underneath.
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
Fill in the pending answers
|
||||
</Text>
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
<View key={question.id} className="gap-2 pt-1">
|
||||
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
|
||||
{question.header}
|
||||
</Text>
|
||||
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
|
||||
{question.question}
|
||||
</Text>
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
{question.options.map((option) => {
|
||||
const selected =
|
||||
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
|
||||
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
|
||||
)}
|
||||
onPress={() =>
|
||||
props.onSelectOption(
|
||||
props.pendingUserInput.requestId,
|
||||
question.id,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Text
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
const questionCount = props.pendingUserInput.questions.length;
|
||||
|
||||
const cardCoverage = props.cardCoverage;
|
||||
const barHeightRef = useRef(0);
|
||||
const cardHeightRef = useRef(0);
|
||||
// Measured card height, written straight from onLayout: the collapse slide
|
||||
// distance. Not animated — it only changes on discrete relayouts.
|
||||
const cardHeight = useSharedValue(0);
|
||||
const notifyCoverage = useCallback(() => {
|
||||
if (!cardCoverage) {
|
||||
return;
|
||||
}
|
||||
const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
|
||||
if (coverage === cardCoverage.value) {
|
||||
return;
|
||||
}
|
||||
if (cardCoverage.value === 0) {
|
||||
// First measurement lands while the list is doing its initial
|
||||
// end-pin (thread opened onto a pending request); animating it from
|
||||
// zero would move the end anchor out from under that scroll.
|
||||
cardCoverage.value = coverage;
|
||||
return;
|
||||
}
|
||||
// Animated so a coverage change at rest (discrete max-height
|
||||
// corrections) glides the feed instead of stepping it; toggle timing is
|
||||
// owned by the host's progress values.
|
||||
cardCoverage.value = withTiming(coverage, {
|
||||
duration: USER_INPUT_TOGGLE_DURATION_MS,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
});
|
||||
}, [cardCoverage]);
|
||||
const handleBarLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
barHeightRef.current = event.nativeEvent.layout.height;
|
||||
notifyCoverage();
|
||||
},
|
||||
[notifyCoverage],
|
||||
);
|
||||
const handleCardLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
cardHeightRef.current = event.nativeEvent.layout.height;
|
||||
cardHeight.value = event.nativeEvent.layout.height;
|
||||
notifyCoverage();
|
||||
},
|
||||
[cardHeight, notifyCoverage],
|
||||
);
|
||||
const cardProgress = props.cardProgress;
|
||||
// No opacity: fading an opaque card over the live transcript reads as a
|
||||
// crossfade (card text, transcript, and bar all half-visible at once).
|
||||
// Instead the card stays opaque and slides its full height down past the
|
||||
// clipping window's bottom edge, so the transcript is only revealed where
|
||||
// the card has physically left.
|
||||
const cardAnimatedStyle = useAnimatedStyle(() => {
|
||||
const progress = cardProgress === undefined ? 1 : cardProgress.value;
|
||||
return {
|
||||
transform: [{ translateY: (1 - progress) * cardHeight.value }],
|
||||
};
|
||||
});
|
||||
|
||||
// On iOS the card stays MOUNTED while collapsed (hidden via the animated
|
||||
// style): expanding animates existing views on the UI thread the same
|
||||
// frame the host starts the progress timing, instead of paying a React
|
||||
// mount + layout before anything moves.
|
||||
const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
|
||||
const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
|
||||
// The bar renders UNDER the card (earlier in JSX), always opaque: while
|
||||
// expanded the opaque card covers it, and during the collapse slide the
|
||||
// card's top edge wipes past and reveals it — no opacity handoff, so no
|
||||
// crossfade frames.
|
||||
const bar = showBar ? (
|
||||
<View
|
||||
onLayout={handleBarLayout}
|
||||
pointerEvents={props.collapsed ? "auto" : "none"}
|
||||
accessibilityElementsHidden={!props.collapsed}
|
||||
importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
|
||||
className="flex-row items-center gap-2 rounded-full border border-neutral-200 bg-neutral-100 py-1.5 pl-4 pr-1.5 dark:border-white/6 dark:bg-neutral-900"
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Expand user input, ${questionCount} question${
|
||||
questionCount === 1 ? "" : "s"
|
||||
}`}
|
||||
onPress={props.onToggleCollapsed}
|
||||
className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
|
||||
>
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
<Text className="font-sans text-xs text-neutral-500 dark:text-neutral-400">
|
||||
{questionCount} question{questionCount === 1 ? "" : "s"}
|
||||
</Text>
|
||||
<View className="flex-1" />
|
||||
<SymbolView name="chevron.up" size={12} tintColor={iconSubtle} type="monochrome" />
|
||||
</Pressable>
|
||||
{props.onStopThread ? (
|
||||
<ControlPill
|
||||
accessibilityLabel="Stop"
|
||||
icon="stop.fill"
|
||||
variant="danger"
|
||||
className="h-9 w-9"
|
||||
onPress={props.onStopThread}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
) : null;
|
||||
const card = renderCard ? (
|
||||
// The surface is opaque on purpose: the card floats over the thread
|
||||
// feed with no blur behind it, so a translucent background renders
|
||||
// the questions on top of whatever message happens to sit underneath.
|
||||
<Animated.View
|
||||
onLayout={handleCardLayout}
|
||||
pointerEvents={props.collapsed ? "none" : "auto"}
|
||||
accessibilityElementsHidden={props.collapsed}
|
||||
importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
|
||||
entering={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? undefined
|
||||
: FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
|
||||
}
|
||||
exiting={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? undefined
|
||||
: FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
|
||||
}
|
||||
layout={CARD_LAYOUT_TRANSITION}
|
||||
className="overflow-hidden gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900"
|
||||
style={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
|
||||
: { maxHeight: props.maxHeight }
|
||||
}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Collapse user input"
|
||||
onPress={props.onToggleCollapsed}
|
||||
className="flex-row items-start gap-2"
|
||||
>
|
||||
<View className="flex-1 gap-2.5">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
Fill in the pending answers
|
||||
</Text>
|
||||
</View>
|
||||
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/8">
|
||||
<SymbolView name="chevron.down" size={13} tintColor={iconSubtle} type="monochrome" />
|
||||
</View>
|
||||
</Pressable>
|
||||
<ScrollView
|
||||
bounces={false}
|
||||
className="min-h-0"
|
||||
contentContainerClassName="gap-2.5 pb-1"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
nestedScrollEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ flexShrink: 1 }}
|
||||
>
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
<View key={question.id} className="gap-2 pt-1">
|
||||
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
|
||||
{question.header}
|
||||
</Text>
|
||||
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
|
||||
{question.question}
|
||||
</Text>
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
{question.options.map((option) => {
|
||||
const selected = isPendingUserInputOptionSelected(draft, option.label);
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
className={cn(
|
||||
"font-t3-bold text-sm",
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
? "text-sky-700 dark:text-sky-300"
|
||||
: "text-neutral-600 dark:text-neutral-300",
|
||||
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
|
||||
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
|
||||
)}
|
||||
onPress={() =>
|
||||
props.onSelectOption(
|
||||
props.pendingUserInput.requestId,
|
||||
question,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-bold text-sm",
|
||||
selected
|
||||
? "text-sky-700 dark:text-sky-300"
|
||||
: "text-neutral-600 dark:text-neutral-300",
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
}
|
||||
onFocus={() => props.onInputFocusChange?.(true)}
|
||||
onBlur={() => props.onInputFocusChange?.(false)}
|
||||
placeholder="Or type a custom answer"
|
||||
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
|
||||
/>
|
||||
</View>
|
||||
<TextInput
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
}
|
||||
placeholder="Or type a custom answer"
|
||||
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
<Pressable
|
||||
className={cn(
|
||||
"items-center justify-center rounded-2xl px-4 py-3.5",
|
||||
@@ -103,6 +317,26 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
|
||||
</Pressable>
|
||||
</Animated.View>
|
||||
) : null;
|
||||
return (
|
||||
<View className="relative">
|
||||
{bar}
|
||||
{EXPANDED_CARD_IS_OVERLAY ? (
|
||||
// Clipping window for the collapse slide: same footprint as the
|
||||
// expanded card, bottom edge on the bar's bottom edge. The sliding
|
||||
// card exits through the bottom edge instead of drawing over the
|
||||
// composer area, wiping the bar (and the transcript) into view.
|
||||
<View
|
||||
pointerEvents={props.collapsed ? "none" : "box-none"}
|
||||
className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
|
||||
style={{ height: props.maxHeight }}
|
||||
>
|
||||
{card}
|
||||
</View>
|
||||
) : (
|
||||
card
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
serializeComposerFileLink,
|
||||
type ComposerTrigger,
|
||||
} from "@t3tools/shared/composerTrigger";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import type { ReactNode } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
@@ -51,7 +52,7 @@ import {
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
@@ -62,9 +63,13 @@ import {
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import {
|
||||
applyProviderOptionSelection,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
import { buildThreadSettingsMenu } from "./thread-settings-menu";
|
||||
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
|
||||
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
@@ -113,6 +118,8 @@ export interface ThreadComposerProps {
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onExpandedChange?: (expanded: boolean) => void;
|
||||
/** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
|
||||
readonly onEditorFocusChange?: (focused: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -307,13 +314,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}
|
||||
}, [inputRef]);
|
||||
|
||||
const onEditorFocusChange = props.onEditorFocusChange;
|
||||
const handleFocus = useCallback(() => {
|
||||
setIsFocused(true);
|
||||
}, []);
|
||||
onEditorFocusChange?.(true);
|
||||
}, [onEditorFocusChange]);
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setIsFocused(false);
|
||||
}, []);
|
||||
onEditorFocusChange?.(false);
|
||||
}, [onEditorFocusChange]);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
@@ -623,6 +633,61 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
interactionMode: currentInteractionMode,
|
||||
});
|
||||
|
||||
// iOS gets a native menu on the trigger pill: the everyday adjustments
|
||||
// apply without resigning the keyboard, while "All Settings…" (and the
|
||||
// Android trigger) still route through the sheet, which must dismiss it.
|
||||
const settingsMenu = useMemo(
|
||||
() =>
|
||||
Platform.OS === "ios"
|
||||
? buildThreadSettingsMenu({
|
||||
providerGroups: threadProviderGroups,
|
||||
selectedModel: currentModelSelection,
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: currentRuntimeMode,
|
||||
})
|
||||
: null,
|
||||
[threadProviderGroups, currentModelSelection, providerOptionDescriptors, currentRuntimeMode],
|
||||
);
|
||||
|
||||
const onUpdateModelSelection = props.onUpdateModelSelection;
|
||||
const onUpdateRuntimeMode = props.onUpdateRuntimeMode;
|
||||
const handleSettingsMenuAction = useCallback(
|
||||
(eventId: string) => {
|
||||
const event = settingsMenu?.events.get(eventId);
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
switch (event.type) {
|
||||
case "select-model":
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateModelSelection(event.option.selection);
|
||||
return;
|
||||
case "set-option": {
|
||||
const options = applyProviderOptionSelection(providerOptionDescriptors, {
|
||||
id: event.optionId,
|
||||
value: event.value,
|
||||
});
|
||||
if (options) {
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateModelSelection({ ...currentModelSelection, options });
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "set-runtime":
|
||||
void Haptics.selectionAsync();
|
||||
onUpdateRuntimeMode(event.mode);
|
||||
return;
|
||||
}
|
||||
},
|
||||
[
|
||||
currentModelSelection,
|
||||
onUpdateModelSelection,
|
||||
onUpdateRuntimeMode,
|
||||
providerOptionDescriptors,
|
||||
settingsMenu,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
className="px-4"
|
||||
@@ -792,15 +857,31 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
{settingsMenu ? (
|
||||
<ControlPillMenu
|
||||
actions={settingsMenu.actions}
|
||||
onPressAction={({ nativeEvent }) => handleSettingsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
) : (
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
)}
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Stop"
|
||||
|
||||
@@ -2,6 +2,7 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect
|
||||
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
@@ -13,14 +14,45 @@ import type {
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Platform, View, type GestureResponderEvent } from "react-native";
|
||||
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import {
|
||||
AppState,
|
||||
Keyboard,
|
||||
Platform,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
type GestureResponderEvent,
|
||||
} from "react-native";
|
||||
import {
|
||||
KeyboardController,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
import Animated, {
|
||||
Easing,
|
||||
FadeInDown,
|
||||
FadeOut,
|
||||
useAnimatedReaction,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
@@ -34,6 +66,11 @@ import type {
|
||||
} from "../../lib/threadActivity";
|
||||
import { PendingApprovalCard } from "./PendingApprovalCard";
|
||||
import { PendingUserInputCard } from "./PendingUserInputCard";
|
||||
import {
|
||||
derivePendingUserInputMaxHeight,
|
||||
ESTIMATED_KEYBOARD_HEIGHT,
|
||||
USER_INPUT_TOGGLE_DURATION_MS,
|
||||
} from "./pendingUserInputLayout";
|
||||
import {
|
||||
COMPOSER_COLLAPSED_CHROME,
|
||||
COMPOSER_EXPANDED_CHROME,
|
||||
@@ -54,7 +91,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
@@ -89,7 +126,7 @@ export interface ThreadDetailScreenProps {
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
question: UserInputQuestion,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
@@ -171,8 +208,48 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
|
||||
}, [threadId, feed]);
|
||||
}
|
||||
|
||||
const USER_INPUT_TOGGLE_TIMING = {
|
||||
duration: USER_INPUT_TOGGLE_DURATION_MS,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
};
|
||||
|
||||
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const liveKeyboardHeight = useKeyboardState((state) => state.height);
|
||||
// Android can swallow the IME hide callbacks when the app is backgrounded
|
||||
// mid keyboard-hide (the reported repro: send — which blurs and starts the
|
||||
// hide — then Home within a second). The keyboard library's height AND
|
||||
// visibility then stay frozen open, so gating the sticky translation on
|
||||
// visibility alone still strands the composer after resume. Quarantine the
|
||||
// translation on every Android resume instead; any sign of a live keyboard
|
||||
// stream — an owned input gaining focus, or any visibility/height movement —
|
||||
// lifts it. A healthy resume sees no visual difference (the translation is
|
||||
// already zero while the keyboard is closed).
|
||||
const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
|
||||
useEffect(() => {
|
||||
if (Platform.OS !== "android") {
|
||||
return;
|
||||
}
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
setKeyboardStateSuspect(true);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
subscription.remove();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
setKeyboardStateSuspect(false);
|
||||
}, [isKeyboardVisible, liveKeyboardHeight]);
|
||||
const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
|
||||
if (focused) {
|
||||
setKeyboardStateSuspect(false);
|
||||
}
|
||||
}, []);
|
||||
const windowHeight = useWindowDimensions().height;
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
@@ -183,7 +260,17 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
|
||||
// Android keys the safe-area padding on keyboard visibility (#5988): the
|
||||
// back gesture closes the keyboard while the editor stays focused, and a
|
||||
// focus-keyed inset would leave the toolbar under the gesture bar. iOS must
|
||||
// NOT use visibility — it only flips on keyboardDidHide, after the hide
|
||||
// animation, so the composer would ride down flush to the screen edge and
|
||||
// then snap up into the inset. On iOS blur precedes the hide, so the
|
||||
// focus-keyed inset is already in place while the composer rides down.
|
||||
const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded)
|
||||
? 0
|
||||
: Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
// The raw sync status enters "synchronizing" on every full fetch, cached or
|
||||
// not. Whether messages are already on screen decides the pill label: no
|
||||
@@ -204,6 +291,41 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
// While a user-input request is pending, the questionnaire owns the
|
||||
// composer slot outright: expanded it is the full card, collapsed it is a
|
||||
// composer-style bar in the same place (with its own stop control). The
|
||||
// composer never mounts into the transition, which keeps the collapse and
|
||||
// keyboard animations coherent. Collapse state is keyed by request id so a
|
||||
// new request re-expands automatically.
|
||||
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
|
||||
useState<ApprovalRequestId | null>(null);
|
||||
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
|
||||
const userInputCollapsed =
|
||||
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
|
||||
// The card's height RESERVES keyboard space at all times instead of
|
||||
// tracking the keyboard: transforms (the sticky translation) apply
|
||||
// same-frame on the UI thread while layout props lag a Yoga pass behind,
|
||||
// so any height that follows the keyboard flashes the card over the nav
|
||||
// header on the way up. With a constant height the keyboard transition is
|
||||
// pure translation — frame-perfect by construction — and the resting card
|
||||
// stays compact over the transcript. Before the first open the reserve is
|
||||
// an estimate; once a real height is known the card corrects once,
|
||||
// discretely.
|
||||
const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
|
||||
useEffect(() => {
|
||||
if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
|
||||
setLastKnownKeyboardHeight(liveKeyboardHeight);
|
||||
}
|
||||
}, [lastKnownKeyboardHeight, liveKeyboardHeight]);
|
||||
const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
|
||||
windowHeight,
|
||||
keyboardHeight:
|
||||
lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
|
||||
navigationHeaderHeight,
|
||||
// The questionnaire owns the composer slot, so only the composer's
|
||||
// bottom inset still overlaps.
|
||||
composerOverlapHeight: composerBottomInset,
|
||||
});
|
||||
const estimatedOverlayHeight = composerOverlapHeight;
|
||||
// The overlay's measured height includes the home-indicator inset (the
|
||||
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
|
||||
@@ -220,7 +342,103 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
|
||||
-nativeInsetOvercount,
|
||||
);
|
||||
// The expanded questionnaire is an absolute overlay on iOS, so it never
|
||||
// changes the measured overlay height (that constancy is what keeps the
|
||||
// feed from snapping on collapse/expand). The toggle choreography runs on
|
||||
// SHARED VALUES set directly in the tap handler — one JS hop, then the
|
||||
// card's rise/sink and the feed's end-inset glide animate in lockstep on
|
||||
// the UI thread, keyboard-style, instead of waiting on React mount +
|
||||
// onLayout + state round trips. Coverage (how far the card extends above
|
||||
// the bar) is measured straight into a shared value by the card's
|
||||
// onLayout, with no re-render.
|
||||
const userInputCardProgress = useSharedValue(1);
|
||||
const userInputInsetProgress = useSharedValue(1);
|
||||
const userInputCardCoverage = useSharedValue(0);
|
||||
// Android renders the expanded card in-flow (it cannot hit-test the iOS
|
||||
// overlay outside the bar's bounds), so its measured overlay height already
|
||||
// includes the card — the coverage extra is iOS-only.
|
||||
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
|
||||
const combinedContentInsetEndAdjustment = useSharedValue(
|
||||
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
|
||||
);
|
||||
useAnimatedReaction(
|
||||
() =>
|
||||
contentInsetEndAdjustment.value +
|
||||
(userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
|
||||
(value) => {
|
||||
combinedContentInsetEndAdjustment.value = value;
|
||||
},
|
||||
[userInputCoverageApplies],
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const endFollowEnabledRef = useRef(true);
|
||||
endFollowEnabledRef.current = endFollowEnabled;
|
||||
const userInputRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// The list's own corrections for these inset changes drift on short
|
||||
// content (and the error compounds across toggles), so deterministically
|
||||
// re-pin the end once a toggle settles: a no-op when the resting position
|
||||
// is already right, corrective when it is not. Follow state is re-checked
|
||||
// inside the callback — the user may grab the list during the settle
|
||||
// window, and yanking them back would override a live gesture.
|
||||
const scheduleUserInputRepin = useCallback(
|
||||
(delayMs: number) => {
|
||||
if (userInputRepinTimerRef.current !== null) {
|
||||
clearTimeout(userInputRepinTimerRef.current);
|
||||
}
|
||||
userInputRepinTimerRef.current = setTimeout(() => {
|
||||
userInputRepinTimerRef.current = null;
|
||||
if (!endFollowEnabledRef.current) {
|
||||
return;
|
||||
}
|
||||
void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
|
||||
freeze.set(false);
|
||||
});
|
||||
}, delayMs);
|
||||
},
|
||||
[freeze, scrollMessageToEnd],
|
||||
);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (userInputRepinTimerRef.current !== null) {
|
||||
clearTimeout(userInputRepinTimerRef.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleToggleUserInputCollapsed = useCallback(() => {
|
||||
if (activeUserInputRequestId === null) {
|
||||
return;
|
||||
}
|
||||
if (userInputCollapsed) {
|
||||
// Expanding: card and feed glide start NOW, on the UI thread.
|
||||
userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
|
||||
userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
|
||||
setCollapsedUserInputRequestId(null);
|
||||
scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
|
||||
} else {
|
||||
// Collapsing hides the custom-answer inputs; release the keyboard with
|
||||
// them instead of leaving it up over a dead responder.
|
||||
Keyboard.dismiss();
|
||||
userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
|
||||
// Instant: the sinking card still covers the strip being revealed, and
|
||||
// animating the inset downward is what drifted the short-content end
|
||||
// anchor.
|
||||
userInputInsetProgress.value = 0;
|
||||
setCollapsedUserInputRequestId(activeUserInputRequestId);
|
||||
scheduleUserInputRepin(60);
|
||||
}
|
||||
}, [
|
||||
activeUserInputRequestId,
|
||||
scheduleUserInputRepin,
|
||||
userInputCardProgress,
|
||||
userInputCollapsed,
|
||||
userInputInsetProgress,
|
||||
]);
|
||||
useEffect(() => {
|
||||
// A new request always arrives expanded.
|
||||
userInputCardProgress.value = 1;
|
||||
userInputInsetProgress.value = 1;
|
||||
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
|
||||
const showContent = props.showContent ?? true;
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
@@ -241,6 +459,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
setEndFollowEnabled(true);
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
@@ -312,6 +531,16 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
composerEditorRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleScrollToEnd = useCallback(() => {
|
||||
void Haptics.selectionAsync();
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
freeze.set(false);
|
||||
});
|
||||
}, [freeze, scrollMessageToEnd]);
|
||||
|
||||
const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
feedTouchStartRef.current = {
|
||||
pageX: event.nativeEvent.pageX,
|
||||
@@ -365,13 +594,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
onEndFollowEnabledChange={setEndFollowEnabled}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
@@ -383,6 +613,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
|
||||
{showContent ? (
|
||||
<KeyboardStickyView
|
||||
// The animated keyboard height can remain stale after a dismissed
|
||||
// IME on both platforms. Visibility is the authoritative closed
|
||||
// state, so disable the translation rather than stranding the pill.
|
||||
enabled={isKeyboardVisible && !keyboardStateSuspect}
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
@@ -390,10 +624,60 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
list's bottom inset, so any padding above the pill/composer
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
{showScrollToEndButton ? (
|
||||
<Animated.View
|
||||
pointerEvents="box-none"
|
||||
className="absolute -top-11 left-0 right-0 z-20 items-center"
|
||||
entering={FadeInDown.duration(160)}
|
||||
exiting={FadeOut.duration(100)}
|
||||
>
|
||||
{isLiquidGlassSupported ? (
|
||||
<LiquidGlassView
|
||||
colorScheme={isDarkMode ? "dark" : "light"}
|
||||
effect="regular"
|
||||
interactive
|
||||
// Interactive glass can render larger than the requested
|
||||
// box (minimum touch size), so center the pill instead of
|
||||
// relying on it filling the glass exactly.
|
||||
style={{
|
||||
alignItems: "center",
|
||||
borderRadius: 18,
|
||||
height: 36,
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
width: 36,
|
||||
}}
|
||||
>
|
||||
<ControlPill
|
||||
accessibilityLabel="Scroll to end"
|
||||
activateOnPressIn
|
||||
className="h-9 w-9 bg-transparent"
|
||||
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
|
||||
onPress={handleScrollToEnd}
|
||||
/>
|
||||
</LiquidGlassView>
|
||||
) : (
|
||||
<ControlPill
|
||||
accessibilityLabel="Scroll to end"
|
||||
activateOnPressIn
|
||||
className="h-9 w-9 border border-border bg-card shadow-md shadow-black/10"
|
||||
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
|
||||
onPress={handleScrollToEnd}
|
||||
/>
|
||||
)}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
// The questionnaire replaces the composer, so it must pad
|
||||
// the home indicator the composer normally covers.
|
||||
style={
|
||||
activeUserInputRequestId !== null
|
||||
? { paddingBottom: composerBottomInset }
|
||||
: undefined
|
||||
}
|
||||
entering={FadeInDown.duration(220)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
>
|
||||
@@ -407,6 +691,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
{props.activePendingUserInput ? (
|
||||
<PendingUserInputCard
|
||||
pendingUserInput={props.activePendingUserInput}
|
||||
maxHeight={pendingUserInputMaxHeight}
|
||||
collapsed={userInputCollapsed}
|
||||
onToggleCollapsed={handleToggleUserInputCollapsed}
|
||||
onStopThread={props.onStopThread}
|
||||
cardProgress={userInputCardProgress}
|
||||
cardCoverage={userInputCardCoverage}
|
||||
onInputFocusChange={handleOwnedInputFocusChange}
|
||||
drafts={props.activePendingUserInputDrafts}
|
||||
answers={props.activePendingUserInputAnswers}
|
||||
respondingUserInputId={props.respondingUserInputId}
|
||||
@@ -419,35 +710,40 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
/>
|
||||
{/* Hidden (not unmounted) while a user-input request owns the
|
||||
composer slot, so composer drafts and editor state survive. */}
|
||||
<View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
onEditorFocusChange={handleOwnedInputFocusChange}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
|
||||
@@ -48,7 +48,9 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
SelectableMarkdownText,
|
||||
@@ -88,6 +90,10 @@ import {
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
resolveThreadFeedLiveFollow,
|
||||
type ThreadFeedLiveFollowEvent,
|
||||
} from "./thread-feed-live-follow";
|
||||
import {
|
||||
collapsedWorkLogHeight,
|
||||
ThreadWorkGroupToggle,
|
||||
@@ -148,6 +154,7 @@ export interface ThreadFeedProps {
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: {
|
||||
@@ -876,6 +883,12 @@ function renderFeedEntry(
|
||||
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
|
||||
const attachments = message.attachments ?? [];
|
||||
const hasReviewCommentContext = message.text.includes("<review_comment");
|
||||
// A bubble that sizes itself from its content cannot lay out a block whose
|
||||
// intrinsic width overflows `maxWidth`: Android positions the bubble's
|
||||
// children during the unclamped pass and never moves them once the width
|
||||
// is clamped, so the paragraphs around the block end up drawn on top of
|
||||
// each other. Pinning the width removes that pass.
|
||||
const hasWideBlock = hasWideMarkdownBlock(message.text);
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
@@ -898,7 +911,11 @@ function renderFeedEntry(
|
||||
style={{
|
||||
backgroundColor: userBubbleColor,
|
||||
maxWidth: props.userBubbleMaxWidth,
|
||||
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
|
||||
...(hasReviewCommentContext
|
||||
? { width: props.reviewCommentBubbleWidth }
|
||||
: hasWideBlock
|
||||
? { width: props.userBubbleMaxWidth }
|
||||
: null),
|
||||
}}
|
||||
>
|
||||
{message.text.trim().length > 0 ? (
|
||||
@@ -1313,6 +1330,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const headerMaterialVisibleRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const { appearance } = useAppearancePreferences();
|
||||
const [viewportWidth, setViewportWidth] = useState(() =>
|
||||
@@ -1331,13 +1349,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// momentum; only motion inside a session can break follow, so MVCP
|
||||
// compensations and programmatic scrolls never strand a follower.
|
||||
const userScrollSessionRef = useRef(false);
|
||||
const setEndFollow = useCallback((enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
}, []);
|
||||
const setEndFollow = useCallback(
|
||||
(enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
props.onEndFollowEnabledChange?.(enabled);
|
||||
},
|
||||
[props.onEndFollowEnabledChange],
|
||||
);
|
||||
const transitionEndFollow = useCallback(
|
||||
(event: ThreadFeedLiveFollowEvent) => {
|
||||
setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
|
||||
},
|
||||
[setEndFollow],
|
||||
);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1449,40 +1477,72 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
|
||||
// header height back or the material toggles a full header too late.
|
||||
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
|
||||
// Latch bookkeeping. LegendList recomputes its inset-aware end distance
|
||||
// before invoking this handler, so getState() is current. Returning to
|
||||
// the end re-arms follow no matter who scrolled (the user, or our own
|
||||
// scroll-to-end); moving away breaks it only during a user-initiated
|
||||
// scroll session, so MVCP compensations and programmatic repositioning
|
||||
// can never strand a follower.
|
||||
// LegendList recomputes its inset-aware end distance before invoking
|
||||
// this handler, so getState() is current. Only the actual end re-arms
|
||||
// follow: its broader maintain-scroll threshold is large enough for a
|
||||
// streaming chunk to pull a user back before their upward drag escapes.
|
||||
// A live user-scroll session still wins even if the first scroll event
|
||||
// remains inside LegendList's at-end tolerance.
|
||||
const listState = props.listRef.current?.getState();
|
||||
if (listState) {
|
||||
if (listState.isWithinMaintainScrollAtEndThreshold) {
|
||||
setEndFollow(true);
|
||||
} else if (userScrollSessionRef.current) {
|
||||
setEndFollow(false);
|
||||
}
|
||||
transitionEndFollow({
|
||||
type: "scroll",
|
||||
isAtEnd: listState.isAtEnd,
|
||||
userScrollSessionActive: userScrollSessionRef.current,
|
||||
});
|
||||
}
|
||||
},
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
|
||||
);
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
userScrollSessionRef.current = true;
|
||||
}, []);
|
||||
// The session must survive past finger-lift so momentum that carries the
|
||||
// user away from the end still breaks follow; a drag released with no
|
||||
// momentum ends its session at the release itself, otherwise at momentum
|
||||
// end. Leaving a session open would let a later animated maintain-scroll
|
||||
// read as user motion and break follow spuriously.
|
||||
const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
const velocity = event.nativeEvent.velocity?.y ?? 0;
|
||||
if (Math.abs(velocity) < 0.05) {
|
||||
userScrollSessionRef.current = false;
|
||||
const clearUserScrollSettle = useCallback(() => {
|
||||
if (userScrollSettleTimerRef.current !== null) {
|
||||
clearTimeout(userScrollSettleTimerRef.current);
|
||||
userScrollSettleTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = true;
|
||||
// Pause before the first scroll event. Otherwise a stream update can run
|
||||
// maintainScrollAtEnd between touch-down and the drag leaving its threshold.
|
||||
transitionEndFollow({ type: "user-scroll-begin" });
|
||||
}, [clearUserScrollSettle, transitionEndFollow]);
|
||||
const finishUserScroll = useCallback(
|
||||
(releaseIsAtEnd?: boolean) => {
|
||||
clearUserScrollSettle();
|
||||
const userScrollSessionActive = userScrollSessionRef.current;
|
||||
userScrollSessionRef.current = false;
|
||||
transitionEndFollow({
|
||||
type: "user-scroll-end",
|
||||
// With no momentum, preserve the finger-release position. Streaming
|
||||
// growth during the native momentum-detection window must not turn a
|
||||
// release at the live edge into an opt-out from follow.
|
||||
isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false,
|
||||
userScrollSessionActive,
|
||||
});
|
||||
},
|
||||
[clearUserScrollSettle, props.listRef, transitionEndFollow],
|
||||
);
|
||||
// Finger-lift velocity is not a reliable momentum signal: a gentle fling
|
||||
// can report zero and still decelerate. Give native momentum a short window
|
||||
// to announce itself; if it does, onMomentumScrollBegin cancels this fallback
|
||||
// and the session survives until the settled momentum-end position. This
|
||||
// mirrors the native-event handoff used by the home thread list's scroll gate.
|
||||
const handleScrollEndDrag = useCallback(() => {
|
||||
clearUserScrollSettle();
|
||||
const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false;
|
||||
userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160);
|
||||
}, [clearUserScrollSettle, finishUserScroll, props.listRef]);
|
||||
const handleMomentumScrollBegin = useCallback(() => {
|
||||
if (userScrollSessionRef.current) {
|
||||
clearUserScrollSettle();
|
||||
}
|
||||
}, [clearUserScrollSettle]);
|
||||
const handleMomentumScrollEnd = useCallback(() => {
|
||||
userScrollSessionRef.current = false;
|
||||
}, []);
|
||||
finishUserScroll();
|
||||
}, [finishUserScroll]);
|
||||
|
||||
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
|
||||
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
@@ -1491,23 +1551,30 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
|
||||
}, []);
|
||||
|
||||
// Thread identity is env-scoped: two environments can hold the same
|
||||
// ThreadId, and keying resets (or the list mount) on the bare id would
|
||||
// carry stale scroll/follow state across an environment switch.
|
||||
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
|
||||
|
||||
useEffect(() => {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [props.threadId, reportHeaderMaterialVisibility]);
|
||||
}, [feedThreadKey, reportHeaderMaterialVisibility]);
|
||||
|
||||
// A thread switch opens pinned to the end; a send explicitly returns to the
|
||||
// live edge (ThreadDetailScreen scrolls the new message into place). Both
|
||||
// re-arm follow regardless of where the user had scrolled before.
|
||||
useEffect(() => {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
}, [props.threadId, setEndFollow]);
|
||||
transitionEndFollow({ type: "reset" });
|
||||
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
|
||||
useEffect(() => {
|
||||
if (props.anchorMessageId !== null) {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
transitionEndFollow({ type: "reset" });
|
||||
}
|
||||
}, [props.anchorMessageId, setEndFollow]);
|
||||
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
@@ -1543,7 +1610,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// initial scroll-to-end computes with a zero end inset and rests one
|
||||
// composer-height short of the end. Layout effect: it must land before the
|
||||
// list's first positioning tick or the one-shot initial scroll misses it.
|
||||
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
useLayoutEffect(() => {
|
||||
const bottom = props.contentInsetEndAdjustment.value;
|
||||
if (bottom > 0) {
|
||||
@@ -1910,6 +1977,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onScroll={handleScroll}
|
||||
onScrollBeginDrag={handleScrollBeginDrag}
|
||||
onScrollEndDrag={handleScrollEndDrag}
|
||||
onMomentumScrollBegin={handleMomentumScrollBegin}
|
||||
onMomentumScrollEnd={handleMomentumScrollEnd}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
|
||||
@@ -30,6 +30,7 @@ import { cn } from "../../lib/cn";
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { RUNTIME_MODE_CHOICES, selectableChoices } from "./thread-settings-menu";
|
||||
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
|
||||
import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
@@ -40,26 +41,6 @@ import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet
|
||||
*/
|
||||
const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
|
||||
|
||||
/**
|
||||
* Desktop-oriented effort keywords that don't belong in the phone picker.
|
||||
* Prompt-injected values (ultrathink and friends) are filtered from the
|
||||
* descriptor metadata; ultracode is a real option but a workflow trigger, not
|
||||
* a reasoning level. A value set elsewhere still displays, it just isn't
|
||||
* offered.
|
||||
*/
|
||||
const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly shortLabel: string;
|
||||
}> = [
|
||||
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
|
||||
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
|
||||
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
|
||||
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
|
||||
* covering model, provider options, runtime mode, and plan mode in one label.
|
||||
@@ -79,13 +60,6 @@ export function threadSettingsSummaryLabel(input: {
|
||||
].join(" · ");
|
||||
}
|
||||
|
||||
function selectableChoices(descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>) {
|
||||
const injected = new Set(descriptor.promptInjectedValues ?? []);
|
||||
return descriptor.options.filter(
|
||||
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
|
||||
);
|
||||
}
|
||||
|
||||
function ModelRow(props: {
|
||||
readonly option: ModelOption;
|
||||
readonly selected: boolean;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { derivePendingUserInputMaxHeight } from "./pendingUserInputLayout";
|
||||
|
||||
describe("derivePendingUserInputMaxHeight", () => {
|
||||
it("caps a tall portrait viewport", () => {
|
||||
expect(
|
||||
derivePendingUserInputMaxHeight({
|
||||
windowHeight: 932,
|
||||
keyboardHeight: 0,
|
||||
navigationHeaderHeight: 103,
|
||||
composerOverlapHeight: 94,
|
||||
}),
|
||||
).toBe(560);
|
||||
});
|
||||
|
||||
it("subtracts the keyboard while editing a custom answer", () => {
|
||||
expect(
|
||||
derivePendingUserInputMaxHeight({
|
||||
windowHeight: 932,
|
||||
keyboardHeight: 336,
|
||||
navigationHeaderHeight: 103,
|
||||
composerOverlapHeight: 94,
|
||||
}),
|
||||
).toBe(387);
|
||||
});
|
||||
|
||||
it("keeps the fixed action area usable in a short keyboard-open viewport", () => {
|
||||
expect(
|
||||
derivePendingUserInputMaxHeight({
|
||||
windowHeight: 375,
|
||||
keyboardHeight: 240,
|
||||
navigationHeaderHeight: 44,
|
||||
composerOverlapHeight: 94,
|
||||
}),
|
||||
).toBe(160);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
const PENDING_USER_INPUT_MAX_HEIGHT = 560;
|
||||
const PENDING_USER_INPUT_MIN_HEIGHT = 160;
|
||||
const PENDING_USER_INPUT_VERTICAL_GAP = 12;
|
||||
|
||||
/**
|
||||
* Reserve for a portrait iPhone keyboard with the QuickType bar until a real
|
||||
* height has been observed. Overestimating only costs card height; an
|
||||
* underestimate would let the card overshoot on the first keyboard open.
|
||||
*/
|
||||
export const ESTIMATED_KEYBOARD_HEIGHT = 336;
|
||||
|
||||
/**
|
||||
* One clock for the questionnaire expand/collapse choreography: the card's
|
||||
* enter/exit and the feed-inset glide must share it or they visibly drift.
|
||||
* Sized for the near-full-height slide (the card travels its own height),
|
||||
* in the same class as the iOS keyboard's ~250ms.
|
||||
*/
|
||||
export const USER_INPUT_TOGGLE_DURATION_MS = 220;
|
||||
|
||||
export function derivePendingUserInputMaxHeight(input: {
|
||||
readonly windowHeight: number;
|
||||
readonly keyboardHeight: number;
|
||||
readonly navigationHeaderHeight: number;
|
||||
readonly composerOverlapHeight: number;
|
||||
}): number {
|
||||
const availableHeight =
|
||||
input.windowHeight -
|
||||
Math.max(0, input.keyboardHeight) -
|
||||
Math.max(0, input.navigationHeaderHeight) -
|
||||
Math.max(0, input.composerOverlapHeight) -
|
||||
PENDING_USER_INPUT_VERTICAL_GAP;
|
||||
|
||||
return Math.min(
|
||||
PENDING_USER_INPUT_MAX_HEIGHT,
|
||||
Math.max(PENDING_USER_INPUT_MIN_HEIGHT, availableHeight),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveThreadFeedLiveFollow } from "./thread-feed-live-follow";
|
||||
|
||||
describe("resolveThreadFeedLiveFollow", () => {
|
||||
it("pauses immediately when the user starts scrolling", () => {
|
||||
expect(resolveThreadFeedLiveFollow(true, { type: "user-scroll-begin" })).toBe(false);
|
||||
});
|
||||
|
||||
it("stays paused away from the actual end", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "scroll",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not mistake programmatic layout compensation for a user scroll", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(true, {
|
||||
type: "scroll",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not re-arm at the end while a user scroll session is active", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "scroll",
|
||||
isAtEnd: true,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("re-arms at the actual end only after the user scroll session ends", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "user-scroll-end",
|
||||
isAtEnd: true,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(false, {
|
||||
type: "user-scroll-end",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores momentum-end events from programmatic scrolling", () => {
|
||||
expect(
|
||||
resolveThreadFeedLiveFollow(true, {
|
||||
type: "user-scroll-end",
|
||||
isAtEnd: false,
|
||||
userScrollSessionActive: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("re-arms after an explicit reset", () => {
|
||||
expect(resolveThreadFeedLiveFollow(false, { type: "reset" })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
export type ThreadFeedLiveFollowEvent =
|
||||
| { readonly type: "reset" }
|
||||
| { readonly type: "user-scroll-begin" }
|
||||
| {
|
||||
readonly type: "user-scroll-end";
|
||||
readonly isAtEnd: boolean;
|
||||
readonly userScrollSessionActive: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "scroll";
|
||||
readonly isAtEnd: boolean;
|
||||
readonly userScrollSessionActive: boolean;
|
||||
};
|
||||
|
||||
export function resolveThreadFeedLiveFollow(
|
||||
current: boolean,
|
||||
event: ThreadFeedLiveFollowEvent,
|
||||
): boolean {
|
||||
switch (event.type) {
|
||||
case "reset":
|
||||
return true;
|
||||
case "user-scroll-begin":
|
||||
return false;
|
||||
case "user-scroll-end":
|
||||
return event.userScrollSessionActive ? event.isAtEnd : current;
|
||||
case "scroll":
|
||||
if (event.userScrollSessionActive) {
|
||||
return false;
|
||||
}
|
||||
if (event.isAtEnd) {
|
||||
return true;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProviderInstanceId, type ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { buildThreadSettingsMenu, type ThreadSettingsMenuEvent } from "./thread-settings-menu";
|
||||
|
||||
function modelOption(
|
||||
model: string,
|
||||
overrides: Partial<Pick<ModelOption, "isDefault" | "isLegacy" | "providerKey">> = {},
|
||||
): ModelOption {
|
||||
const providerKey = overrides.providerKey ?? "codex";
|
||||
return {
|
||||
key: `${providerKey}:${model}`,
|
||||
label: model,
|
||||
subtitle: providerKey,
|
||||
providerKey,
|
||||
providerLabel: providerKey === "codex" ? "Codex" : "Claude",
|
||||
providerDriver: providerKey === "codex" ? "codex" : "claudeAgent",
|
||||
isDefault: overrides.isDefault ?? false,
|
||||
isLegacy: overrides.isLegacy ?? false,
|
||||
capabilities: null,
|
||||
selection: {
|
||||
instanceId: ProviderInstanceId.make(providerKey),
|
||||
model,
|
||||
options: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function group(models: ReadonlyArray<ModelOption>): ProviderGroup {
|
||||
const first = models[0];
|
||||
if (!first) {
|
||||
throw new Error("group requires at least one model");
|
||||
}
|
||||
return {
|
||||
providerKey: first.providerKey,
|
||||
providerLabel: first.providerLabel,
|
||||
models,
|
||||
};
|
||||
}
|
||||
|
||||
const effortDescriptor: ProviderOptionDescriptor = {
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium", isDefault: true },
|
||||
{ id: "high", label: "High" },
|
||||
{ id: "ultrathink", label: "Ultrathink" },
|
||||
{ id: "ultracode", label: "Ultracode" },
|
||||
],
|
||||
currentValue: "high",
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
};
|
||||
|
||||
const fastModeDescriptor: ProviderOptionDescriptor = {
|
||||
id: "fastMode",
|
||||
label: "Fast mode",
|
||||
type: "boolean",
|
||||
currentValue: false,
|
||||
};
|
||||
|
||||
function baseInput() {
|
||||
const models = [
|
||||
modelOption("gpt-current", { isDefault: true }),
|
||||
modelOption("gpt-next"),
|
||||
modelOption("gpt-old", { isLegacy: true }),
|
||||
];
|
||||
return {
|
||||
providerGroups: [group(models)],
|
||||
selectedModel: models[0]?.selection ?? null,
|
||||
optionDescriptors: [effortDescriptor, fastModeDescriptor],
|
||||
runtimeMode: "auto",
|
||||
} as const;
|
||||
}
|
||||
|
||||
function eventFor(menu: ReturnType<typeof buildThreadSettingsMenu>, id: string | undefined) {
|
||||
return id === undefined ? undefined : menu.events.get(id);
|
||||
}
|
||||
|
||||
describe("buildThreadSettingsMenu", () => {
|
||||
it("orders the top level as model, options, runtime", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
expect(menu.actions.map((action) => action.title)).toEqual([
|
||||
"Model",
|
||||
"Reasoning",
|
||||
"Fast mode",
|
||||
"Runtime",
|
||||
]);
|
||||
});
|
||||
|
||||
it("summarizes the current choice on each submenu row", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
expect(menu.actions.find((action) => action.title === "Model")?.subtitle).toBe("gpt-current");
|
||||
expect(menu.actions.find((action) => action.title === "Reasoning")?.subtitle).toBe("High");
|
||||
expect(menu.actions.find((action) => action.title === "Runtime")?.subtitle).toBe("Auto");
|
||||
});
|
||||
|
||||
it("checkmarks the selected model and resolves selection events", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
const current = modelItems.find((action) => action.title === "gpt-current");
|
||||
expect(current?.state).toBe("on");
|
||||
expect(current?.subtitle).toBe("Default");
|
||||
expect(modelItems.find((action) => action.title === "gpt-next")?.state).toBe("off");
|
||||
|
||||
const event = eventFor(menu, modelItems.find((action) => action.title === "gpt-next")?.id);
|
||||
expect(event?.type).toBe("select-model");
|
||||
expect(event?.type === "select-model" ? event.option.selection.model : null).toBe("gpt-next");
|
||||
});
|
||||
|
||||
it("folds unselected legacy models behind a nested submenu", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(modelItems.map((action) => action.title)).toEqual([
|
||||
"gpt-current",
|
||||
"gpt-next",
|
||||
"Legacy Models",
|
||||
]);
|
||||
expect(
|
||||
modelItems
|
||||
.find((action) => action.title === "Legacy Models")
|
||||
?.subactions?.map((action) => action.title),
|
||||
).toEqual(["gpt-old"]);
|
||||
});
|
||||
|
||||
it("keeps a selected legacy model in the main list", () => {
|
||||
const input = baseInput();
|
||||
const legacy = input.providerGroups[0]?.models.find((model) => model.isLegacy);
|
||||
const menu = buildThreadSettingsMenu({
|
||||
...input,
|
||||
selectedModel: legacy?.selection ?? null,
|
||||
});
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(modelItems.map((action) => action.title)).toEqual([
|
||||
"gpt-current",
|
||||
"gpt-next",
|
||||
"gpt-old",
|
||||
]);
|
||||
expect(modelItems.find((action) => action.title === "gpt-old")?.state).toBe("on");
|
||||
});
|
||||
|
||||
it("hides prompt-injected and workflow-trigger efforts but still summarizes them", () => {
|
||||
const menu = buildThreadSettingsMenu({
|
||||
...baseInput(),
|
||||
optionDescriptors: [{ ...effortDescriptor, currentValue: "ultracode" }],
|
||||
});
|
||||
|
||||
const reasoning = menu.actions.find((action) => action.title === "Reasoning");
|
||||
expect(reasoning?.subactions?.map((action) => action.title)).toEqual(["Low", "Medium", "High"]);
|
||||
// The hidden value stays visible as the current summary; it just can't be
|
||||
// picked from the phone.
|
||||
expect(reasoning?.subtitle).toBe("Ultracode");
|
||||
expect(reasoning?.subactions?.every((action) => action.state === "off")).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves select-option and runtime events with checkmarked current values", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const reasoningItems =
|
||||
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
|
||||
expect(reasoningItems.find((action) => action.title === "High")?.state).toBe("on");
|
||||
expect(eventFor(menu, reasoningItems.find((action) => action.title === "Low")?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "effort",
|
||||
value: "low",
|
||||
});
|
||||
|
||||
const runtimeItems =
|
||||
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
|
||||
expect(runtimeItems.find((action) => action.title === "Auto")?.state).toBe("on");
|
||||
expect(
|
||||
eventFor(menu, runtimeItems.find((action) => action.title === "Full access")?.id),
|
||||
).toEqual({ type: "set-runtime", mode: "full-access" });
|
||||
});
|
||||
|
||||
it("toggles boolean options with the inverted current value", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
const fastMode = menu.actions.find((action) => action.title === "Fast mode");
|
||||
expect(fastMode?.state).toBe("off");
|
||||
expect(fastMode?.subactions).toBeUndefined();
|
||||
expect(eventFor(menu, fastMode?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "fastMode",
|
||||
value: true,
|
||||
});
|
||||
|
||||
const enabled = buildThreadSettingsMenu({
|
||||
...baseInput(),
|
||||
optionDescriptors: [{ ...fastModeDescriptor, currentValue: true }],
|
||||
});
|
||||
const enabledRow = enabled.actions.find((action) => action.title === "Fast mode");
|
||||
expect(enabledRow?.state).toBe("on");
|
||||
expect(eventFor(enabled, enabledRow?.id)).toEqual({
|
||||
type: "set-option",
|
||||
optionId: "fastMode",
|
||||
value: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the menu presented only for top-level toggles", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
|
||||
// Root-level boolean toggles refresh in place with clean chrome, so they
|
||||
// keep the menu presented.
|
||||
expect(
|
||||
menu.actions.find((action) => action.title === "Fast mode")?.attributes?.keepsMenuPresented,
|
||||
).toBe(true);
|
||||
|
||||
// Picks inside nested submenus close the menu: staying presented leaves
|
||||
// the submenu on screen with an expanded-submenu header, and the
|
||||
// bottom-anchored collapse back out drops by the levels' height delta.
|
||||
const expected = undefined;
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
const reasoningItems =
|
||||
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
|
||||
const runtimeItems =
|
||||
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
|
||||
const nestedPicks = [...modelItems, ...reasoningItems, ...runtimeItems].filter(
|
||||
(action) => action.subactions === undefined,
|
||||
);
|
||||
expect(nestedPicks.length).toBeGreaterThan(0);
|
||||
expect(nestedPicks.every((action) => action.attributes?.keepsMenuPresented === expected)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("sections models by provider only when multiple groups are offered", () => {
|
||||
const codexModels = [modelOption("gpt-current", { isDefault: true })];
|
||||
const claudeModels = [modelOption("fable-5", { providerKey: "claude" })];
|
||||
const menu = buildThreadSettingsMenu({
|
||||
providerGroups: [group(codexModels), group(claudeModels)],
|
||||
selectedModel: codexModels[0]?.selection ?? null,
|
||||
optionDescriptors: [],
|
||||
runtimeMode: "auto",
|
||||
});
|
||||
|
||||
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
|
||||
expect(
|
||||
modelItems.map((action) => ({ title: action.title, inline: action.displayInline ?? false })),
|
||||
).toEqual([
|
||||
{ title: "Codex", inline: true },
|
||||
{ title: "Claude", inline: true },
|
||||
]);
|
||||
const claudeSection = modelItems.find((action) => action.title === "Claude");
|
||||
expect(claudeSection?.subactions?.map((action) => action.title)).toEqual(["fable-5"]);
|
||||
});
|
||||
|
||||
const eventTypes = (menu: ReturnType<typeof buildThreadSettingsMenu>) => {
|
||||
const types = new Set<ThreadSettingsMenuEvent["type"]>();
|
||||
for (const event of menu.events.values()) {
|
||||
types.add(event.type);
|
||||
}
|
||||
return types;
|
||||
};
|
||||
|
||||
it("registers an event for every leaf action id", () => {
|
||||
const menu = buildThreadSettingsMenu(baseInput());
|
||||
const leafIds: string[] = [];
|
||||
const collect = (items: ReadonlyArray<{ id?: string; subactions?: unknown[] }>) => {
|
||||
for (const item of items) {
|
||||
if (Array.isArray(item.subactions) && item.subactions.length > 0) {
|
||||
collect(item.subactions as ReadonlyArray<{ id?: string; subactions?: unknown[] }>);
|
||||
} else if (item.id !== undefined) {
|
||||
leafIds.push(item.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
collect(menu.actions);
|
||||
|
||||
for (const id of leafIds) {
|
||||
expect(menu.events.get(id), `missing event for ${id}`).toBeDefined();
|
||||
}
|
||||
expect(eventTypes(menu)).toEqual(new Set(["select-model", "set-option", "set-runtime"]));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import type { ModelSelection, ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
|
||||
import {
|
||||
getProviderOptionCurrentLabel,
|
||||
getProviderOptionCurrentValue,
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
|
||||
/**
|
||||
* Desktop-oriented effort keywords that don't belong in the phone picker.
|
||||
* Prompt-injected values (ultrathink and friends) are filtered from the
|
||||
* descriptor metadata; ultracode is a real option but a workflow trigger, not
|
||||
* a reasoning level. A value set elsewhere still displays, it just isn't
|
||||
* offered.
|
||||
*/
|
||||
export const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly shortLabel: string;
|
||||
}> = [
|
||||
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
|
||||
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
|
||||
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
|
||||
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
|
||||
];
|
||||
|
||||
export function selectableChoices(
|
||||
descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
|
||||
) {
|
||||
const injected = new Set(descriptor.promptInjectedValues ?? []);
|
||||
return descriptor.options.filter(
|
||||
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
|
||||
);
|
||||
}
|
||||
|
||||
export type ThreadSettingsMenuEvent =
|
||||
| { readonly type: "select-model"; readonly option: ModelOption }
|
||||
| { readonly type: "set-option"; readonly optionId: string; readonly value: string | boolean }
|
||||
| { readonly type: "set-runtime"; readonly mode: RuntimeMode };
|
||||
|
||||
export type ThreadSettingsMenu = {
|
||||
readonly actions: MenuAction[];
|
||||
/** Menu action id → the change it applies, for the onPressAction dispatch. */
|
||||
readonly events: ReadonlyMap<string, ThreadSettingsMenuEvent>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Native menu replacement for the thread settings sheet (model, select and
|
||||
* boolean provider options, runtime mode). The menu presents from the
|
||||
* composer pill without resigning the keyboard, so adjusting settings never
|
||||
* bounces focus. A thread is bound to one harness, so the menu covers the
|
||||
* sheet's full surface for existing threads; the sheet remains the Android
|
||||
* and new-task-draft surface.
|
||||
*
|
||||
* Selections apply immediately — the sheet's stage-then-Save flow only exists
|
||||
* because the sheet batches a model change with its option edits.
|
||||
*/
|
||||
export function buildThreadSettingsMenu(input: {
|
||||
readonly providerGroups: ReadonlyArray<ProviderGroup>;
|
||||
readonly selectedModel: ModelSelection | null;
|
||||
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
}): ThreadSettingsMenu {
|
||||
const events = new Map<string, ThreadSettingsMenuEvent>();
|
||||
const actions: MenuAction[] = [];
|
||||
|
||||
const isSelected = (option: ModelOption) =>
|
||||
option.selection.instanceId === input.selectedModel?.instanceId &&
|
||||
option.selection.model === input.selectedModel.model;
|
||||
|
||||
// Only top-level leaves (boolean toggles) keep the menu presented (iOS
|
||||
// 16+): the root refreshes in place with clean chrome. Picks inside nested
|
||||
// submenus close the menu — keeping the submenu presented renders an
|
||||
// expanded-submenu header with no way to pop back to the root, and the
|
||||
// bottom-anchored collapse back out travels the levels' height difference.
|
||||
const keepPresented = { keepsMenuPresented: true } as const;
|
||||
|
||||
const modelAction = (option: ModelOption, id: string): MenuAction => {
|
||||
events.set(id, { type: "select-model", option });
|
||||
return {
|
||||
id,
|
||||
title: option.label,
|
||||
...(option.isDefault ? { subtitle: "Default" } : {}),
|
||||
state: isSelected(option) ? "on" : "off",
|
||||
};
|
||||
};
|
||||
|
||||
const modelItems: MenuAction[] = [];
|
||||
const legacyItems: MenuAction[] = [];
|
||||
let selectedModelLabel: string | undefined;
|
||||
input.providerGroups.forEach((group, groupIndex) => {
|
||||
const groupItems: MenuAction[] = [];
|
||||
group.models.forEach((option, modelIndex) => {
|
||||
if (isSelected(option)) {
|
||||
selectedModelLabel = option.label;
|
||||
}
|
||||
const id = `model:${groupIndex}:${modelIndex}`;
|
||||
// A highlighted legacy model stays in the main list (mirroring the
|
||||
// sheet) so the checkmark isn't hidden behind the Legacy fold.
|
||||
if (option.isLegacy && !isSelected(option)) {
|
||||
legacyItems.push(modelAction(option, id));
|
||||
} else {
|
||||
groupItems.push(modelAction(option, id));
|
||||
}
|
||||
});
|
||||
if (groupItems.length === 0) {
|
||||
return;
|
||||
}
|
||||
// A thread is bound to one harness, so provider sections only appear for
|
||||
// multi-group callers (the new-task draft, if it ever adopts the menu).
|
||||
if (input.providerGroups.length > 1) {
|
||||
modelItems.push({
|
||||
id: `model-group:${groupIndex}`,
|
||||
title: group.providerLabel,
|
||||
displayInline: true,
|
||||
subactions: groupItems,
|
||||
});
|
||||
} else {
|
||||
modelItems.push(...groupItems);
|
||||
}
|
||||
});
|
||||
if (legacyItems.length > 0) {
|
||||
modelItems.push({
|
||||
id: "legacy-models",
|
||||
title: "Legacy Models",
|
||||
subactions: legacyItems,
|
||||
});
|
||||
}
|
||||
if (modelItems.length > 0) {
|
||||
actions.push({
|
||||
id: "model",
|
||||
title: "Model",
|
||||
...(selectedModelLabel === undefined
|
||||
? input.selectedModel
|
||||
? { subtitle: input.selectedModel.model }
|
||||
: {}
|
||||
: { subtitle: selectedModelLabel }),
|
||||
subactions: modelItems,
|
||||
});
|
||||
}
|
||||
|
||||
for (const descriptor of input.optionDescriptors) {
|
||||
if (descriptor.type === "boolean") {
|
||||
const id = `option:${descriptor.id}`;
|
||||
events.set(id, {
|
||||
type: "set-option",
|
||||
optionId: descriptor.id,
|
||||
value: !(descriptor.currentValue ?? false),
|
||||
});
|
||||
actions.push({
|
||||
id,
|
||||
title: descriptor.label,
|
||||
state: descriptor.currentValue ? "on" : "off",
|
||||
attributes: keepPresented,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const currentValue = getProviderOptionCurrentValue(descriptor);
|
||||
const choices = selectableChoices(descriptor).map((choice): MenuAction => {
|
||||
const id = `option:${descriptor.id}:${choice.id}`;
|
||||
events.set(id, { type: "set-option", optionId: descriptor.id, value: choice.id });
|
||||
return {
|
||||
id,
|
||||
title: choice.label,
|
||||
state: choice.id === currentValue ? "on" : "off",
|
||||
};
|
||||
});
|
||||
if (choices.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const currentLabel = getProviderOptionCurrentLabel(descriptor);
|
||||
actions.push({
|
||||
id: `option:${descriptor.id}`,
|
||||
title: descriptor.label,
|
||||
...(currentLabel === undefined ? {} : { subtitle: currentLabel }),
|
||||
subactions: choices,
|
||||
});
|
||||
}
|
||||
|
||||
const runtimeLabel = RUNTIME_MODE_CHOICES.find(
|
||||
(choice) => choice.mode === input.runtimeMode,
|
||||
)?.label;
|
||||
actions.push({
|
||||
id: "runtime",
|
||||
title: "Runtime",
|
||||
...(runtimeLabel === undefined ? {} : { subtitle: runtimeLabel }),
|
||||
subactions: RUNTIME_MODE_CHOICES.map((choice): MenuAction => {
|
||||
const id = `runtime:${choice.mode}`;
|
||||
events.set(id, { type: "set-runtime", mode: choice.mode });
|
||||
return {
|
||||
id,
|
||||
title: choice.label,
|
||||
state: choice.mode === input.runtimeMode ? "on" : "off",
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
return { actions, events };
|
||||
}
|
||||
@@ -32,6 +32,19 @@ function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateCl
|
||||
}
|
||||
|
||||
describe("runAppUpdateCheck", () => {
|
||||
it("does nothing while running from the Metro development server", async () => {
|
||||
vi.stubGlobal("__DEV__", true);
|
||||
const client = makeUpdateClient();
|
||||
|
||||
try {
|
||||
await runAppUpdateCheck({ client });
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
|
||||
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("downloads and restarts when a new update is available", async () => {
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
@@ -100,6 +113,32 @@ describe("runAppUpdateCheck", () => {
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it.each(["ERR_NOT_AVAILABLE_IN_DEV_CLIENT", "ERR_UPDATES_DISABLED"])(
|
||||
"treats Expo's %s failure as an unavailable update check",
|
||||
async (code) => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const error = Object.assign(new Error("Updates are unavailable"), { code });
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => {
|
||||
throw error;
|
||||
}),
|
||||
});
|
||||
const failures: string[] = [];
|
||||
const states: AppUpdateCheckState[] = [];
|
||||
|
||||
await runAppUpdateCheck({
|
||||
client,
|
||||
onFailure: (message) => failures.push(message),
|
||||
onStateChange: (state) => states.push(state),
|
||||
});
|
||||
|
||||
expect(reportError).not.toHaveBeenCalled();
|
||||
expect(failures).toEqual([]);
|
||||
expect(states).toEqual(["checking", "idle"]);
|
||||
reportError.mockRestore();
|
||||
},
|
||||
);
|
||||
|
||||
it("coalesces overlapping launch and manual checks", async () => {
|
||||
let resolveCheck!: (result: {
|
||||
readonly isAvailable: boolean;
|
||||
|
||||
@@ -48,8 +48,17 @@ interface Deferred {
|
||||
}
|
||||
|
||||
const HIDDEN_UPDATE_TAP_COUNT = 5;
|
||||
const UPDATE_CHECK_UNAVAILABLE_ERROR_CODES = new Set([
|
||||
"ERR_NOT_AVAILABLE_IN_DEV_CLIENT",
|
||||
"ERR_UPDATES_DISABLED",
|
||||
]);
|
||||
let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
|
||||
|
||||
/** Expo's development launcher reports updates as enabled even though its OTA APIs reject. */
|
||||
export function isAppUpdateCheckAvailable(client: Pick<AppUpdateClient, "isEnabled"> = Updates) {
|
||||
return client.isEnabled && !(typeof __DEV__ !== "undefined" && __DEV__);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the manual update affordance discoverable only to someone deliberately
|
||||
* tapping the version row five times.
|
||||
@@ -73,7 +82,7 @@ export function registerHiddenUpdateTap(count: number): {
|
||||
|
||||
export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
|
||||
const client = options.client ?? Updates;
|
||||
if (!client.isEnabled) return;
|
||||
if (!isAppUpdateCheckAvailable(client)) return;
|
||||
|
||||
if (appUpdateCheckInFlight) {
|
||||
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
|
||||
@@ -207,19 +216,27 @@ function reportUpdateFailure(
|
||||
fallback: string,
|
||||
onFailure: AppUpdateCheckOptions["onFailure"],
|
||||
): void {
|
||||
reportAtomCommandResult(result, { label: "app update check" });
|
||||
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
|
||||
const error = squashAtomCommandFailure(result);
|
||||
if (isAppUpdateUnavailableError(error)) return;
|
||||
|
||||
reportAtomCommandResult(result, { label: "app update check" });
|
||||
onFailure?.(error instanceof Error ? error.message : fallback);
|
||||
}
|
||||
|
||||
function isAppUpdateUnavailableError(error: unknown): boolean {
|
||||
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
||||
const code = error.code;
|
||||
return typeof code === "string" && UPDATE_CHECK_UNAVAILABLE_ERROR_CODES.has(code);
|
||||
}
|
||||
|
||||
export function createAppUpdateLaunchCheck(
|
||||
client: AppUpdateClient = Updates,
|
||||
): () => Promise<void> | undefined {
|
||||
let started = false;
|
||||
|
||||
return () => {
|
||||
if (started || !client.isEnabled) return undefined;
|
||||
if (started || !isAppUpdateCheckAvailable(client)) return undefined;
|
||||
started = true;
|
||||
return runAppUpdateCheck({ client });
|
||||
};
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import {
|
||||
enumerateDays,
|
||||
enumerateHourStarts,
|
||||
formatCount,
|
||||
formatDayShort,
|
||||
formatHourShort,
|
||||
formatPercent,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
@@ -26,6 +28,7 @@ import type { UsageChartMetric } from "./usageChartData";
|
||||
import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
|
||||
|
||||
const WINDOW_OPTIONS = [
|
||||
{ days: 1, label: "Past 24h" },
|
||||
{ days: 7, label: "7 days" },
|
||||
{ days: 30, label: "30 days" },
|
||||
{ days: 90, label: "90 days" },
|
||||
@@ -36,13 +39,14 @@ const CHART_HEIGHT = 180;
|
||||
export function UsageRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const [windowDays, setWindowDays] = useState<number>(30);
|
||||
const [windowSelection, setWindowSelection] = useState(() => ({
|
||||
days: 30,
|
||||
window: makeWindow(30),
|
||||
}));
|
||||
const [metric, setMetric] = useState<UsageChartMetric>("cost");
|
||||
const [environmentFilter, setEnvironmentFilter] = useState<EnvironmentId | null>(null);
|
||||
|
||||
// Recomputed only when the window length changes, so a re-render does not
|
||||
// shift the range and refetch every environment.
|
||||
const window = useMemo(() => makeWindow(windowDays), [windowDays]);
|
||||
const { days: windowDays, window } = windowSelection;
|
||||
const isPast24Hours = windowDays === 1;
|
||||
const { merged, options, environments, selectedEnvironmentId, isPending, isPartial, refresh } =
|
||||
useUsage(window, environmentFilter);
|
||||
|
||||
@@ -86,12 +90,50 @@ export function UsageRouteScreen() {
|
||||
() => enumerateDays(window.sinceDay, window.untilDay),
|
||||
[window.sinceDay, window.untilDay],
|
||||
);
|
||||
const chartDays = useMemo(
|
||||
() =>
|
||||
isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
|
||||
? enumerateHourStarts(window.sinceTime, window.untilTime)
|
||||
: days,
|
||||
[days, isPast24Hours, window.sinceTime, window.untilTime],
|
||||
);
|
||||
const chartTotals = useMemo(
|
||||
(): readonly DailyTotals[] =>
|
||||
isPast24Hours
|
||||
? merged.hourly.map((hour) => ({
|
||||
day: hour.hourStart,
|
||||
costUsd: hour.costUsd,
|
||||
totalTokens: hour.totalTokens,
|
||||
byProvider: hour.byProvider,
|
||||
}))
|
||||
: merged.daily,
|
||||
[isPast24Hours, merged.daily, merged.hourly],
|
||||
);
|
||||
|
||||
// The pull spinner tracks re-scans of connected environments that have
|
||||
// answered before. The initial scan renders its own placeholder.
|
||||
const refreshing = environments.some(
|
||||
(entry) => entry.phase === "connected" && entry.isPending && entry.summary !== null,
|
||||
);
|
||||
const selectWindow = (days: number) => {
|
||||
setWindowSelection({
|
||||
days,
|
||||
window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
|
||||
});
|
||||
};
|
||||
const refreshWindow = () => {
|
||||
const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
|
||||
if (
|
||||
nextWindow.sinceDay === window.sinceDay &&
|
||||
nextWindow.untilDay === window.untilDay &&
|
||||
nextWindow.sinceTime === window.sinceTime &&
|
||||
nextWindow.untilTime === window.untilTime
|
||||
) {
|
||||
refresh();
|
||||
} else {
|
||||
setWindowSelection({ days: windowDays, window: nextWindow });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
@@ -107,7 +149,7 @@ export function UsageRouteScreen() {
|
||||
className="flex-1"
|
||||
contentContainerClassName="gap-6 px-5 pt-4"
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refresh} />}
|
||||
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}
|
||||
>
|
||||
<View className="gap-3">
|
||||
<SegmentedControl
|
||||
@@ -116,7 +158,7 @@ export function UsageRouteScreen() {
|
||||
label: option.label,
|
||||
}))}
|
||||
selected={windowDays}
|
||||
onSelect={setWindowDays}
|
||||
onSelect={selectWindow}
|
||||
/>
|
||||
<View className="max-w-full items-start">
|
||||
<ControlPillMenu
|
||||
@@ -159,14 +201,17 @@ export function UsageRouteScreen() {
|
||||
<>
|
||||
<ChartCard
|
||||
merged={merged}
|
||||
days={days}
|
||||
days={chartDays}
|
||||
daily={chartTotals}
|
||||
metric={metric}
|
||||
onMetricChange={setMetric}
|
||||
sinceDay={window.sinceDay}
|
||||
untilDay={window.untilDay}
|
||||
isPast24Hours={isPast24Hours}
|
||||
timeZone={window.timeZone}
|
||||
/>
|
||||
<ProviderSection merged={merged} metric={metric} />
|
||||
<TotalsSection merged={merged} />
|
||||
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
|
||||
<ModelsSection merged={merged} />
|
||||
</>
|
||||
)}
|
||||
@@ -214,14 +259,17 @@ function SegmentedControl<Value extends number | string>(props: {
|
||||
function ChartCard(props: {
|
||||
readonly merged: MergedUsage;
|
||||
readonly days: readonly string[];
|
||||
readonly daily: readonly DailyTotals[];
|
||||
readonly metric: UsageChartMetric;
|
||||
readonly onMetricChange: (metric: UsageChartMetric) => void;
|
||||
readonly sinceDay: string;
|
||||
readonly untilDay: string;
|
||||
readonly isPast24Hours: boolean;
|
||||
readonly timeZone: string;
|
||||
}) {
|
||||
const { merged, metric } = props;
|
||||
const colors = useProviderColors();
|
||||
const hasActivity = merged.daily.some((day) => day.totalTokens > 0);
|
||||
const hasActivity = props.daily.some((period) => period.totalTokens > 0);
|
||||
|
||||
return (
|
||||
<View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
|
||||
@@ -245,7 +293,7 @@ function ChartCard(props: {
|
||||
{hasActivity ? (
|
||||
<UsageDailyChart
|
||||
days={props.days}
|
||||
daily={merged.daily}
|
||||
daily={props.daily}
|
||||
metric={metric}
|
||||
height={CHART_HEIGHT}
|
||||
/>
|
||||
@@ -256,7 +304,11 @@ function ChartCard(props: {
|
||||
)}
|
||||
|
||||
<View className="flex-row items-center justify-between">
|
||||
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.sinceDay)}</Text>
|
||||
<Text className="text-xs text-foreground-tertiary">
|
||||
{props.isPast24Hours
|
||||
? formatHourShort(props.days[0] ?? "", props.timeZone)
|
||||
: formatDayShort(props.sinceDay)}
|
||||
</Text>
|
||||
<View className="flex-row items-center gap-4">
|
||||
{merged.providers.map((provider) => (
|
||||
<View key={provider.provider} className="flex-row items-center gap-1.5">
|
||||
@@ -270,7 +322,11 @@ function ChartCard(props: {
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
<Text className="text-xs text-foreground-tertiary">{formatDayShort(props.untilDay)}</Text>
|
||||
<Text className="text-xs text-foreground-tertiary">
|
||||
{props.isPast24Hours
|
||||
? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
|
||||
: formatDayShort(props.untilDay)}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
@@ -364,10 +420,12 @@ function ProviderSection(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function TotalsSection(props: { readonly merged: MergedUsage }) {
|
||||
function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
|
||||
const { merged } = props;
|
||||
const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;
|
||||
const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;
|
||||
const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
|
||||
(period) => period.totalTokens > 0,
|
||||
).length;
|
||||
const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
|
||||
const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
|
||||
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
|
||||
|
||||
@@ -377,7 +435,7 @@ function TotalsSection(props: { readonly merged: MergedUsage }) {
|
||||
<MetricCell
|
||||
label="Processed tokens"
|
||||
value={formatTokens(merged.totalTokens)}
|
||||
detail={`${formatTokens(dailyAverage)} per active day`}
|
||||
detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
|
||||
/>
|
||||
<MetricCell
|
||||
label="Cache savings"
|
||||
|
||||
@@ -12,12 +12,107 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
isPendingUserInputOptionSelected,
|
||||
setPendingUserInputCustomAnswer,
|
||||
togglePendingUserInputOptionSelection,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
|
||||
const singleSelectQuestion = {
|
||||
id: "runtime",
|
||||
header: "Runtime",
|
||||
question: "Which runtime should be used?",
|
||||
options: [
|
||||
{ label: "Go", description: "One binary" },
|
||||
{ label: "Node.js", description: "Reuse TypeScript" },
|
||||
],
|
||||
multiSelect: false,
|
||||
} as const;
|
||||
|
||||
const multiSelectQuestion = {
|
||||
id: "scope",
|
||||
header: "Scope",
|
||||
question: "Which data should be collected?",
|
||||
options: [
|
||||
{ label: "Orders", description: "Receipts" },
|
||||
{ label: "Listings", description: "Inventory" },
|
||||
],
|
||||
multiSelect: true,
|
||||
} as const;
|
||||
|
||||
describe("pending user input answers", () => {
|
||||
it("replaces single-select options and toggles multi-select options", () => {
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(
|
||||
singleSelectQuestion,
|
||||
{ selectedOptionLabels: ["Go"] },
|
||||
"Node.js",
|
||||
),
|
||||
).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] });
|
||||
|
||||
const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");
|
||||
const ordersAndListings = togglePendingUserInputOptionSelection(
|
||||
multiSelectQuestion,
|
||||
orders,
|
||||
"Listings",
|
||||
);
|
||||
expect(ordersAndListings).toEqual({
|
||||
customAnswer: "",
|
||||
selectedOptionLabels: ["Orders", "Listings"],
|
||||
});
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),
|
||||
).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] });
|
||||
|
||||
const paddedOrders = togglePendingUserInputOptionSelection(
|
||||
multiSelectQuestion,
|
||||
undefined,
|
||||
" Orders ",
|
||||
);
|
||||
expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] });
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "),
|
||||
).toEqual({ customAnswer: "" });
|
||||
});
|
||||
|
||||
it("builds array answers for multi-select questions", () => {
|
||||
expect(
|
||||
buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {
|
||||
runtime: { selectedOptionLabels: ["Go"] },
|
||||
scope: { selectedOptionLabels: ["Orders", "Listings"] },
|
||||
}),
|
||||
).toEqual({
|
||||
runtime: "Go",
|
||||
scope: ["Orders", "Listings"],
|
||||
});
|
||||
});
|
||||
|
||||
it("clears selected options while a custom answer is active", () => {
|
||||
expect(
|
||||
setPendingUserInputCustomAnswer(
|
||||
{ selectedOptionLabels: ["Orders", "Listings"] },
|
||||
"Orders first",
|
||||
),
|
||||
).toEqual({ customAnswer: "Orders first" });
|
||||
});
|
||||
|
||||
it("matches selected chips against normalized option labels", () => {
|
||||
expect(
|
||||
isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isPendingUserInputOptionSelected(
|
||||
{ selectedOptionLabels: ["Orders"], customAnswer: "Orders first" },
|
||||
" Orders ",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface PendingUserInput {
|
||||
}
|
||||
|
||||
export interface PendingUserInputDraftAnswer {
|
||||
readonly selectedOptionLabel?: string;
|
||||
readonly selectedOptionLabels?: ReadonlyArray<string>;
|
||||
readonly customAnswer?: string;
|
||||
}
|
||||
|
||||
@@ -227,14 +227,32 @@ function normalizeDraftAnswer(value: string | undefined): string | null {
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedOptionLabels(
|
||||
value: ReadonlyArray<string> | undefined,
|
||||
): ReadonlyArray<string> {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Array.from(
|
||||
new Set(value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)),
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePendingUserInputAnswer(
|
||||
question: UserInputQuestion,
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
): string | null {
|
||||
): string | ReadonlyArray<string> | null {
|
||||
const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
|
||||
if (customAnswer) {
|
||||
return customAnswer;
|
||||
}
|
||||
return normalizeDraftAnswer(draft?.selectedOptionLabel);
|
||||
|
||||
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
|
||||
if (question.multiSelect) {
|
||||
return selectedOptionLabels.length > 0 ? selectedOptionLabels : null;
|
||||
}
|
||||
return selectedOptionLabels[0] ?? null;
|
||||
}
|
||||
|
||||
/** Codex children settle via task.updated (idle/failed/interrupted), never
|
||||
@@ -554,6 +572,8 @@ function toolDetailTextLooksLikeFailure(text: string): boolean {
|
||||
normalized.includes("command not found") ||
|
||||
(normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
|
||||
(normalized.includes("is not recognized") && normalized.includes("the term '")) ||
|
||||
normalized.includes("is not recognized as the name of a cmdlet") ||
|
||||
normalized.includes("a parameter cannot be found that matches parameter name") ||
|
||||
/<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
|
||||
/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
|
||||
/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
|
||||
@@ -1426,22 +1446,62 @@ export function setPendingUserInputCustomAnswer(
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
customAnswer: string,
|
||||
): PendingUserInputDraftAnswer {
|
||||
const selectedOptionLabel =
|
||||
customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
|
||||
const selectedOptionLabels =
|
||||
customAnswer.trim().length > 0
|
||||
? undefined
|
||||
: normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
|
||||
return {
|
||||
customAnswer,
|
||||
...(selectedOptionLabel ? { selectedOptionLabel } : {}),
|
||||
...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function isPendingUserInputOptionSelected(
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
optionLabel: string,
|
||||
): boolean {
|
||||
if (normalizeDraftAnswer(draft?.customAnswer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return normalizeSelectedOptionLabels(draft?.selectedOptionLabels).includes(optionLabel.trim());
|
||||
}
|
||||
|
||||
export function togglePendingUserInputOptionSelection(
|
||||
question: UserInputQuestion,
|
||||
draft: PendingUserInputDraftAnswer | undefined,
|
||||
optionLabel: string,
|
||||
): PendingUserInputDraftAnswer {
|
||||
const normalizedOptionLabel = optionLabel.trim();
|
||||
|
||||
if (question.multiSelect) {
|
||||
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
|
||||
const nextSelectedOptionLabels = selectedOptionLabels.includes(normalizedOptionLabel)
|
||||
? selectedOptionLabels.filter((label) => label !== normalizedOptionLabel)
|
||||
: [...selectedOptionLabels, normalizedOptionLabel];
|
||||
|
||||
return {
|
||||
customAnswer: "",
|
||||
...(nextSelectedOptionLabels.length > 0
|
||||
? { selectedOptionLabels: nextSelectedOptionLabels }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
customAnswer: "",
|
||||
selectedOptionLabels: [normalizedOptionLabel],
|
||||
};
|
||||
}
|
||||
|
||||
export function buildPendingUserInputAnswers(
|
||||
questions: ReadonlyArray<UserInputQuestion>,
|
||||
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
|
||||
): Record<string, string> | null {
|
||||
const answers: Record<string, string> = {};
|
||||
): Record<string, string | ReadonlyArray<string>> | null {
|
||||
const answers: Record<string, string | ReadonlyArray<string>> = {};
|
||||
|
||||
for (const question of questions) {
|
||||
const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
|
||||
const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
|
||||
if (!answer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { hasWideMarkdownBlock } from "./wideMarkdownBlocks";
|
||||
|
||||
describe("hasWideMarkdownBlock", () => {
|
||||
it("ignores prose, inline code, and emphasis", () => {
|
||||
expect(hasWideMarkdownBlock("just a message")).toBe(false);
|
||||
expect(hasWideMarkdownBlock("I found it in `secteurs_intervention` earlier")).toBe(false);
|
||||
expect(hasWideMarkdownBlock("a | b in a sentence")).toBe(false);
|
||||
expect(hasWideMarkdownBlock("an em dash — and a rule\n\n---\n")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects fenced code blocks", () => {
|
||||
expect(hasWideMarkdownBlock("before\n```\ncode\n```\nafter")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("before\n```ts\ncode\n```")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("before\n~~~\ncode\n~~~")).toBe(true);
|
||||
expect(hasWideMarkdownBlock(" ```\ncode\n```")).toBe(true);
|
||||
});
|
||||
|
||||
it("detects GFM tables", () => {
|
||||
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |\n| 1 | 2 |")).toBe(true);
|
||||
expect(hasWideMarkdownBlock("a | b\n:-- | --:\n1 | 2")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Detects markdown that the JS renderer draws as a standalone block View
|
||||
* wrapping a horizontal ScrollView — fenced code blocks and GFM tables.
|
||||
*
|
||||
* Those blocks report an intrinsic width equal to their widest line, which is
|
||||
* effectively unbounded. A user bubble sizes itself from its content
|
||||
* (`maxWidth` with no `width`), so Android lays the bubble's children out
|
||||
* during the unclamped intrinsic pass — where the surrounding paragraphs
|
||||
* collapse to a single line — and never repositions them once the width is
|
||||
* clamped back to `maxWidth`. The result is siblings drawn on top of each
|
||||
* other inside an over-tall bubble. Pinning the bubble's width removes the
|
||||
* intrinsic pass entirely, which is the same reason review-comment bubbles
|
||||
* already carry an explicit width.
|
||||
*
|
||||
* Indented (four-space) code blocks are deliberately not detected: they are
|
||||
* vanishingly rare in chat input and the check would fire on ordinary nested
|
||||
* list continuations.
|
||||
*/
|
||||
|
||||
const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
|
||||
|
||||
function isTableDelimiterRow(line: string): boolean {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.includes("|") || !trimmed.includes("-")) {
|
||||
return false;
|
||||
}
|
||||
return /^[|\-: \t]+$/.test(trimmed);
|
||||
}
|
||||
|
||||
export function hasWideMarkdownBlock(text: string): boolean {
|
||||
if (FENCED_CODE_BLOCK.test(text)) {
|
||||
return true;
|
||||
}
|
||||
if (!text.includes("|")) {
|
||||
return false;
|
||||
}
|
||||
return text.split("\n").some(isTableDelimiterRow);
|
||||
}
|
||||
@@ -115,9 +115,19 @@ export function useUsage(
|
||||
sinceDay: input.sinceDay,
|
||||
untilDay: input.untilDay,
|
||||
timeZone: input.timeZone,
|
||||
resolution: input.resolution,
|
||||
sinceTime: input.sinceTime,
|
||||
untilTime: input.untilTime,
|
||||
},
|
||||
}),
|
||||
[input.sinceDay, input.untilDay, input.timeZone],
|
||||
[
|
||||
input.sinceDay,
|
||||
input.untilDay,
|
||||
input.timeZone,
|
||||
input.resolution,
|
||||
input.sinceTime,
|
||||
input.untilTime,
|
||||
],
|
||||
);
|
||||
const atom = usageByWindowAtom(key);
|
||||
const value = useAtomValue(atom);
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
@@ -12,6 +16,7 @@ import {
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
togglePendingUserInputOptionSelection,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -23,15 +28,21 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
|
||||
Record<string, Record<string, PendingUserInputDraftAnswer>>
|
||||
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
|
||||
|
||||
function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
|
||||
function setUserInputDraftOption(
|
||||
requestKey: string,
|
||||
question: UserInputQuestion,
|
||||
label: string,
|
||||
): void {
|
||||
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
|
||||
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
|
||||
...current,
|
||||
[requestKey]: {
|
||||
...current[requestKey],
|
||||
[questionId]: {
|
||||
selectedOptionLabel: label,
|
||||
},
|
||||
[question.id]: togglePendingUserInputOptionSelection(
|
||||
question,
|
||||
current[requestKey]?.[question.id],
|
||||
label,
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -97,13 +108,13 @@ export function useSelectedThreadRequests() {
|
||||
: null;
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, label: string) => {
|
||||
(requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
|
||||
setUserInputDraftOption(requestKey, questionId, label);
|
||||
setUserInputDraftOption(requestKey, question, label);
|
||||
},
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.32",
|
||||
"version": "0.0.33",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -37,6 +37,17 @@ describe("RPC authorization scopes", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.cloudInstallRelayClient)).toBe(AuthRelayWriteScope);
|
||||
});
|
||||
|
||||
it("reads the reviewer menu under the same scope as the pull request it belongs to", () => {
|
||||
// The candidate list is a read like the detail beside it, and asking somebody for a review is
|
||||
// a write like every other pull request operation.
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsReviewerCandidates)).toBe(
|
||||
requiredScopeForRpcMethod(WS_METHODS.pullRequestsDetail),
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.pullRequestsRequestReviewers)).toBe(
|
||||
requiredScopeForRpcMethod(WS_METHODS.pullRequestsComment),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects unknown RPC method names", () => {
|
||||
for (const method of ["server.notRegistered", "toString", "constructor"]) {
|
||||
expect(() => requiredScopeForRpcMethod(method)).toThrow(
|
||||
|
||||
@@ -52,6 +52,23 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.cloudGetRelayClientStatus]: AuthRelayReadScope,
|
||||
[WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,
|
||||
[WS_METHODS.pullRequestsList]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsListStats]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsDetail]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsRunAction]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.pullRequestsComment]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.pullRequestsSubmitReview]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.pullRequestsReplyToThread]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.pullRequestsSetThreadResolution]: AuthOrchestrationOperateScope,
|
||||
// Read scope like the reads it un-caches: refreshing is part of reading, and a read-only
|
||||
// client pressing refresh must not be told it may not look again.
|
||||
[WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,
|
||||
// The candidate list is a read like the detail beside it; asking somebody for a review is a
|
||||
// write like every other one.
|
||||
[WS_METHODS.pullRequestsReviewerCandidates]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.pullRequestsRequestReviewers]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.sourceControlCloneRepository]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,
|
||||
|
||||
@@ -81,6 +81,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -31,6 +31,8 @@ const successfulRunner = (fs: FileSystem.FileSystem, path: Path.Path) =>
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -45,6 +45,8 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
};
|
||||
}
|
||||
order.push("preflight");
|
||||
@@ -64,6 +66,8 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -69,6 +69,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
|
||||
expect(first.environmentId).toBe(second.environmentId);
|
||||
expect(second.capabilities.repositoryIdentity).toBe(true);
|
||||
expect(second.capabilities.connectionProbe).toBe(true);
|
||||
expect(second.capabilities.pullRequests).toBe(true);
|
||||
expect(second.capabilities.threadTitleRegeneration).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -143,6 +143,7 @@ export const make = Effect.gen(function* () {
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
connectionProbe: true,
|
||||
pullRequests: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
threadPinning: true,
|
||||
|
||||
@@ -81,6 +81,8 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -120,6 +122,8 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -223,6 +227,8 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -264,6 +270,8 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -3341,7 +3341,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("launches setup only when creating a new PR worktree", () =>
|
||||
it.effect("launches setup when creating a new PR worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -3614,6 +3614,547 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
NodeFS.realpathSync.native(worktreePath),
|
||||
);
|
||||
expect(result.branch).toBe("feature/pr-existing-worktree");
|
||||
// Nothing to fetch from, so the checkout keeps the commit it had and setup stays out of a
|
||||
// worktree another thread may be sitting in.
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
expect(result.isOnPullRequestHead).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refreshes a reused PR worktree onto the updated pull request head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-reused-stale"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "stale.txt"), "stale\n");
|
||||
yield* runGit(repoDir, ["add", "stale.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Reused stale PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-reused-stale"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-reused-stale-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-stale"]);
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "author-push", "origin/feature/pr-reused-stale"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "authored.txt"), "authored\n");
|
||||
yield* runGit(repoDir, ["add", "authored.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "New PR head commit"]);
|
||||
yield* runGit(repoDir, ["push", "origin", "author-push:feature/pr-reused-stale"]);
|
||||
const updatedHead = (yield* runGit(repoDir, ["rev-parse", "author-push"])).stdout.trim();
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 84,
|
||||
title: "Reused stale PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/84",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-reused-stale",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "84",
|
||||
mode: "worktree",
|
||||
});
|
||||
|
||||
expect(result.worktreePath && NodeFS.realpathSync.native(result.worktreePath)).toBe(
|
||||
NodeFS.realpathSync.native(worktreePath),
|
||||
);
|
||||
expect(result.branch).toBe("feature/pr-reused-stale");
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(updatedHead);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("runs the setup script when a reused PR worktree moves onto the new head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-reused-setup"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "reused-setup.txt"), "reused setup\n");
|
||||
yield* runGit(repoDir, ["add", "reused-setup.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Reused setup PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-reused-setup"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-reused-setup-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-setup"]);
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "setup-author-push", "feature/pr-reused-setup"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "reused-setup.txt"), "reused setup again\n");
|
||||
yield* runGit(repoDir, ["add", "reused-setup.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "New reused setup head"]);
|
||||
yield* runGit(repoDir, ["push", "origin", "setup-author-push:feature/pr-reused-setup"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 85,
|
||||
title: "Reused setup PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/85",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-reused-setup",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "85",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-reused-setup"),
|
||||
});
|
||||
|
||||
expect(setupCalls).toHaveLength(1);
|
||||
expect(setupCalls[0]).toEqual({
|
||||
threadId: "thread-pr-reused-setup",
|
||||
projectCwd: repoDir,
|
||||
worktreePath: result.worktreePath as string,
|
||||
});
|
||||
expect(result.isOnPullRequestHead).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("leaves the setup script alone when a reused PR worktree is already on the head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-reused-current"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "reused-current.txt"), "reused current\n");
|
||||
yield* runGit(repoDir, ["add", "reused-current.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Reused current PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-reused-current"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-reused-current-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-current"]);
|
||||
const currentHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 95,
|
||||
title: "Reused current PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/95",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-reused-current",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "95",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-reused-current"),
|
||||
});
|
||||
|
||||
expect(result.isOnPullRequestHead).toBe(true);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(currentHead);
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resets a clean reused PR worktree onto a force-pushed pull request head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-force-pushed"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "force-pushed.txt"), "first\n");
|
||||
yield* runGit(repoDir, ["add", "force-pushed.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Force-pushed PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-force-pushed"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-force-pushed-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-force-pushed"]);
|
||||
const staleHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "author-rewrite", "feature/pr-force-pushed"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "force-pushed.txt"), "rewritten\n");
|
||||
yield* runGit(repoDir, ["add", "force-pushed.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "--amend", "-m", "Rewritten PR head"]);
|
||||
yield* runGit(repoDir, [
|
||||
"push",
|
||||
"--force",
|
||||
"origin",
|
||||
"author-rewrite:feature/pr-force-pushed",
|
||||
]);
|
||||
const rewrittenHead = (yield* runGit(repoDir, ["rev-parse", "author-rewrite"])).stdout.trim();
|
||||
// Pushing from this clone also advanced its remote-tracking ref. A head rewritten by the
|
||||
// author leaves that ref behind, which is the state a reused worktree is really opened in.
|
||||
yield* runGit(repoDir, [
|
||||
"update-ref",
|
||||
"refs/remotes/origin/feature/pr-force-pushed",
|
||||
staleHead,
|
||||
]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 86,
|
||||
title: "Force-pushed PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/86",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-force-pushed",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "86",
|
||||
mode: "worktree",
|
||||
});
|
||||
|
||||
expect(result.worktreePath && NodeFS.realpathSync.native(result.worktreePath)).toBe(
|
||||
NodeFS.realpathSync.native(worktreePath),
|
||||
);
|
||||
expect(result.isOnPullRequestHead).toBe(true);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(
|
||||
rewrittenHead,
|
||||
);
|
||||
expect(NodeFS.readFileSync(NodePath.join(worktreePath, "force-pushed.txt"), "utf8")).toBe(
|
||||
"rewritten\n",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a reused PR worktree that carries its own commit off the rewritten head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-commit"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "local-commit.txt"), "first\n");
|
||||
yield* runGit(repoDir, ["add", "local-commit.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Local commit PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-commit"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-local-commit-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-local-commit"]);
|
||||
const upstreamHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "local-commit-rewrite", "feature/pr-local-commit"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "local-commit.txt"), "rewritten\n");
|
||||
yield* runGit(repoDir, ["add", "local-commit.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "--amend", "-m", "Rewritten local commit head"]);
|
||||
yield* runGit(repoDir, [
|
||||
"push",
|
||||
"--force",
|
||||
"origin",
|
||||
"local-commit-rewrite:feature/pr-local-commit",
|
||||
]);
|
||||
yield* runGit(repoDir, [
|
||||
"update-ref",
|
||||
"refs/remotes/origin/feature/pr-local-commit",
|
||||
upstreamHead,
|
||||
]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
// The work that must survive: a commit made in the worktree, on top of the stale head.
|
||||
NodeFS.writeFileSync(NodePath.join(worktreePath, "thread-work.txt"), "thread work\n");
|
||||
yield* runGit(worktreePath, ["add", "thread-work.txt"]);
|
||||
yield* runGit(worktreePath, ["commit", "-m", "Work done in the reused worktree"]);
|
||||
const worktreeHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 87,
|
||||
title: "Local commit PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/87",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-local-commit",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "87",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-local-commit"),
|
||||
});
|
||||
|
||||
expect(result.isOnPullRequestHead).toBe(false);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(worktreeHead);
|
||||
expect(NodeFS.existsSync(NodePath.join(worktreePath, "thread-work.txt"))).toBe(true);
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a dirty reused PR worktree off the rewritten pull request head", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-dirty-worktree"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "dirty.txt"), "first\n");
|
||||
yield* runGit(repoDir, ["add", "dirty.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Dirty worktree PR branch"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-dirty-worktree"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
const worktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`pr-dirty-worktree-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-dirty-worktree"]);
|
||||
const staleHead = (yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim();
|
||||
|
||||
yield* runGit(repoDir, ["checkout", "-b", "dirty-rewrite", "feature/pr-dirty-worktree"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "dirty.txt"), "rewritten\n");
|
||||
yield* runGit(repoDir, ["add", "dirty.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "--amend", "-m", "Rewritten dirty head"]);
|
||||
yield* runGit(repoDir, [
|
||||
"push",
|
||||
"--force",
|
||||
"origin",
|
||||
"dirty-rewrite:feature/pr-dirty-worktree",
|
||||
]);
|
||||
yield* runGit(repoDir, [
|
||||
"update-ref",
|
||||
"refs/remotes/origin/feature/pr-dirty-worktree",
|
||||
staleHead,
|
||||
]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
NodeFS.writeFileSync(NodePath.join(worktreePath, "dirty.txt"), "uncommitted edit\n");
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 89,
|
||||
title: "Dirty worktree PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/89",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-dirty-worktree",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "89",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-dirty-worktree"),
|
||||
});
|
||||
|
||||
expect(result.isOnPullRequestHead).toBe(false);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(staleHead);
|
||||
expect(NodeFS.readFileSync(NodePath.join(worktreePath, "dirty.txt"), "utf8")).toBe(
|
||||
"uncommitted edit\n",
|
||||
);
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refreshes a reused PR worktree that has no upstream from the pull request ref", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-ref-only"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "ref-only.txt"), "ref only\n");
|
||||
yield* runGit(repoDir, ["add", "ref-only.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Pull ref only PR branch"]);
|
||||
// The head lives at refs/pull/90/head and nowhere else, so nothing can be tracked.
|
||||
yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/90/head"]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
yield* runGit(repoDir, ["branch", "-D", "feature/pr-ref-only"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 90,
|
||||
title: "Pull ref only PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/90",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-ref-only",
|
||||
state: "open",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const created = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "90",
|
||||
mode: "worktree",
|
||||
});
|
||||
const worktreePath = created.worktreePath as string;
|
||||
expect(
|
||||
(yield* runGit(worktreePath, ["rev-parse", "--abbrev-ref", "@{upstream}"], true)).exitCode,
|
||||
).not.toBe(0);
|
||||
|
||||
yield* runGit(repoDir, ["fetch", "origin", "refs/pull/90/head"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "ref-only-author", "FETCH_HEAD"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "ref-only.txt"), "ref only again\n");
|
||||
yield* runGit(repoDir, ["add", "ref-only.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "New pull ref head"]);
|
||||
yield* runGit(repoDir, ["push", "origin", "ref-only-author:refs/pull/90/head"]);
|
||||
const updatedHead = (yield* runGit(repoDir, ["rev-parse", "ref-only-author"])).stdout.trim();
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "90",
|
||||
mode: "worktree",
|
||||
});
|
||||
|
||||
expect(result.worktreePath && NodeFS.realpathSync.native(result.worktreePath)).toBe(
|
||||
NodeFS.realpathSync.native(worktreePath),
|
||||
);
|
||||
expect(result.isOnPullRequestHead).toBe(true);
|
||||
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(updatedHead);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("never moves an unrelated local branch that shares the fork head branch name", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const originDir = yield* createBareRemote();
|
||||
const forkDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "fork-main-collision"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "contributor.txt"), "contributor\n");
|
||||
yield* runGit(repoDir, ["add", "contributor.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Contributor commit on the fork main"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-collision:main"]);
|
||||
// The user's own main, checked out in its own worktree and behind the fork's main: a
|
||||
// fast-forward would land the contributor's commits in it.
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/root-work", "main"]);
|
||||
const mainWorktreePath = NodePath.join(
|
||||
repoDir,
|
||||
"..",
|
||||
`local-main-${NodePath.basename(repoDir)}`,
|
||||
);
|
||||
yield* runGit(repoDir, ["worktree", "add", mainWorktreePath, "main"]);
|
||||
const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();
|
||||
|
||||
const setupCalls: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput[] = [];
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
pullRequest: {
|
||||
number: 94,
|
||||
title: "Fork main collision PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/94",
|
||||
baseRefName: "main",
|
||||
headRefName: "main",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
},
|
||||
repositoryCloneUrls: {
|
||||
"octocat/codething-mvp": {
|
||||
url: forkDir,
|
||||
sshUrl: forkDir,
|
||||
},
|
||||
},
|
||||
},
|
||||
setupScriptRunner: {
|
||||
runForThread: (setupInput) =>
|
||||
Effect.sync(() => {
|
||||
setupCalls.push(setupInput);
|
||||
return { status: "no-script" as const };
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* preparePullRequestThread(manager, {
|
||||
cwd: repoDir,
|
||||
reference: "94",
|
||||
mode: "worktree",
|
||||
threadId: asThreadId("thread-pr-fork-main-collision"),
|
||||
});
|
||||
|
||||
expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore);
|
||||
expect((yield* runGit(mainWorktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(
|
||||
localMainBefore,
|
||||
);
|
||||
expect(NodeFS.existsSync(NodePath.join(mainWorktreePath, "contributor.txt"))).toBe(false);
|
||||
expect(result.isOnPullRequestHead).toBe(false);
|
||||
expect(setupCalls).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1849,6 +1849,7 @@ export const make = Effect.gen(function* () {
|
||||
pullRequest,
|
||||
branch: details.branch ?? pullRequest.headBranch,
|
||||
worktreePath: null,
|
||||
isOnPullRequestHead: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1873,6 +1874,102 @@ export const make = Effect.gen(function* () {
|
||||
const localPullRequestBranch =
|
||||
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
|
||||
|
||||
// Git refuses to move a branch that is checked out in a worktree, so the
|
||||
// reuse paths cannot go through materializePullRequestHeadBranch and instead
|
||||
// advance the checkout from inside the worktree. A worktree that cannot be
|
||||
// moved (no reachable head, local commits, dirty tree) is still handed
|
||||
// back, because stranding the thread is worse than reporting the staleness.
|
||||
const reuseExistingWorktree = Effect.fn("reuseExistingWorktree")(function* (
|
||||
worktreePath: string,
|
||||
checkedOutBranch: string,
|
||||
) {
|
||||
if (checkedOutBranch !== localPullRequestBranch) {
|
||||
// findLocalHeadBranch also accepts a branch that merely shares the head's bare name —
|
||||
// a fork PR opened from "main" matches the user's own local main. That checkout is
|
||||
// somebody else's work, so it keeps its tracking config and nothing else.
|
||||
yield* ensureExistingWorktreeUpstream(worktreePath);
|
||||
return {
|
||||
pullRequest,
|
||||
branch: localPullRequestBranch,
|
||||
worktreePath,
|
||||
isOnPullRequestHead: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Read before ensureExistingWorktreeUpstream: it force-updates the remote-tracking ref,
|
||||
// and once that has jumped to a rewritten head there is no way left to tell a checkout
|
||||
// that holds nothing of its own from one carrying local commits.
|
||||
const upstreamCommitBeforeFetch = yield* gitCore
|
||||
.resolveCommit({ cwd: worktreePath, revision: "@{upstream}" })
|
||||
.pipe(
|
||||
Effect.map((resolved) => resolved.commitSha),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
|
||||
yield* ensureExistingWorktreeUpstream(worktreePath);
|
||||
|
||||
const refreshed = yield* gitCore
|
||||
// The pull request's own ref, because it is the only thing that certainly names its
|
||||
// head. The branch's upstream does not: configuring it is best-effort, so a branch cut
|
||||
// from `origin/main` whose head branch has since been deleted still resolves — and
|
||||
// following it would move the checkout onto main and call that the pull request.
|
||||
.fetchPullRequestHeadCommit({ cwd: worktreePath, prNumber: pullRequest.number })
|
||||
.pipe(
|
||||
// A host that publishes no `refs/pull/<n>/head` leaves the remote-tracking branch,
|
||||
// taken only where it is the head branch's own rather than whatever the checkout
|
||||
// happened to be cut from.
|
||||
Effect.catch(() =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* gitCore.statusDetails(worktreePath);
|
||||
if (
|
||||
details.upstreamRef === null ||
|
||||
!details.upstreamRef.endsWith(`/${pullRequest.headBranch}`)
|
||||
) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "preparePullRequestThread",
|
||||
cwd: worktreePath,
|
||||
detail: "The pull request head could not be resolved for this checkout.",
|
||||
});
|
||||
}
|
||||
return yield* gitCore.resolveCommit({
|
||||
cwd: worktreePath,
|
||||
revision: details.upstreamRef,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((target) =>
|
||||
gitCore.refreshCheckedOutBranch({
|
||||
cwd: worktreePath,
|
||||
targetCommit: target.commitSha,
|
||||
resetWhenHeadCommit: upstreamCommitBeforeFetch,
|
||||
}),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
"GitManager.preparePullRequestThread reused worktree refresh failed",
|
||||
{
|
||||
worktreePath,
|
||||
localBranch: localPullRequestBranch,
|
||||
cause: error,
|
||||
},
|
||||
).pipe(Effect.as({ moved: false, onTarget: false })),
|
||||
),
|
||||
);
|
||||
|
||||
// Only when the checkout actually moved: another thread may be running in this worktree,
|
||||
// and re-running the setup script under it buys nothing when the code did not change.
|
||||
if (refreshed.moved) {
|
||||
yield* maybeRunSetupScript(worktreePath);
|
||||
}
|
||||
|
||||
return {
|
||||
pullRequest,
|
||||
branch: localPullRequestBranch,
|
||||
worktreePath,
|
||||
isOnPullRequestHead: refreshed.onTarget,
|
||||
};
|
||||
});
|
||||
|
||||
const findLocalHeadBranch = Effect.fn("findLocalHeadBranch")(function* (cwd: string) {
|
||||
const result = yield* gitCore.listRefs({ cwd, refresh: true });
|
||||
const localBranch = result.refs.find(
|
||||
@@ -1907,12 +2004,10 @@ export const make = Effect.gen(function* () {
|
||||
existingBranchBeforeFetch?.worktreePath &&
|
||||
existingBranchBeforeFetchPath !== rootWorktreePath
|
||||
) {
|
||||
yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath);
|
||||
return {
|
||||
pullRequest,
|
||||
branch: localPullRequestBranch,
|
||||
worktreePath: existingBranchBeforeFetch.worktreePath,
|
||||
};
|
||||
return yield* reuseExistingWorktree(
|
||||
existingBranchBeforeFetch.worktreePath,
|
||||
existingBranchBeforeFetch.name,
|
||||
);
|
||||
}
|
||||
if (existingBranchBeforeFetchPath === rootWorktreePath) {
|
||||
return yield* new GitManagerError({
|
||||
@@ -1937,12 +2032,10 @@ export const make = Effect.gen(function* () {
|
||||
existingBranchAfterFetch?.worktreePath &&
|
||||
existingBranchAfterFetchPath !== rootWorktreePath
|
||||
) {
|
||||
yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath);
|
||||
return {
|
||||
pullRequest,
|
||||
branch: localPullRequestBranch,
|
||||
worktreePath: existingBranchAfterFetch.worktreePath,
|
||||
};
|
||||
return yield* reuseExistingWorktree(
|
||||
existingBranchAfterFetch.worktreePath,
|
||||
existingBranchAfterFetch.name,
|
||||
);
|
||||
}
|
||||
if (existingBranchAfterFetchPath === rootWorktreePath) {
|
||||
return yield* new GitManagerError({
|
||||
@@ -1965,6 +2058,7 @@ export const make = Effect.gen(function* () {
|
||||
pullRequest,
|
||||
branch: worktree.worktree.refName,
|
||||
worktreePath: worktree.worktree.path,
|
||||
isOnPullRequestHead: true,
|
||||
};
|
||||
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { describe } from "vite-plus/test";
|
||||
|
||||
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
import { assetResponseHeaders, isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
|
||||
|
||||
describe("http dev routing", () => {
|
||||
it("treats localhost and loopback addresses as local", () => {
|
||||
@@ -26,3 +26,22 @@ describe("http dev routing", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assetResponseHeaders", () => {
|
||||
it("sandboxes SVG assets", () => {
|
||||
expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
|
||||
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty(
|
||||
"Content-Security-Policy",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not apply document policy to raster images", () => {
|
||||
expect(assetResponseHeaders("/attachments/user-image.png")).toEqual({
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
});
|
||||
});
|
||||
+13
-4
@@ -43,6 +43,18 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
|
||||
const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
|
||||
|
||||
export function assetResponseHeaders(filePath: string): Record<string, string> {
|
||||
return {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
...(filePath.toLowerCase().endsWith(".svg")
|
||||
? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
|
||||
global: true,
|
||||
});
|
||||
@@ -207,10 +219,7 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
}
|
||||
return yield* HttpServerResponse.file(asset.path, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": "private, max-age=3600",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
headers: assetResponseHeaders(asset.path),
|
||||
}).pipe(
|
||||
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
||||
);
|
||||
|
||||
@@ -13,6 +13,7 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import {
|
||||
collectUint8StreamText,
|
||||
decodeUtf8,
|
||||
type CollectedUint8StreamText,
|
||||
} from "./stream/collectUint8StreamText.ts";
|
||||
|
||||
@@ -41,6 +42,8 @@ export interface ProcessRunOutput {
|
||||
readonly timedOut: boolean;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
readonly stdoutInvalidUtf8: boolean;
|
||||
readonly stderrInvalidUtf8: boolean;
|
||||
}
|
||||
|
||||
const ProcessInvocationFields = {
|
||||
@@ -238,7 +241,7 @@ const collectText = Effect.fn("processRunner.collectText")(function* (input: {
|
||||
),
|
||||
Effect.map(
|
||||
(state): CollectedUint8StreamText => ({
|
||||
text: Buffer.concat(state.chunks, state.bytes).toString("utf8"),
|
||||
...decodeUtf8(Buffer.concat(state.chunks, state.bytes)),
|
||||
bytes: state.bytes,
|
||||
truncated: false,
|
||||
}),
|
||||
@@ -268,6 +271,8 @@ function finalizeRunProcess<R>(
|
||||
timedOut: true,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
} satisfies ProcessRunOutput);
|
||||
}
|
||||
return Effect.fail(
|
||||
@@ -394,6 +399,8 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
|
||||
timedOut: false,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
stdoutInvalidUtf8: stdout.invalidUtf8,
|
||||
stderrInvalidUtf8: stderr.invalidUtf8,
|
||||
} satisfies ProcessRunOutput;
|
||||
});
|
||||
|
||||
|
||||
@@ -125,6 +125,31 @@ describe("parseModelsCliOutput", () => {
|
||||
NodeAssert.ok(model.variants);
|
||||
NodeAssert.equal(model.variants!["medium"] !== undefined, true);
|
||||
});
|
||||
|
||||
it("keeps a model whose JSON body has a slash and no interior whitespace", () => {
|
||||
// OpenRouter-style: the model id contains a `/` and no string value has a
|
||||
// space, so the JSON body line itself matches the slug regex. It must still
|
||||
// be treated as the body of the preceding slug, not a new slug.
|
||||
const stdout = [
|
||||
"openrouter/qwen/qwen3-coder",
|
||||
JSON.stringify({
|
||||
id: "qwen/qwen3-coder",
|
||||
providerID: "openrouter",
|
||||
name: "qwen3-coder",
|
||||
status: "active",
|
||||
}),
|
||||
].join("\n");
|
||||
|
||||
const result = parseModelsCliOutput(stdout);
|
||||
NodeAssert.equal(result.providers.size, 1);
|
||||
NodeAssert.deepEqual([...result.connected], ["openrouter"]);
|
||||
const provider = result.providers.get("openrouter")!;
|
||||
NodeAssert.ok(provider);
|
||||
const model = provider.models["qwen/qwen3-coder"]!;
|
||||
NodeAssert.ok(model);
|
||||
NodeAssert.equal(model.id, "qwen/qwen3-coder");
|
||||
NodeAssert.equal(model.providerID, "openrouter");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseAgentListCliOutput", () => {
|
||||
|
||||
@@ -216,7 +216,13 @@ export function parseModelsCliOutput(stdout: string): {
|
||||
};
|
||||
|
||||
for (const line of lines) {
|
||||
const slugMatch = SLUG_LINE_RE.exec(line);
|
||||
// A model's JSON body is a single `JSON.stringify` line starting with `{`,
|
||||
// while a provider/model slug is a bare `provider/model` header. Only the
|
||||
// latter can be a slug: without this guard a body line with no interior
|
||||
// whitespace and a `/` in one of its values (e.g. an OpenRouter model whose
|
||||
// `id` is `vendor/model`) matches SLUG_LINE_RE, so flushModel runs against
|
||||
// an empty body and the model is silently dropped.
|
||||
const slugMatch = line.trimStart().startsWith("{") ? null : SLUG_LINE_RE.exec(line);
|
||||
if (slugMatch) {
|
||||
flushModel();
|
||||
currentSlug = slugMatch[1]!;
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
import { afterEach, assert, expect, it, vi } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";
|
||||
import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
|
||||
import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
|
||||
|
||||
const mockedExecute = vi.fn<AzureDevOpsCli.AzureDevOpsCli["Service"]["execute"]>();
|
||||
|
||||
const layer = it.layer(
|
||||
AzureDevOpsPullRequestCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
|
||||
execute: mockedExecute,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function output(stdout: string) {
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
function pullRequestRows(
|
||||
count: number,
|
||||
firstNumber: number,
|
||||
): ReadonlyArray<Record<string, unknown>> {
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
pullRequestId: firstNumber + index,
|
||||
title: `Pull request ${firstNumber + index}`,
|
||||
status: "active",
|
||||
sourceRefName: "refs/heads/feat/page",
|
||||
targetRefName: "refs/heads/main",
|
||||
creationDate: "2026-07-01T00:00:00Z",
|
||||
repository: { name: "web", project: { name: "platform" } },
|
||||
url: `https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/${firstNumber + index}`,
|
||||
}));
|
||||
}
|
||||
|
||||
function pullRequests(count: number, firstNumber: number): string {
|
||||
return JSON.stringify(pullRequestRows(count, firstNumber));
|
||||
}
|
||||
|
||||
/** The arguments of the nth az invocation. */
|
||||
function argsOfCall(index: number): ReadonlyArray<string> {
|
||||
const call = mockedExecute.mock.calls[index];
|
||||
assert.isDefined(call);
|
||||
return call[0].args;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
mockedExecute.mockReset();
|
||||
});
|
||||
|
||||
layer("AzureDevOpsPullRequestCli.layer", (it) => {
|
||||
it.effect("asks for one row more than the page, to probe for a next page", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const batch = yield* cli.listPullRequests({
|
||||
cwd: "/w",
|
||||
repository: "web",
|
||||
state: "open",
|
||||
involvement: "all",
|
||||
viewer: "[email protected]",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.strictEqual(batch.items.length, 3);
|
||||
assert.isFalse(batch.truncated);
|
||||
expect(argsOfCall(0)).toEqual([
|
||||
"repos",
|
||||
"pr",
|
||||
"list",
|
||||
"--detect",
|
||||
"true",
|
||||
"--repository",
|
||||
"web",
|
||||
"--status",
|
||||
"active",
|
||||
"--include-links",
|
||||
"--top",
|
||||
"11",
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads the page unnarrowed when asked to search, having nothing to search with", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
|
||||
const provider = yield* AzureDevOpsPullRequestProvider.make;
|
||||
|
||||
const page = yield* provider.listChangeRequests({
|
||||
cwd: "/w",
|
||||
repository: "web",
|
||||
host: "dev.azure.com",
|
||||
state: "open",
|
||||
involvement: "all",
|
||||
viewer: "[email protected]",
|
||||
limit: 10,
|
||||
query: "page",
|
||||
});
|
||||
|
||||
// `az repos pr list` filters by status, creator, reviewer and branch, and by no text at
|
||||
// all. The rows come back as they would have without a search, for the caller to narrow;
|
||||
// nothing of the search reaches the command, where it could only mean the wrong thing.
|
||||
assert.strictEqual(page.items.length, 3);
|
||||
expect(argsOfCall(0)).toEqual([
|
||||
"repos",
|
||||
"pr",
|
||||
"list",
|
||||
"--detect",
|
||||
"true",
|
||||
"--repository",
|
||||
"web",
|
||||
"--status",
|
||||
"active",
|
||||
"--include-links",
|
||||
"--top",
|
||||
"11",
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("steps over what it has already handed over, which is all Azure can be told", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
yield* cli.listPullRequests({
|
||||
cwd: "/w",
|
||||
repository: "web",
|
||||
state: "open",
|
||||
involvement: "all",
|
||||
viewer: "[email protected]",
|
||||
limit: 10,
|
||||
// The instant is the same cursor every other host reads; Azure has no filter for it and
|
||||
// takes the count instead.
|
||||
cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 20 },
|
||||
});
|
||||
|
||||
const args = argsOfCall(0);
|
||||
expect(args).toContain("--skip");
|
||||
assert.strictEqual(args[args.indexOf("--skip") + 1], "20");
|
||||
expect(args).not.toContain("2026-07-02T00:00:00Z");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports truncation from the extra row", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(11, 1))));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const batch = yield* cli.listPullRequests({
|
||||
cwd: "/w",
|
||||
repository: "web",
|
||||
state: "open",
|
||||
involvement: "all",
|
||||
viewer: "[email protected]",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.strictEqual(batch.items.length, 10);
|
||||
assert.isTrue(batch.truncated);
|
||||
assert.strictEqual(batch.cursorAdvance, 10);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("advances by malformed raw rows and keeps reading until the page is full", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
output(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify([
|
||||
{ pullRequestId: "malformed" },
|
||||
pullRequestRows(1, 1)[0],
|
||||
{ pullRequestId: "also malformed" },
|
||||
]),
|
||||
),
|
||||
),
|
||||
)
|
||||
.mockReturnValueOnce(Effect.succeed(output(pullRequests(2, 2))));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const batch = yield* cli.listPullRequests({
|
||||
cwd: "/w",
|
||||
repository: "web",
|
||||
state: "open",
|
||||
involvement: "all",
|
||||
viewer: "[email protected]",
|
||||
limit: 2,
|
||||
});
|
||||
|
||||
expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
|
||||
assert.isTrue(batch.truncated);
|
||||
// Three raw rows from the first request and one from the second produced this page.
|
||||
assert.strictEqual(batch.cursorAdvance, 4);
|
||||
const secondArgs = argsOfCall(1);
|
||||
assert.strictEqual(secondArgs[secondArgs.indexOf("--skip") + 1], "3");
|
||||
assert.strictEqual(secondArgs[secondArgs.indexOf("--top") + 1], "2");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("narrows to the author on the authored tab", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
yield* cli.listPullRequests({
|
||||
cwd: "/w",
|
||||
repository: "web",
|
||||
state: "closed",
|
||||
involvement: "authored",
|
||||
viewer: "[email protected]",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(argsOfCall(0)).toContain("--creator");
|
||||
expect(argsOfCall(0)).toContain("[email protected]");
|
||||
// Azure calls a closed pull request abandoned.
|
||||
expect(argsOfCall(0)).toContain("abandoned");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("asks Azure for every status on the All tab", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
yield* cli.listPullRequests({
|
||||
cwd: "/w",
|
||||
repository: "web",
|
||||
state: "all",
|
||||
involvement: "all",
|
||||
viewer: "[email protected]",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(argsOfCall(0)).toContain("--status");
|
||||
expect(argsOfCall(0)).toContain("all");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("narrows to the reviewer on the reviewing tab", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
yield* cli.listPullRequests({
|
||||
cwd: "/w",
|
||||
repository: "web",
|
||||
state: "open",
|
||||
involvement: "reviewing",
|
||||
viewer: "[email protected]",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(argsOfCall(0)).toContain("--reviewer");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads the signed-in account, which az reports as a bare value", () =>
|
||||
Effect.gen(function* () {
|
||||
// `--query user` unwraps the object, so the wrapper has to put it back.
|
||||
mockedExecute.mockReturnValueOnce(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
Effect.succeed(output(JSON.stringify({ name: "[email protected]", type: "user" }))),
|
||||
);
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const viewer = yield* cli.getViewer({ cwd: "/w" });
|
||||
|
||||
assert.strictEqual(viewer, "[email protected]");
|
||||
expect(argsOfCall(0)).toEqual([
|
||||
"account",
|
||||
"show",
|
||||
"--query",
|
||||
"user",
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails when nobody is signed in", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
|
||||
|
||||
assert.strictEqual(error._tag, "AzureDevOpsViewerUnavailableError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("completes a pull request to merge it, squashing only when asked", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
yield* cli.runPullRequestAction({
|
||||
cwd: "/w",
|
||||
number: 42,
|
||||
action: "merge",
|
||||
mergeMethod: "squash",
|
||||
});
|
||||
|
||||
expect(argsOfCall(0)).toEqual([
|
||||
"repos",
|
||||
"pr",
|
||||
"update",
|
||||
"--detect",
|
||||
"true",
|
||||
"--id",
|
||||
"42",
|
||||
"--status",
|
||||
"completed",
|
||||
"--squash",
|
||||
"true",
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect.each([
|
||||
{ action: "draft", expected: ["--draft", "true"] },
|
||||
{ action: "ready", expected: ["--draft", "false"] },
|
||||
{ action: "close", expected: ["--status", "abandoned"] },
|
||||
{ action: "reopen", expected: ["--status", "active"] },
|
||||
] as const)("moves a pull request with $action", ({ action, expected }) =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
yield* cli.runPullRequestAction({ cwd: "/w", number: 42, action });
|
||||
|
||||
expect(argsOfCall(0)).toEqual([
|
||||
"repos",
|
||||
"pr",
|
||||
"update",
|
||||
"--detect",
|
||||
"true",
|
||||
"--id",
|
||||
"42",
|
||||
...expected,
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads the conversation through the REST API, pinned to a version", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
output(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({
|
||||
value: [
|
||||
{
|
||||
id: 1,
|
||||
comments: [
|
||||
{ id: 1, content: "Looks good.", publishedDate: "2026-07-02T00:00:00Z" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const comments = yield* cli.listThreads({
|
||||
cwd: "/w",
|
||||
threadsUrl: "https://dev.azure.com/acme/platform/_apis/git/r/web/pullRequests/42/threads",
|
||||
});
|
||||
|
||||
assert.strictEqual(comments.length, 1);
|
||||
expect(argsOfCall(0)).toContain("rest");
|
||||
expect(argsOfCall(0)).toContain(
|
||||
"https://dev.azure.com/acme/platform/_apis/git/r/web/pullRequests/42/threads?api-version=7.1",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a pull request it cannot place as its own outcome", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
output(
|
||||
// Well-formed, but with nothing to build a link from: not a decode failure.
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({
|
||||
pullRequestId: 42,
|
||||
title: "Add the page",
|
||||
sourceRefName: "refs/heads/feat/page",
|
||||
targetRefName: "refs/heads/main",
|
||||
creationDate: "2026-07-01T00:00:00Z",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const error = yield* Effect.flip(cli.getPullRequest({ cwd: "/w", number: 42 }));
|
||||
|
||||
assert.strictEqual(error._tag, "AzureDevOpsPullRequestIncompleteError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails the read when az returns something unreadable", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"not found"}')));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const error = yield* Effect.flip(cli.getPullRequest({ cwd: "/w", number: 42 }));
|
||||
|
||||
assert.strictEqual(error._tag, "AzureDevOpsPullRequestReadError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("adds reviewers with the one command Azure has for it", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
yield* cli.setPullRequestReviewers({
|
||||
cwd: "/w",
|
||||
number: 42,
|
||||
reviewers: ["[email protected]", "[email protected]"],
|
||||
requested: true,
|
||||
});
|
||||
|
||||
expect(argsOfCall(0)).toEqual([
|
||||
"repos",
|
||||
"pr",
|
||||
"reviewer",
|
||||
"add",
|
||||
"--detect",
|
||||
"true",
|
||||
"--id",
|
||||
"42",
|
||||
"--reviewers",
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("takes a reviewer off the pull request with the same command's counterpart", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
yield* cli.setPullRequestReviewers({
|
||||
cwd: "/w",
|
||||
number: 42,
|
||||
reviewers: ["[email protected]"],
|
||||
requested: false,
|
||||
});
|
||||
|
||||
expect(argsOfCall(0)).toContain("remove");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses a reviewer az would read as a flag, before running anything", () =>
|
||||
Effect.gen(function* () {
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
cli.setPullRequestReviewers({
|
||||
cwd: "/w",
|
||||
number: 42,
|
||||
reviewers: ["--query"],
|
||||
requested: true,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(error._tag, "AzureDevOpsReviewerNameError");
|
||||
assert.strictEqual(mockedExecute.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,487 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type {
|
||||
PullRequestAction,
|
||||
PullRequestComment,
|
||||
PullRequestInvolvement,
|
||||
PullRequestListState,
|
||||
PullRequestMergeMethod,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";
|
||||
import {
|
||||
decodePullRequestJson,
|
||||
decodePullRequestListJson,
|
||||
decodeThreadsJson,
|
||||
decodeViewerJson,
|
||||
type AzureDevOpsPullRequest,
|
||||
} from "./azureDevOpsPullRequestJson.ts";
|
||||
import type { ProviderListCursor } from "./PullRequestProvider.ts";
|
||||
|
||||
/**
|
||||
* Names the read that produced unusable output, so a failure reports the call it came from
|
||||
* rather than borrowing another operation's message.
|
||||
*/
|
||||
export class AzureDevOpsPullRequestReadError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestReadError>()(
|
||||
"AzureDevOpsPullRequestReadError",
|
||||
{
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
operation: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Azure CLI returned an unreadable ${this.operation} response.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Not a decode failure: az answered, the account it answered for just has no name. */
|
||||
export class AzureDevOpsViewerUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsViewerUnavailableError>()(
|
||||
"AzureDevOpsViewerUnavailableError",
|
||||
{
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure CLI returned no account for the current sign-in.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure CLI failed in getViewer: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Not a decode failure either: az answered with a well-formed pull request that simply carries
|
||||
* no branch or link, which is a response this cannot place rather than one it cannot read.
|
||||
*/
|
||||
export class AzureDevOpsPullRequestIncompleteError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestIncompleteError>()(
|
||||
"AzureDevOpsPullRequestIncompleteError",
|
||||
{
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
number: Schema.Int,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps returned no branch or link for the pull request.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure CLI failed in getPullRequest: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Not a decode failure: the reader named a reviewer `az` would read as a flag of its own. The
|
||||
* reviewers travel as argv rather than in a request body — `az repos pr reviewer` takes them no
|
||||
* other way — so anything that could leave the value position is refused rather than sent.
|
||||
*/
|
||||
export class AzureDevOpsReviewerNameError extends Schema.TaggedErrorClass<AzureDevOpsReviewerNameError>()(
|
||||
"AzureDevOpsReviewerNameError",
|
||||
{
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "A reviewer is named by an email address or an identity id.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure CLI failed in setPullRequestReviewers: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type AzureDevOpsPullRequestCliError =
|
||||
| AzureDevOpsCli.AzureDevOpsCliError
|
||||
| AzureDevOpsPullRequestReadError
|
||||
| AzureDevOpsPullRequestIncompleteError
|
||||
| AzureDevOpsReviewerNameError
|
||||
| AzureDevOpsViewerUnavailableError;
|
||||
|
||||
/** The version every REST call below is pinned to, so a new default cannot reshape a response. */
|
||||
const REST_API_VERSION = "7.1";
|
||||
|
||||
export class AzureDevOpsPullRequestCli extends Context.Service<
|
||||
AzureDevOpsPullRequestCli,
|
||||
{
|
||||
readonly getViewer: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<string, AzureDevOpsPullRequestCliError>;
|
||||
|
||||
readonly listPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly state: PullRequestListState;
|
||||
readonly involvement: PullRequestInvolvement;
|
||||
readonly viewer: string;
|
||||
readonly limit: number;
|
||||
/**
|
||||
* Where to carry on from. Azure has no date filter for a pull request listing, so the only
|
||||
* part of a cursor it can use is how many rows have already been handed over.
|
||||
*/
|
||||
readonly cursor?: ProviderListCursor | undefined;
|
||||
}) => Effect.Effect<
|
||||
{
|
||||
readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
|
||||
readonly truncated: boolean;
|
||||
/** Raw Azure rows consumed to produce this page, including malformed rows. */
|
||||
readonly cursorAdvance: number;
|
||||
},
|
||||
AzureDevOpsPullRequestCliError
|
||||
>;
|
||||
|
||||
readonly getPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly number: number;
|
||||
}) => Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError>;
|
||||
|
||||
/** Threads are not reachable through `az repos pr`, so they come from the REST API. */
|
||||
readonly listThreads: (input: {
|
||||
readonly cwd: string;
|
||||
readonly threadsUrl: string;
|
||||
}) => Effect.Effect<ReadonlyArray<PullRequestComment>, AzureDevOpsPullRequestCliError>;
|
||||
|
||||
readonly runPullRequestAction: (input: {
|
||||
readonly cwd: string;
|
||||
readonly number: number;
|
||||
readonly action: PullRequestAction;
|
||||
readonly mergeMethod?: PullRequestMergeMethod;
|
||||
}) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
|
||||
|
||||
/**
|
||||
* Adds reviewers to a pull request, or takes them off it. `az repos pr reviewer` is the whole
|
||||
* of what Azure offers here: it adds and removes named identities, and has no counterpart that
|
||||
* says who could be named.
|
||||
*/
|
||||
readonly setPullRequestReviewers: (input: {
|
||||
readonly cwd: string;
|
||||
readonly number: number;
|
||||
readonly reviewers: ReadonlyArray<string>;
|
||||
readonly requested: boolean;
|
||||
}) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
|
||||
}
|
||||
>()("t3/pullRequest/AzureDevOpsPullRequestCli") {}
|
||||
|
||||
function statusArgs(state: PullRequestListState): ReadonlyArray<string> {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return ["--status", "active"];
|
||||
case "merged":
|
||||
return ["--status", "completed"];
|
||||
case "closed":
|
||||
return ["--status", "abandoned"];
|
||||
case "all":
|
||||
return ["--status", "all"];
|
||||
}
|
||||
}
|
||||
|
||||
function involvementArgs(input: {
|
||||
readonly involvement: PullRequestInvolvement;
|
||||
readonly viewer: string;
|
||||
}): ReadonlyArray<string> {
|
||||
switch (input.involvement) {
|
||||
case "authored":
|
||||
return ["--creator", input.viewer];
|
||||
case "reviewing":
|
||||
return ["--reviewer", input.viewer];
|
||||
case "all":
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Azure moves a pull request by setting its state rather than by named commands: completing it
|
||||
* is the merge, abandoning it is the close, and reactivating it is the reopen. Squashing is a
|
||||
* completion option rather than a strategy of its own.
|
||||
*/
|
||||
function actionArgs(
|
||||
action: PullRequestAction,
|
||||
mergeMethod: PullRequestMergeMethod | undefined,
|
||||
): ReadonlyArray<string> {
|
||||
switch (action) {
|
||||
case "merge":
|
||||
return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"];
|
||||
case "ready":
|
||||
return ["--draft", "false"];
|
||||
case "draft":
|
||||
return ["--draft", "true"];
|
||||
case "close":
|
||||
return ["--status", "abandoned"];
|
||||
case "reopen":
|
||||
return ["--status", "active"];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A reviewer Azure could be given: an email address, a display name or an identity guid, and
|
||||
* nothing that starts with a dash. The dash is the whole point — these are argv, and a value that
|
||||
* looks like a flag stops being a value.
|
||||
*/
|
||||
function isReviewerName(value: string): boolean {
|
||||
const name = value.trim();
|
||||
return name.length > 0 && !name.startsWith("-");
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
|
||||
// Every command resolves the organization, project and repository from the checkout, which is
|
||||
// what the rest of the Azure wrapper does. The remote takes three shapes and only `az` knows
|
||||
// how to read all of them.
|
||||
const detectArgs = ["--detect", "true"] as const;
|
||||
|
||||
const executeJson = (input: { readonly cwd: string; readonly args: ReadonlyArray<string> }) =>
|
||||
azure.execute({
|
||||
cwd: input.cwd,
|
||||
args: [...input.args, "--only-show-errors", "--output", "json"],
|
||||
});
|
||||
|
||||
/**
|
||||
* Azure pages by raw offset. Keep reading when malformed rows leave the decoded page short, and
|
||||
* retain the raw count so the next public cursor skips every row this walk consumed.
|
||||
*/
|
||||
const listPullRequestPage = (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly state: PullRequestListState;
|
||||
readonly involvement: PullRequestInvolvement;
|
||||
readonly viewer: string;
|
||||
readonly limit: number;
|
||||
readonly skip: number;
|
||||
readonly cursorAdvance: number;
|
||||
readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
|
||||
}): Effect.Effect<
|
||||
{
|
||||
readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
|
||||
readonly truncated: boolean;
|
||||
readonly cursorAdvance: number;
|
||||
},
|
||||
AzureDevOpsPullRequestCliError
|
||||
> => {
|
||||
const remaining = input.limit - input.items.length;
|
||||
const top = remaining + 1;
|
||||
return executeJson({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"list",
|
||||
...detectArgs,
|
||||
"--repository",
|
||||
input.repository,
|
||||
...statusArgs(input.state),
|
||||
...involvementArgs(input),
|
||||
// A web link per row, which is the only url that needs no assembling.
|
||||
"--include-links",
|
||||
...(input.skip === 0 ? [] : ["--skip", String(input.skip)]),
|
||||
"--top",
|
||||
String(top),
|
||||
],
|
||||
}).pipe(
|
||||
Effect.flatMap((result) => {
|
||||
const raw = result.stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return Effect.succeed({
|
||||
items: input.items,
|
||||
truncated: false,
|
||||
cursorAdvance: input.cursorAdvance,
|
||||
});
|
||||
}
|
||||
const decoded = decodePullRequestListJson(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsPullRequestReadError({
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
operation: "listPullRequests",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const lastItemIndex = decoded.success.rawIndexes[remaining - 1];
|
||||
if (lastItemIndex !== undefined) {
|
||||
const consumed = lastItemIndex + 1;
|
||||
return Effect.succeed({
|
||||
items: [...input.items, ...decoded.success.items.slice(0, remaining)],
|
||||
// A full raw response may have more rows even when malformed entries used the probe.
|
||||
truncated: consumed < decoded.success.rawCount || decoded.success.rawCount === top,
|
||||
cursorAdvance: input.cursorAdvance + consumed,
|
||||
});
|
||||
}
|
||||
|
||||
const items = [...input.items, ...decoded.success.items];
|
||||
if (decoded.success.rawCount < top) {
|
||||
return Effect.succeed({
|
||||
items,
|
||||
truncated: false,
|
||||
cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
|
||||
});
|
||||
}
|
||||
return listPullRequestPage({
|
||||
...input,
|
||||
skip: input.skip + decoded.success.rawCount,
|
||||
cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
|
||||
items,
|
||||
});
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
return AzureDevOpsPullRequestCli.of({
|
||||
getViewer: (input) =>
|
||||
executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(
|
||||
Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
|
||||
// `--query user` narrows the payload to the account, so it is nested back under the
|
||||
// key the decoder reads to keep one shape for the signed-in user.
|
||||
const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsPullRequestReadError({
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
operation: "getViewer",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return decoded.success === null
|
||||
? Effect.fail(new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }))
|
||||
: Effect.succeed(decoded.success);
|
||||
}),
|
||||
),
|
||||
|
||||
listPullRequests: (input) =>
|
||||
listPullRequestPage({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
state: input.state,
|
||||
involvement: input.involvement,
|
||||
viewer: input.viewer,
|
||||
limit: input.limit,
|
||||
// Azure counts rather than filters, so a slice carries on by stepping over every raw row
|
||||
// the prior slice consumed. That is an offset into a list that can shift underneath it:
|
||||
// a pull request opened between two slices moves everything down one, and the row on the
|
||||
// seam is the one that pays for it.
|
||||
skip: input.cursor?.delivered ?? 0,
|
||||
cursorAdvance: 0,
|
||||
items: [],
|
||||
}),
|
||||
|
||||
getPullRequest: (input) =>
|
||||
executeJson({
|
||||
cwd: input.cwd,
|
||||
args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],
|
||||
}).pipe(
|
||||
Effect.flatMap(
|
||||
(result): Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError> => {
|
||||
const decoded = decodePullRequestJson(result.stdout.trim());
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsPullRequestReadError({
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
operation: "getPullRequest",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Null means Azure answered with too little to place the pull request. Nothing
|
||||
// failed underneath it, so it is its own outcome rather than a decode failure.
|
||||
return decoded.success === null
|
||||
? Effect.fail(
|
||||
new AzureDevOpsPullRequestIncompleteError({
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
number: input.number,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(decoded.success);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
listThreads: (input) =>
|
||||
executeJson({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"rest",
|
||||
"--method",
|
||||
"get",
|
||||
"--url",
|
||||
`${input.threadsUrl}?api-version=${REST_API_VERSION}`,
|
||||
],
|
||||
}).pipe(
|
||||
Effect.flatMap((result) => {
|
||||
const decoded = decodeThreadsJson(result.stdout.trim());
|
||||
return Result.isSuccess(decoded)
|
||||
? Effect.succeed(decoded.success)
|
||||
: Effect.fail(
|
||||
new AzureDevOpsPullRequestReadError({
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
operation: "listThreads",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
),
|
||||
|
||||
setPullRequestReviewers: (input) =>
|
||||
input.reviewers.some((reviewer) => !isReviewerName(reviewer))
|
||||
? Effect.fail(new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }))
|
||||
: azure
|
||||
.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"reviewer",
|
||||
input.requested ? "add" : "remove",
|
||||
...detectArgs,
|
||||
"--id",
|
||||
String(input.number),
|
||||
// One `--reviewers` takes them all, because az reads the flag as a list and a
|
||||
// second one would replace the first rather than add to it.
|
||||
"--reviewers",
|
||||
...input.reviewers,
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
|
||||
runPullRequestAction: (input) =>
|
||||
azure
|
||||
.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"update",
|
||||
...detectArgs,
|
||||
"--id",
|
||||
String(input.number),
|
||||
...actionArgs(input.action, input.mergeMethod),
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(AzureDevOpsPullRequestCli, make);
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { AZURE_DEVOPS_VIEWER_PERMISSIONS } from "./AzureDevOpsPullRequestProvider.ts";
|
||||
|
||||
describe("azure devops viewer permissions", () => {
|
||||
it("offers every action to whoever is signed in, because Azure names no permission", () => {
|
||||
// The same answer for a viewer who can write, one who can only read, and an author with read
|
||||
// access: `az repos pr show` and `az repos pr list` carry nothing about the caller's standing,
|
||||
// and an unknown permission is granted rather than guessed away. Azure refuses the ones it
|
||||
// will not allow, at the moment they are taken, in words this could not have written.
|
||||
expect(AZURE_DEVOPS_VIEWER_PERMISSIONS).toEqual({
|
||||
actions: ["merge", "ready", "draft", "close", "reopen"],
|
||||
// False because the host itself cannot post one, not because this viewer may not.
|
||||
comment: false,
|
||||
resolve: false,
|
||||
verdicts: [],
|
||||
// True because `az repos pr reviewer` does take one, and Azure says nothing about who may.
|
||||
requestReviewers: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,246 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
|
||||
|
||||
import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
|
||||
import {
|
||||
PullRequestProviderError,
|
||||
type ProviderChangeRequest,
|
||||
type ProviderChangeRequestActivity,
|
||||
type ProviderChangeRequestDetail,
|
||||
type PullRequestProviderApi,
|
||||
} from "./PullRequestProvider.ts";
|
||||
import type { AzureDevOpsPullRequest } from "./azureDevOpsPullRequestJson.ts";
|
||||
|
||||
const CAPABILITIES: PullRequestCapabilities = {
|
||||
// `az repos pr` has no diff command, and the REST route reports changed files without their
|
||||
// contents, so there is no patch to show. The Code tab is hidden rather than empty.
|
||||
diff: false,
|
||||
// Reading a conversation is a plain REST read, but posting one is not something this can
|
||||
// claim without having run it, so the composer stays hidden.
|
||||
comment: false,
|
||||
actions: ["merge", "ready", "draft", "close", "reopen"],
|
||||
// Azure squashes as a completion option; it has no rebase strategy of its own.
|
||||
mergeMethods: ["merge", "squash"],
|
||||
// `az repos pr list` filters by status, creator, reviewer and branch, and by no text at all.
|
||||
search: false,
|
||||
// With no patch to show there are no lines to write against, so nothing here is offered.
|
||||
review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
|
||||
// `az repos pr reviewer add` and `remove` name identities, and nothing anywhere in `az repos`
|
||||
// lists the ones this repository could name — that lives behind the identity and graph APIs, a
|
||||
// different service with its own permissions. So the page takes a name here rather than being
|
||||
// handed a menu built out of a guess.
|
||||
reviewers: { request: true, listCandidates: false },
|
||||
};
|
||||
|
||||
/**
|
||||
* Everything this host offers, granted to whoever is signed in. Azure DevOps states no permission
|
||||
* anywhere `az repos pr show` or `az repos pr list` reach: the answer lives in the security
|
||||
* namespaces, behind identity descriptors and token paths that would be several calls per pull
|
||||
* request to resolve.
|
||||
*
|
||||
* So the actions stay live and a viewer who may not take one is told so by Azure, at the moment
|
||||
* they try. That is the safer half of an unknown: hiding a control from someone entitled to it
|
||||
* leaves them no way through and no reason given.
|
||||
*/
|
||||
export const AZURE_DEVOPS_VIEWER_PERMISSIONS: PullRequestViewerPermissions = {
|
||||
actions: CAPABILITIES.actions,
|
||||
comment: CAPABILITIES.comment,
|
||||
resolve: CAPABILITIES.review.resolve,
|
||||
verdicts: CAPABILITIES.review.verdicts,
|
||||
requestReviewers: CAPABILITIES.reviewers.request,
|
||||
};
|
||||
|
||||
/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
|
||||
function reasonFor(
|
||||
error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError,
|
||||
): PullRequestProviderError["reason"] {
|
||||
if (error._tag === "AzureDevOpsCliUnavailableError") return "missing-tool";
|
||||
if (error._tag === "AzureDevOpsCliAuthenticationError") return "unauthenticated";
|
||||
return "failed";
|
||||
}
|
||||
|
||||
function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeRequest {
|
||||
return {
|
||||
number: pullRequest.number,
|
||||
title: pullRequest.title,
|
||||
url: pullRequest.url,
|
||||
author: pullRequest.author,
|
||||
headBranch: pullRequest.headBranch,
|
||||
baseBranch: pullRequest.baseBranch,
|
||||
state: pullRequest.state,
|
||||
isDraft: pullRequest.isDraft,
|
||||
mergeability: pullRequest.mergeability,
|
||||
// Azure reports no line counts on a pull request, and with no patch to read there is
|
||||
// nothing to count them from either.
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
createdAt: pullRequest.createdAt,
|
||||
updatedAt: pullRequest.updatedAt,
|
||||
reviewRequestLogins: pullRequest.reviewRequestLogins,
|
||||
// Azure keeps labels on work items rather than on the pull request.
|
||||
labels: [],
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
|
||||
|
||||
const fail =
|
||||
(operation: string) => (error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError) =>
|
||||
new PullRequestProviderError({
|
||||
provider: "azure-devops",
|
||||
operation,
|
||||
reason: reasonFor(error),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
});
|
||||
|
||||
/** Refuses what the capabilities already say this host cannot do. */
|
||||
const unsupported = (operation: string) =>
|
||||
Effect.fail(
|
||||
new PullRequestProviderError({
|
||||
provider: "azure-devops",
|
||||
operation,
|
||||
reason: "failed",
|
||||
detail: "Azure DevOps reviews cannot be written from here yet.",
|
||||
}),
|
||||
);
|
||||
|
||||
const provider: PullRequestProviderApi = {
|
||||
kind: "azure-devops",
|
||||
capabilities: CAPABILITIES,
|
||||
|
||||
getViewer: (input) =>
|
||||
cli.getViewer({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
|
||||
|
||||
// `input.query` is deliberately dropped: `az repos pr list` filters by status, creator,
|
||||
// reviewer and branch, and has nothing that matches text. Sending it as one of those would
|
||||
// narrow by the wrong thing, so the page comes back unnarrowed and the caller filters it.
|
||||
listChangeRequests: (input) =>
|
||||
cli
|
||||
.listPullRequests({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
state: input.state,
|
||||
involvement: input.involvement,
|
||||
viewer: input.viewer,
|
||||
limit: input.limit,
|
||||
cursor: input.cursor,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(fail("listChangeRequests")),
|
||||
Effect.map((batch) => ({
|
||||
items: batch.items.map(toChangeRequest),
|
||||
truncated: batch.truncated,
|
||||
cursorAdvance: batch.cursorAdvance,
|
||||
// Azure answers in one order whether or not it is being carried on from, so a slice
|
||||
// can always be stepped past — by counting, which is all Azure offers.
|
||||
continues: true,
|
||||
})),
|
||||
),
|
||||
|
||||
getChangeRequest: (input) =>
|
||||
cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
|
||||
Effect.mapError(fail("getChangeRequest")),
|
||||
Effect.map(
|
||||
(pullRequest): ProviderChangeRequestDetail => ({
|
||||
...toChangeRequest(pullRequest),
|
||||
body: pullRequest.body,
|
||||
changedFiles: 0,
|
||||
mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
|
||||
closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
|
||||
reviewers: pullRequest.reviewers,
|
||||
checks: [],
|
||||
mergeCapabilities: { merge: true, squash: true, rebase: false },
|
||||
viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
getChangeRequestActivity: (input) =>
|
||||
cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
|
||||
Effect.mapError(fail("getChangeRequestActivity")),
|
||||
Effect.flatMap((pullRequest) =>
|
||||
(pullRequest.threadsUrl === null
|
||||
? Effect.succeed({ comments: [], truncated: true })
|
||||
: cli.listThreads({ cwd: input.cwd, threadsUrl: pullRequest.threadsUrl }).pipe(
|
||||
Effect.map((comments) => ({ comments, truncated: false })),
|
||||
Effect.orElseSucceed(() => ({ comments: [], truncated: true })),
|
||||
)
|
||||
).pipe(
|
||||
Effect.map(
|
||||
(conversation): ProviderChangeRequestActivity => ({
|
||||
comments: conversation.comments,
|
||||
commentCount: conversation.comments.length,
|
||||
commentsTruncated: conversation.truncated,
|
||||
reviewThreads: [],
|
||||
commits: [],
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// No request at all: Azure has nothing to say about the viewer that a pull request read can
|
||||
// reach, so the answer is the same constant the detail carries.
|
||||
getViewerPermissions: () => Effect.succeed(AZURE_DEVOPS_VIEWER_PERMISSIONS),
|
||||
|
||||
// Never called: `capabilities.diff` is false, and the service refuses a diff without it.
|
||||
getDiff: () =>
|
||||
Effect.fail(
|
||||
new PullRequestProviderError({
|
||||
provider: "azure-devops",
|
||||
operation: "getDiff",
|
||||
reason: "failed",
|
||||
detail: "Azure DevOps cannot produce a patch for a pull request.",
|
||||
}),
|
||||
),
|
||||
|
||||
runAction: (input) =>
|
||||
cli
|
||||
.runPullRequestAction({
|
||||
cwd: input.cwd,
|
||||
number: input.number,
|
||||
action: input.action,
|
||||
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
|
||||
})
|
||||
.pipe(Effect.mapError(fail("runAction"))),
|
||||
|
||||
// Never called: `capabilities.reviewers.listCandidates` is false, and the service refuses the
|
||||
// list without it.
|
||||
listReviewerCandidates: () =>
|
||||
Effect.fail(
|
||||
new PullRequestProviderError({
|
||||
provider: "azure-devops",
|
||||
operation: "listReviewerCandidates",
|
||||
reason: "failed",
|
||||
detail: "Azure DevOps cannot say who may review a pull request.",
|
||||
}),
|
||||
),
|
||||
|
||||
setReviewerRequest: (input) =>
|
||||
cli
|
||||
.setPullRequestReviewers({
|
||||
cwd: input.cwd,
|
||||
number: input.number,
|
||||
// Azure names an identity by an email address or a guid, and has no team to ask, so a
|
||||
// candidate's id is the whole of what it takes.
|
||||
reviewers: input.reviewers.map((reviewer) => reviewer.id),
|
||||
requested: input.requested,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("setReviewerRequest"))),
|
||||
|
||||
// Never called: `capabilities.comment` is false, and the service refuses a comment without it.
|
||||
comment: () => unsupported("comment"),
|
||||
|
||||
// Declared unsupported above, so the service refuses these before a provider is reached.
|
||||
// They exist because every provider answers the whole port.
|
||||
submitReview: () => unsupported("submitReview"),
|
||||
|
||||
replyToThread: () => unsupported("replyToThread"),
|
||||
|
||||
setThreadResolution: () => unsupported("setThreadResolution"),
|
||||
};
|
||||
|
||||
return provider;
|
||||
});
|
||||
@@ -0,0 +1,874 @@
|
||||
import { afterEach, assert, expect, it, vi } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
|
||||
import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
|
||||
|
||||
const mockedRequest = vi.fn<BitbucketApi.BitbucketApi["Service"]["request"]>();
|
||||
|
||||
const layer = it.layer(
|
||||
BitbucketPullRequestApi.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(BitbucketApi.BitbucketApi)({
|
||||
request: mockedRequest,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/** The shape `request` answers with: a body plus whether it had to be cut short. */
|
||||
function response(body: string) {
|
||||
return { body, truncated: false };
|
||||
}
|
||||
|
||||
function page(count: number, firstNumber: number, next?: string): string {
|
||||
return JSON.stringify({
|
||||
pagelen: 50,
|
||||
size: count,
|
||||
values: Array.from({ length: count }, (_, index) => ({
|
||||
id: firstNumber + index,
|
||||
title: `Pull request ${firstNumber + index}`,
|
||||
state: "OPEN",
|
||||
created_on: "2026-06-16T05:04:32+00:00",
|
||||
updated_on: "2026-06-16T05:04:33+00:00",
|
||||
source: { branch: { name: "feat/page" } },
|
||||
destination: { branch: { name: "master" } },
|
||||
links: { html: { href: `https://bitbucket.org/acme/web/pull-requests/${firstNumber}` } },
|
||||
})),
|
||||
...(next === undefined ? {} : { next }),
|
||||
});
|
||||
}
|
||||
|
||||
function valuePage(values: ReadonlyArray<unknown>, next?: string): string {
|
||||
return JSON.stringify({ values, ...(next === undefined ? {} : { next }) });
|
||||
}
|
||||
|
||||
/** Who opened the pull request, and two accounts that could review it. */
|
||||
const bilal = { uuid: "{bilal}", nickname: "bilal" };
|
||||
const octocat = { uuid: "{octocat}", nickname: "octocat" };
|
||||
const hubot = { uuid: "{hubot}", nickname: "hubot" };
|
||||
|
||||
/** One pull request as `/pullrequests/{id}` answers with it. */
|
||||
function pullRequestJson(overrides: Record<string, unknown>): string {
|
||||
return JSON.stringify({
|
||||
id: 7,
|
||||
title: "Pull request 7",
|
||||
state: "OPEN",
|
||||
author: bilal,
|
||||
created_on: "2026-06-16T05:04:32+00:00",
|
||||
updated_on: "2026-06-16T05:04:33+00:00",
|
||||
source: { branch: { name: "feat/page" } },
|
||||
destination: { branch: { name: "master" } },
|
||||
links: { html: { href: "https://bitbucket.org/acme/web/pull-requests/7" } },
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
/** The request the nth call made. */
|
||||
function callAt(index: number) {
|
||||
const call = mockedRequest.mock.calls[index];
|
||||
assert.isDefined(call);
|
||||
return call[0];
|
||||
}
|
||||
|
||||
/** The filter expression of the nth request, read back out of its query string. */
|
||||
function filterOfCall(index: number): string | null {
|
||||
const url = callAt(index).url;
|
||||
return new URLSearchParams(url.slice(url.indexOf("?") + 1)).get("q");
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
mockedRequest.mockReset();
|
||||
});
|
||||
|
||||
layer("BitbucketPullRequestApi.layer", (it) => {
|
||||
it.effect("asks for reviewers, newest first, at Bitbucket's page ceiling", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(3, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const batch = yield* api.listPullRequests({
|
||||
repository: "acme/web",
|
||||
state: "open",
|
||||
limit: 50,
|
||||
});
|
||||
|
||||
assert.strictEqual(batch.items.length, 3);
|
||||
assert.isFalse(batch.truncated);
|
||||
const url = callAt(0).url;
|
||||
expect(url).toContain("/repositories/acme/web/pullrequests");
|
||||
expect(url).toContain("state=OPEN");
|
||||
// Over 50 Bitbucket answers with an empty page and no error, so it is never exceeded.
|
||||
expect(url).toContain("pagelen=50");
|
||||
expect(url).toContain("sort=-updated_on");
|
||||
expect(url).toContain("fields=%2Bvalues.reviewers");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("follows the cursor Bitbucket sends rather than counting offsets", () =>
|
||||
Effect.gen(function* () {
|
||||
const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
|
||||
mockedRequest
|
||||
.mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
|
||||
.mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const batch = yield* api.listPullRequests({
|
||||
repository: "acme/web",
|
||||
state: "open",
|
||||
limit: 100,
|
||||
});
|
||||
|
||||
assert.strictEqual(batch.items.length, 100);
|
||||
assert.isFalse(batch.truncated);
|
||||
assert.strictEqual(callAt(1).url, next);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops at the caller's page and says more remain", () =>
|
||||
Effect.gen(function* () {
|
||||
const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const batch = yield* api.listPullRequests({
|
||||
repository: "acme/web",
|
||||
state: "open",
|
||||
limit: 50,
|
||||
});
|
||||
|
||||
assert.strictEqual(batch.items.length, 50);
|
||||
assert.isTrue(batch.truncated);
|
||||
assert.strictEqual(mockedRequest.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("counts the rows it walked past as more to come", () =>
|
||||
Effect.gen(function* () {
|
||||
// Bitbucket pages in fifties whatever was asked for, so a request for ninety-nine reads a
|
||||
// hundred and drops one. That row is more results, and saying otherwise takes the "load
|
||||
// more" away from a listing that has not finished.
|
||||
const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
|
||||
mockedRequest
|
||||
.mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
|
||||
.mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const batch = yield* api.listPullRequests({
|
||||
repository: "acme/web",
|
||||
state: "open",
|
||||
limit: 99,
|
||||
});
|
||||
|
||||
assert.strictEqual(batch.items.length, 99);
|
||||
assert.isTrue(batch.truncated);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("searches with a filter expression, which is all Bitbucket offers", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.listPullRequests({
|
||||
repository: "acme/web",
|
||||
state: "open",
|
||||
limit: 50,
|
||||
query: "page",
|
||||
});
|
||||
|
||||
expect(filterOfCall(0)).toBe('(title ~ "page" OR description ~ "page")');
|
||||
// The state filter beside it still stands, which the brackets are there to keep.
|
||||
expect(callAt(0).url).toContain("state=OPEN");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("escapes a quote and a backslash, so a search cannot reshape the filter", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.listPullRequests({
|
||||
repository: "acme/web",
|
||||
state: "open",
|
||||
limit: 50,
|
||||
query: String.raw`a\" OR state = "MERGED"`,
|
||||
});
|
||||
|
||||
const literal = String.raw`a\\\" OR state = \"MERGED\"`;
|
||||
expect(filterOfCall(0)).toBe(`(title ~ "${literal}" OR description ~ "${literal}")`);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("asks for no filter at all when the reader typed only spaces", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.listPullRequests({
|
||||
repository: "acme/web",
|
||||
state: "open",
|
||||
limit: 50,
|
||||
query: " ",
|
||||
});
|
||||
|
||||
assert.isNull(filterOfCall(0));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("carries on from the instant the last slice ended on", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.listPullRequests({
|
||||
repository: "acme/web",
|
||||
state: "open",
|
||||
limit: 50,
|
||||
cursor: { updatedBefore: "2026-07-02T00:00:00.123456+00:00", delivered: 50 },
|
||||
});
|
||||
|
||||
// Inclusive, so the rows already sent at that instant come back for the caller to drop.
|
||||
expect(filterOfCall(0)).toBe("updated_on <= 2026-07-02T00:00:00.123456+00:00");
|
||||
expect(callAt(0).url).toContain("sort=-updated_on");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("narrows by the reader's words and by where it left off at once", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.listPullRequests({
|
||||
repository: "acme/web",
|
||||
state: "open",
|
||||
limit: 50,
|
||||
query: "page",
|
||||
cursor: { updatedBefore: "2026-07-02T00:00:00+00:00", delivered: 50 },
|
||||
});
|
||||
|
||||
// Bitbucket takes one `q`, so the two narrowings are joined rather than one replacing the
|
||||
// other — and the search keeps its brackets, which is what keeps the AND out of its OR.
|
||||
expect(filterOfCall(0)).toBe(
|
||||
'(title ~ "page" OR description ~ "page") AND updated_on <= 2026-07-02T00:00:00+00:00',
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("asks for declined pull requests on the closed tab", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.listPullRequests({ repository: "acme/web", state: "closed", limit: 50 });
|
||||
|
||||
expect(callAt(0).url).toContain("state=DECLINED");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("asks for every state at once on the All tab", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.listPullRequests({ repository: "acme/web", state: "all", limit: 50 });
|
||||
|
||||
// Bitbucket unions repeated state parameters, which is the only way to span them.
|
||||
const url = callAt(0).url;
|
||||
for (const state of ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"]) {
|
||||
expect(url).toContain(`state=${state}`);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("counts a superseded pull request as closed", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.listPullRequests({ repository: "acme/web", state: "closed", limit: 50 });
|
||||
|
||||
expect(callAt(0).url).toContain("state=DECLINED");
|
||||
expect(callAt(0).url).toContain("state=SUPERSEDED");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses a repository that is not workspace and slug", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
api.listPullRequests({ repository: "acme/team/web", state: "open", limit: 50 }),
|
||||
);
|
||||
|
||||
assert.strictEqual(error._tag, "BitbucketRepositoryUnsupportedError");
|
||||
assert.strictEqual(mockedRequest.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the diff verbatim, because Bitbucket already sends a patch", () =>
|
||||
Effect.gen(function* () {
|
||||
const patch = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n";
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(patch)));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const diff = yield* api.getPullRequestDiff({ repository: "acme/web", number: 7 });
|
||||
|
||||
assert.strictEqual(diff.patch, patch);
|
||||
assert.isFalse(diff.truncated);
|
||||
expect(callAt(0)).toMatchObject({
|
||||
url: "/repositories/acme/web/pullrequests/7/diff",
|
||||
// A diff of any size would otherwise be read into memory whole.
|
||||
maxBytes: 8 * 1024 * 1024,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads a named commit's own patch, which pages no further than the whole of it", () =>
|
||||
Effect.gen(function* () {
|
||||
const patch = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n";
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(patch)));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const diff = yield* api.getPullRequestDiff({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
commit: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
|
||||
});
|
||||
|
||||
assert.strictEqual(diff.patch, patch);
|
||||
expect(callAt(0)).toMatchObject({
|
||||
url: "/repositories/acme/web/diff/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
|
||||
maxBytes: 8 * 1024 * 1024,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses a commit that is not a sha rather than reading it into a URL", () =>
|
||||
Effect.gen(function* () {
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
api.getPullRequestDiff({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
commit: "../../acme/other/diff/deadbeef",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(error._tag, "BitbucketDiffCommitError");
|
||||
assert.strictEqual(mockedRequest.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("aggregates every diffstat page", () =>
|
||||
Effect.gen(function* () {
|
||||
const next = "https://api.bitbucket.org/2.0/diffstat?page=2";
|
||||
mockedRequest
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
response(
|
||||
valuePage(
|
||||
[
|
||||
{ lines_added: 9, lines_removed: 2 },
|
||||
{ lines_added: 3, lines_removed: 1 },
|
||||
],
|
||||
next,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(response(valuePage([{ lines_added: 4, lines_removed: 7 }]))),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const stat = yield* api.getDiffStat({ repository: "acme/web", number: 7 });
|
||||
|
||||
expect(stat).toEqual({ additions: 16, deletions: 10, changedFiles: 3 });
|
||||
expect(callAt(1).url).toBe(next);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the complete commit timeline oldest first across pages", () =>
|
||||
Effect.gen(function* () {
|
||||
const next = "https://api.bitbucket.org/2.0/commits?page=2";
|
||||
mockedRequest
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
response(
|
||||
valuePage(
|
||||
[
|
||||
{ hash: "ddd", message: "fourth", date: "2026-07-04T00:00:00Z" },
|
||||
{ hash: "ccc", message: "third", date: "2026-07-03T00:00:00Z" },
|
||||
],
|
||||
next,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
response(
|
||||
valuePage([
|
||||
{ hash: "bbb", message: "second", date: "2026-07-02T00:00:00Z" },
|
||||
{ hash: "aaa", message: "first", date: "2026-07-01T00:00:00Z" },
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const commits = yield* api.listCommits({ repository: "acme/web", number: 7 });
|
||||
|
||||
expect(commits.map((commit) => commit.oid)).toEqual(["aaa", "bbb", "ccc", "ddd"]);
|
||||
expect(callAt(1).url).toBe(next);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns build statuses from every page", () =>
|
||||
Effect.gen(function* () {
|
||||
const next = "https://api.bitbucket.org/2.0/statuses?page=2";
|
||||
mockedRequest
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(response(valuePage([{ name: "Build", state: "SUCCESSFUL" }], next))),
|
||||
)
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(response(valuePage([{ name: "Lint", state: "FAILED" }]))),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const checks = yield* api.listChecks({ repository: "acme/web", number: 7 });
|
||||
|
||||
expect(checks.map((check) => [check.name, check.status])).toEqual([
|
||||
["Build", "success"],
|
||||
["Lint", "failure"],
|
||||
]);
|
||||
expect(callAt(1).url).toBe(next);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads an empty conflict list as mergeable", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const mergeability = yield* api.getMergeability({ repository: "acme/web", number: 7 });
|
||||
|
||||
assert.strictEqual(mergeability, "mergeable");
|
||||
expect(callAt(0).url).toBe("/repositories/acme/web/pullrequests/7/conflicts");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("merges with Bitbucket's own name for the strategy", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.runAction({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
action: "merge",
|
||||
mergeMethod: "rebase",
|
||||
});
|
||||
|
||||
expect(callAt(0)).toMatchObject({
|
||||
method: "POST",
|
||||
url: "/repositories/acme/web/pullrequests/7/merge",
|
||||
body: '{"merge_strategy":"rebase_fast_forward"}',
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("closes a pull request by declining it", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.runAction({ repository: "acme/web", number: 7, action: "close" });
|
||||
|
||||
expect(callAt(0)).toMatchObject({
|
||||
method: "POST",
|
||||
url: "/repositories/acme/web/pullrequests/7/decline",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("posts a comment as a JSON document, so the body stays text", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.comment({ repository: "acme/web", number: 7, body: "true" });
|
||||
|
||||
expect(callAt(0)).toMatchObject({
|
||||
method: "POST",
|
||||
url: "/repositories/acme/web/pullrequests/7/comments",
|
||||
body: '{"content":{"raw":"true"}}',
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails the read when Bitbucket answers with something unreadable", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
Effect.succeed(response(JSON.stringify({ error: "nope" }))),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const error = yield* Effect.flip(api.getPullRequest({ repository: "acme/web", number: 7 }));
|
||||
|
||||
assert.strictEqual(error._tag, "BitbucketPullRequestReadError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("states a failure once, without stacking one message inside another", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new BitbucketApi.BitbucketResponseError({
|
||||
operation: "request",
|
||||
status: 500,
|
||||
responseBodyLength: 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const error = yield* Effect.flip(api.getViewer());
|
||||
|
||||
// The fact only; the provider adds the operation around it.
|
||||
assert.strictEqual(error.detail, "Bitbucket returned HTTP 500.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails when the credentials belong to no named account", () =>
|
||||
Effect.gen(function* () {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
mockedRequest.mockReturnValueOnce(Effect.succeed(response(JSON.stringify({}))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const error = yield* Effect.flip(api.getViewer());
|
||||
|
||||
assert.strictEqual(error._tag, "BitbucketViewerUnavailableError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("follows Bitbucket's cursor and reassembles a thread that spans two pages", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
response(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({
|
||||
next: "https://api.bitbucket.org/2.0/comments?page=2",
|
||||
values: [
|
||||
{
|
||||
id: 10,
|
||||
content: { raw: "rename this" },
|
||||
user: { nickname: "bilal" },
|
||||
created_on: "2026-06-16T05:04:32+00:00",
|
||||
inline: { path: "src/a.ts", to: 12 },
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
mockedRequest.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
response(
|
||||
// The reply arrives a page after the remark it answers, which is why the threads
|
||||
// are only assembled once every page is in hand.
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({
|
||||
values: [
|
||||
{
|
||||
id: 11,
|
||||
content: { raw: "done" },
|
||||
user: { nickname: "julius" },
|
||||
created_on: "2026-06-16T06:04:32+00:00",
|
||||
parent: { id: 10 },
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const { comments, threads, truncated } = yield* api.listComments({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
});
|
||||
|
||||
expect(callAt(1).url).toBe("https://api.bitbucket.org/2.0/comments?page=2");
|
||||
expect(comments.map((comment) => comment.id)).toEqual(["10", "11"]);
|
||||
expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11"]);
|
||||
assert.isFalse(truncated);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops the comment walk at its bound and says the conversation was cut short", () =>
|
||||
Effect.gen(function* () {
|
||||
// Bitbucket that always names a next page: the walk has to end itself.
|
||||
mockedRequest.mockReturnValue(
|
||||
Effect.succeed(
|
||||
response(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({
|
||||
next: "https://api.bitbucket.org/2.0/comments?page=2",
|
||||
values: [
|
||||
{
|
||||
id: 10,
|
||||
content: { raw: "again" },
|
||||
created_on: "2026-06-16T05:04:32+00:00",
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const { truncated } = yield* api.listComments({ repository: "acme/web", number: 7 });
|
||||
|
||||
assert.strictEqual(mockedRequest.mock.calls.length, 10);
|
||||
assert.isTrue(truncated);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reassembles a thread from the flat comment list, replies included", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
response(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({
|
||||
values: [
|
||||
{
|
||||
id: 10,
|
||||
content: { raw: "rename this" },
|
||||
user: { nickname: "bilal" },
|
||||
created_on: "2026-06-16T05:04:32+00:00",
|
||||
inline: { path: "src/a.ts", to: 12, from: null },
|
||||
resolution: { type: "pullrequest_comment_resolution" },
|
||||
},
|
||||
{
|
||||
id: 11,
|
||||
content: { raw: "done" },
|
||||
user: { nickname: "julius" },
|
||||
created_on: "2026-06-16T06:04:32+00:00",
|
||||
parent: { id: 10 },
|
||||
},
|
||||
// A reply to a reply still belongs to the thread its root opened.
|
||||
{
|
||||
id: 12,
|
||||
content: { raw: "thanks" },
|
||||
user: { nickname: "bilal" },
|
||||
created_on: "2026-06-16T07:04:32+00:00",
|
||||
parent: { id: 11 },
|
||||
},
|
||||
{
|
||||
id: 13,
|
||||
content: { raw: "ship it" },
|
||||
user: { nickname: "bilal" },
|
||||
created_on: "2026-06-16T08:04:32+00:00",
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const { threads } = yield* api.listComments({ repository: "acme/web", number: 7 });
|
||||
|
||||
assert.strictEqual(threads.length, 1);
|
||||
expect(threads[0]).toMatchObject({
|
||||
id: "10",
|
||||
path: "src/a.ts",
|
||||
line: 12,
|
||||
side: "right",
|
||||
isResolved: true,
|
||||
});
|
||||
expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11", "12"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("writes a review's line comments, its summary, then its verdict", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.submitReview({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
verdict: "request-changes",
|
||||
body: "Two things.",
|
||||
comments: [{ path: "src/a.ts", line: 12, side: "left", body: "why remove?" }],
|
||||
});
|
||||
|
||||
expect(callAt(0).url).toContain("/pullrequests/7/comments");
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
expect(JSON.parse(callAt(0).body ?? "")).toEqual({
|
||||
content: { raw: "why remove?" },
|
||||
inline: { path: "src/a.ts", from: 12 },
|
||||
});
|
||||
expect(callAt(1).url).toContain("/pullrequests/7/comments");
|
||||
// The verdict goes last, so a review that failed part-way is never a rejection either.
|
||||
expect(callAt(2).url).toContain("/pullrequests/7/request-changes");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves by creating the sub-resource and unresolves by deleting it", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.setCommentResolution({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
commentId: "10",
|
||||
resolved: true,
|
||||
});
|
||||
yield* api.setCommentResolution({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
commentId: "10",
|
||||
resolved: false,
|
||||
});
|
||||
|
||||
assert.strictEqual(callAt(0).method, "POST");
|
||||
assert.strictEqual(callAt(1).method, "DELETE");
|
||||
expect(callAt(0).url).toContain("/comments/10/resolve");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("replies by naming the comment it answers", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.replyToComment({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
commentId: "10",
|
||||
body: "Fixed.",
|
||||
});
|
||||
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
expect(JSON.parse(callAt(0).body ?? "")).toEqual({
|
||||
content: { raw: "Fixed." },
|
||||
parent: { id: 10 },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("asks for the credentials' permission on this repository, and nobody else's", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest.mockReturnValue(
|
||||
Effect.succeed(
|
||||
response(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({ values: [{ type: "repository_permission", permission: "read" }] }),
|
||||
),
|
||||
),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
assert.isFalse(yield* api.getRepositoryPermission({ repository: "acme/web" }));
|
||||
|
||||
expect(callAt(0).url).toContain("/user/permissions/repositories");
|
||||
assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/web"');
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("escapes a repository name before it goes inside a filter literal", () =>
|
||||
Effect.gen(function* () {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
mockedRequest.mockReturnValue(Effect.succeed(response(JSON.stringify({ values: [] }))));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.getRepositoryPermission({ repository: 'acme/we"b' });
|
||||
|
||||
// A quote would otherwise end the literal and leave the rest standing as filter syntax.
|
||||
assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/we\\"b"');
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads the workspace's people and marks whoever is already a reviewer", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest
|
||||
.mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
response(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.stringify({ values: [{ user: bilal }, { user: octocat }, { user: hubot }] }),
|
||||
),
|
||||
),
|
||||
);
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const list = yield* api.listReviewerCandidates({ repository: "acme/web", number: 7 });
|
||||
|
||||
// The people live on the workspace: nothing on a repository lists who may review it.
|
||||
expect(callAt(1).url).toBe("/workspaces/acme/members?pagelen=50");
|
||||
expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([
|
||||
["{octocat}", true],
|
||||
["{hubot}", false],
|
||||
]);
|
||||
assert.isFalse(list.truncated);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("writes the reviewer set back with the one being asked added to it", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest
|
||||
.mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
|
||||
.mockReturnValueOnce(Effect.succeed(response("{}")));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.setReviewerRequest({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
reviewers: [{ id: "{hubot}" }],
|
||||
requested: true,
|
||||
});
|
||||
|
||||
// Bitbucket writes `reviewers` whole, so the one already on the pull request travels with
|
||||
// the new one or the request would take them off it.
|
||||
const call = callAt(1);
|
||||
expect(call.method).toBe("PUT");
|
||||
expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
expect(JSON.parse(call.body ?? "")).toEqual({
|
||||
reviewers: [{ uuid: "{octocat}" }, { uuid: "{hubot}" }],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("takes a reviewer out of the set rather than clearing it", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRequest
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(response(pullRequestJson({ reviewers: [octocat, hubot] }))),
|
||||
)
|
||||
.mockReturnValueOnce(Effect.succeed(response("{}")));
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
yield* api.setReviewerRequest({
|
||||
repository: "acme/web",
|
||||
number: 7,
|
||||
reviewers: [{ id: "{hubot}" }],
|
||||
requested: false,
|
||||
});
|
||||
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
expect(JSON.parse(callAt(1).body ?? "")).toEqual({ reviewers: [{ uuid: "{octocat}" }] });
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,785 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type {
|
||||
PullRequestAction,
|
||||
PullRequestCheck,
|
||||
PullRequestComment,
|
||||
PullRequestCommit,
|
||||
PullRequestListState,
|
||||
PullRequestMergeMethod,
|
||||
PullRequestMergeability,
|
||||
PullRequestReviewCommentDraft,
|
||||
PullRequestReviewThread,
|
||||
PullRequestReviewVerdict,
|
||||
PullRequestReviewerCandidateList,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
|
||||
import {
|
||||
buildReviewThreads,
|
||||
decodeCommentsJson,
|
||||
decodeCommitsJson,
|
||||
decodeConflictsJson,
|
||||
decodeDiffstatJson,
|
||||
decodePullRequestJson,
|
||||
decodePullRequestPageJson,
|
||||
decodeRepositoryPermissionJson,
|
||||
decodeStatusesJson,
|
||||
decodeViewerJson,
|
||||
decodeWorkspaceMembersJson,
|
||||
type BitbucketDiffStat,
|
||||
type BitbucketPullRequest,
|
||||
type BitbucketRawComment,
|
||||
} from "./bitbucketPullRequestJson.ts";
|
||||
import type { ProviderListCursor } from "./PullRequestProvider.ts";
|
||||
|
||||
/**
|
||||
* Names the read that produced unusable output, so a failure reports the call it came from
|
||||
* rather than borrowing another operation's message.
|
||||
*/
|
||||
export class BitbucketPullRequestReadError extends Schema.TaggedErrorClass<BitbucketPullRequestReadError>()(
|
||||
"BitbucketPullRequestReadError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Bitbucket returned an unreadable ${this.operation} response.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Not a decode failure: Bitbucket answered, the account it answered for just has no handle. */
|
||||
export class BitbucketViewerUnavailableError extends Schema.TaggedErrorClass<BitbucketViewerUnavailableError>()(
|
||||
"BitbucketViewerUnavailableError",
|
||||
{},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Bitbucket returned no account name for the configured credentials.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket failed in getViewer: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** A repository that is not `workspace/slug`, which is the only form Bitbucket addresses. */
|
||||
export class BitbucketRepositoryUnsupportedError extends Schema.TaggedErrorClass<BitbucketRepositoryUnsupportedError>()(
|
||||
"BitbucketRepositoryUnsupportedError",
|
||||
{
|
||||
repository: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "A Bitbucket repository is addressed as workspace/repository.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket failed in resolveRepository: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Not a decode failure: the reader named a commit that is not a sha this repository could hold. */
|
||||
export class BitbucketDiffCommitError extends Schema.TaggedErrorClass<BitbucketDiffCommitError>()(
|
||||
"BitbucketDiffCommitError",
|
||||
{},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "The named commit was not a commit sha.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket failed in getPullRequestDiff: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type BitbucketPullRequestApiError =
|
||||
| BitbucketApi.BitbucketApiError
|
||||
| BitbucketPullRequestReadError
|
||||
| BitbucketViewerUnavailableError
|
||||
| BitbucketRepositoryUnsupportedError
|
||||
| BitbucketDiffCommitError;
|
||||
|
||||
/**
|
||||
* Bitbucket's own ceiling. Asking for more does not fail — it answers with an empty page and no
|
||||
* error at all, so this is a number to respect rather than to push against.
|
||||
*/
|
||||
const MAX_PAGE_SIZE = 50;
|
||||
/** Pages to walk before a listing is reported as truncated. */
|
||||
const MAX_LIST_PAGES = 10;
|
||||
/** The page size for pull request conversations, commits, and checks. */
|
||||
const CONVERSATION_PAGE_SIZE = 50;
|
||||
/**
|
||||
* Pages of the conversation to follow before it is reported as truncated. Bitbucket serves
|
||||
* fifty comments a page, so this is five hundred — beyond any pull request a person is reading,
|
||||
* and an end to a walk whose only other stop is Bitbucket running out.
|
||||
*/
|
||||
const CONVERSATION_PAGES = 10;
|
||||
/** The same ceiling the gh and glab diff reads use. */
|
||||
const DIFF_MAX_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
export interface BitbucketPullRequestBatch {
|
||||
readonly items: ReadonlyArray<BitbucketPullRequest>;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export class BitbucketPullRequestApi extends Context.Service<
|
||||
BitbucketPullRequestApi,
|
||||
{
|
||||
/** A function rather than a value, so the request is built per call and not at layer time. */
|
||||
readonly getViewer: () => Effect.Effect<string, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly listPullRequests: (input: {
|
||||
readonly repository: string;
|
||||
readonly state: PullRequestListState;
|
||||
readonly limit: number;
|
||||
/** Free text, matched against a pull request's title and description. */
|
||||
readonly query?: string | undefined;
|
||||
/** Where to carry on from, as a predicate on `updated_on` beside any other. */
|
||||
readonly cursor?: ProviderListCursor | undefined;
|
||||
}) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly getPullRequest: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
}) => Effect.Effect<BitbucketPullRequest, BitbucketPullRequestApiError>;
|
||||
|
||||
/** True where the credentials can write to the repository, which is what merging needs. */
|
||||
readonly getRepositoryPermission: (input: {
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<boolean, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly getPullRequestDiff: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
/** One commit's own changes, rather than everything the pull request carries. */
|
||||
readonly commit?: string | undefined;
|
||||
}) => Effect.Effect<
|
||||
{ readonly patch: string; readonly truncated: boolean },
|
||||
BitbucketPullRequestApiError
|
||||
>;
|
||||
|
||||
readonly getDiffStat: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
}) => Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly getMergeability: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
}) => Effect.Effect<PullRequestMergeability, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly listComments: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
}) => Effect.Effect<
|
||||
{
|
||||
readonly comments: ReadonlyArray<PullRequestComment>;
|
||||
readonly threads: ReadonlyArray<PullRequestReviewThread>;
|
||||
readonly truncated: boolean;
|
||||
},
|
||||
BitbucketPullRequestApiError
|
||||
>;
|
||||
|
||||
readonly listCommits: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
}) => Effect.Effect<ReadonlyArray<PullRequestCommit>, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly listChecks: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
}) => Effect.Effect<ReadonlyArray<PullRequestCheck>, BitbucketPullRequestApiError>;
|
||||
|
||||
/**
|
||||
* Who this pull request may be sent to, and who it has already been sent to. Two reads at
|
||||
* once, because Bitbucket keeps the people on the workspace and the reviewers on the pull
|
||||
* request, and neither answers for the other.
|
||||
*/
|
||||
readonly listReviewerCandidates: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
}) => Effect.Effect<PullRequestReviewerCandidateList, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly setReviewerRequest: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
readonly reviewers: ReadonlyArray<{ readonly id: string }>;
|
||||
readonly requested: boolean;
|
||||
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly runAction: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
readonly action: PullRequestAction;
|
||||
readonly mergeMethod?: PullRequestMergeMethod;
|
||||
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly comment: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
readonly body: string;
|
||||
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly submitReview: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
readonly verdict: PullRequestReviewVerdict;
|
||||
readonly body: string;
|
||||
readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
|
||||
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly replyToComment: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
readonly commentId: string;
|
||||
readonly body: string;
|
||||
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
|
||||
|
||||
readonly setCommentResolution: (input: {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
readonly commentId: string;
|
||||
readonly resolved: boolean;
|
||||
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
|
||||
}
|
||||
>()("t3/pullRequest/BitbucketPullRequestApi") {}
|
||||
|
||||
/** `workspace/slug`; Bitbucket has no deeper nesting to address. */
|
||||
function repositorySegments(
|
||||
repository: string,
|
||||
): Result.Result<
|
||||
{ readonly workspace: string; readonly slug: string },
|
||||
BitbucketRepositoryUnsupportedError
|
||||
> {
|
||||
const segments = repository
|
||||
.split("/")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0);
|
||||
const [workspace, slug] = segments;
|
||||
if (segments.length !== 2 || workspace === undefined || slug === undefined) {
|
||||
return Result.fail(new BitbucketRepositoryUnsupportedError({ repository }));
|
||||
}
|
||||
return Result.succeed({ workspace, slug });
|
||||
}
|
||||
|
||||
function repositoryPathOf(segments: { readonly workspace: string; readonly slug: string }): string {
|
||||
return `/repositories/${encodeURIComponent(segments.workspace)}/${encodeURIComponent(
|
||||
segments.slug,
|
||||
)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A commit sha arrives from the reader and goes straight into a request path, so it is checked
|
||||
* rather than trusted: hexadecimal only, from the shortest abbreviation a host prints up to a
|
||||
* whole sha.
|
||||
*/
|
||||
function isCommitSha(value: string): boolean {
|
||||
return /^[0-9a-f]{7,64}$/i.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bitbucket unions repeated `state` parameters, so a tab that spans several of its states asks
|
||||
* for each. It separates a declined pull request from one superseded by another, and both read
|
||||
* as closed here.
|
||||
*/
|
||||
function stateParams(state: PullRequestListState): ReadonlyArray<string> {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return ["OPEN"];
|
||||
case "merged":
|
||||
return ["MERGED"];
|
||||
case "closed":
|
||||
return ["DECLINED", "SUPERSEDED"];
|
||||
case "all":
|
||||
return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bitbucket has no search term, only a filter expression, so free text becomes one: a
|
||||
* case-insensitive contains against the two fields a pull request carries words in. The
|
||||
* parentheses matter, because the expression is ANDed with the state filter beside it and an
|
||||
* unbracketed `OR` would swallow it.
|
||||
*
|
||||
* A string literal in that grammar is delimited by double quotes, so the reader's text is
|
||||
* escaped before it goes inside one — a quote would otherwise end the literal and leave the
|
||||
* rest of the text standing as filter syntax. The whole expression is then URL-encoded, so
|
||||
* nothing in it reaches the query string as a parameter of its own.
|
||||
*/
|
||||
function searchFilter(query: string): string {
|
||||
const literal = filterLiteral(query);
|
||||
return `(title ~ "${literal}" OR description ~ "${literal}")`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Text as a string literal of Bitbucket's filter grammar. The backslash is escaped first, or
|
||||
* escaping the quote would only produce a literal backslash followed by a live quote.
|
||||
*/
|
||||
function filterLiteral(value: string): string {
|
||||
return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
|
||||
}
|
||||
|
||||
/** Bitbucket's merge strategies, named differently from the three the contract carries. */
|
||||
function mergeStrategy(method: PullRequestMergeMethod | undefined): string {
|
||||
switch (method) {
|
||||
case "squash":
|
||||
return "squash";
|
||||
case "rebase":
|
||||
// The linear history GitHub calls "rebase and merge".
|
||||
return "rebase_fast_forward";
|
||||
default:
|
||||
return "merge_commit";
|
||||
}
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
|
||||
/**
|
||||
* The repository's own path, and the workspace above it — which the people who may review are
|
||||
* kept on rather than on the repository, so both are handed over at once.
|
||||
*/
|
||||
const withRepository = <A>(
|
||||
repository: string,
|
||||
use: (path: string, workspace: string) => Effect.Effect<A, BitbucketPullRequestApiError>,
|
||||
): Effect.Effect<A, BitbucketPullRequestApiError> => {
|
||||
const segments = repositorySegments(repository);
|
||||
return Result.isSuccess(segments)
|
||||
? use(repositoryPathOf(segments.success), segments.success.workspace)
|
||||
: Effect.fail(segments.failure);
|
||||
};
|
||||
|
||||
/**
|
||||
* Bitbucket pages with a cursor rather than an offset, so the walk follows the `next` URL it
|
||||
* sends. It stops once the caller's page is filled, when Bitbucket reports no next page, or at
|
||||
* the page cap — and anything but running out of pages means there is more to be had.
|
||||
*/
|
||||
const listPage = (input: {
|
||||
readonly url: string;
|
||||
readonly limit: number;
|
||||
readonly page: number;
|
||||
readonly collected: ReadonlyArray<BitbucketPullRequest>;
|
||||
}): Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError> =>
|
||||
bitbucket.request({ method: "GET", url: input.url }).pipe(
|
||||
Effect.flatMap((response) => {
|
||||
const decoded = decodePullRequestPageJson(response.body);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new BitbucketPullRequestReadError({
|
||||
operation: "listPullRequests",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const collected = [...input.collected, ...decoded.success.items];
|
||||
const next = decoded.success.next;
|
||||
if (next === null || collected.length >= input.limit || input.page >= MAX_LIST_PAGES) {
|
||||
return Effect.succeed({
|
||||
items: collected.slice(0, input.limit),
|
||||
// Bitbucket pages in fifties whatever was asked for, so a walk that stopped on the
|
||||
// count rather than on the last page is holding rows it is about to drop. Those are
|
||||
// more results just as surely as another page would be.
|
||||
truncated: next !== null || collected.length > input.limit,
|
||||
});
|
||||
}
|
||||
return listPage({ ...input, url: next, page: input.page + 1, collected });
|
||||
}),
|
||||
);
|
||||
|
||||
const readPage = <A>(input: {
|
||||
readonly operation: string;
|
||||
readonly url: string;
|
||||
readonly decode: (body: string) => Result.Result<A, unknown>;
|
||||
}): Effect.Effect<A, BitbucketPullRequestApiError> =>
|
||||
bitbucket.request({ method: "GET", url: input.url }).pipe(
|
||||
Effect.flatMap((response) => {
|
||||
const decoded = input.decode(response.body);
|
||||
return Result.isSuccess(decoded)
|
||||
? Effect.succeed(decoded.success)
|
||||
: Effect.fail(
|
||||
new BitbucketPullRequestReadError({
|
||||
operation: input.operation,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* The conversation, following the `next` Bitbucket sends until it sends none. Threads are
|
||||
* assembled once at the end rather than per page, because a reply and the remark it answers
|
||||
* can land either side of a page boundary.
|
||||
*/
|
||||
const commentsPage = (input: {
|
||||
readonly url: string;
|
||||
readonly page: number;
|
||||
readonly comments: ReadonlyArray<PullRequestComment>;
|
||||
readonly entries: ReadonlyArray<BitbucketRawComment>;
|
||||
}): Effect.Effect<
|
||||
{
|
||||
readonly comments: ReadonlyArray<PullRequestComment>;
|
||||
readonly threads: ReadonlyArray<PullRequestReviewThread>;
|
||||
readonly truncated: boolean;
|
||||
},
|
||||
BitbucketPullRequestApiError
|
||||
> =>
|
||||
readPage({ operation: "listComments", url: input.url, decode: decodeCommentsJson }).pipe(
|
||||
Effect.flatMap((page) => {
|
||||
const comments = [...input.comments, ...page.comments];
|
||||
const entries = [...input.entries, ...page.entries];
|
||||
if (page.next !== null && input.page < CONVERSATION_PAGES) {
|
||||
return commentsPage({ url: page.next, page: input.page + 1, comments, entries });
|
||||
}
|
||||
return Effect.succeed({
|
||||
comments,
|
||||
threads: buildReviewThreads(entries),
|
||||
truncated: page.next !== null,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
/** Walks a Bitbucket cursor to its end and combines every decoded item. */
|
||||
const itemPages = <A>(input: {
|
||||
readonly operation: string;
|
||||
readonly url: string;
|
||||
readonly decode: (
|
||||
body: string,
|
||||
) => Result.Result<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, unknown>;
|
||||
readonly items: ReadonlyArray<A>;
|
||||
/** Commit pages are individually oldest-first, so older pages are prepended. */
|
||||
readonly prepend: boolean;
|
||||
}): Effect.Effect<ReadonlyArray<A>, BitbucketPullRequestApiError> =>
|
||||
readPage({ operation: input.operation, url: input.url, decode: input.decode }).pipe(
|
||||
Effect.flatMap((page) => {
|
||||
const items = input.prepend
|
||||
? [...page.items, ...input.items]
|
||||
: [...input.items, ...page.items];
|
||||
return page.next === null
|
||||
? Effect.succeed(items)
|
||||
: itemPages({ ...input, url: page.next, items });
|
||||
}),
|
||||
);
|
||||
|
||||
/** Diffstat has one aggregate per page, so its totals are folded while following `next`. */
|
||||
const diffStatPages = (input: {
|
||||
readonly url: string;
|
||||
readonly totals: BitbucketDiffStat;
|
||||
}): Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError> =>
|
||||
readPage({ operation: "getDiffStat", url: input.url, decode: decodeDiffstatJson }).pipe(
|
||||
Effect.flatMap((page) => {
|
||||
const totals = {
|
||||
additions: input.totals.additions + page.additions,
|
||||
deletions: input.totals.deletions + page.deletions,
|
||||
changedFiles: input.totals.changedFiles + page.changedFiles,
|
||||
};
|
||||
return page.next === null
|
||||
? Effect.succeed(totals)
|
||||
: diffStatPages({ url: page.next, totals });
|
||||
}),
|
||||
);
|
||||
|
||||
return BitbucketPullRequestApi.of({
|
||||
getViewer: () =>
|
||||
bitbucket.request({ method: "GET", url: "/user" }).pipe(
|
||||
Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
|
||||
const decoded = decodeViewerJson(response.body);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new BitbucketPullRequestReadError({ operation: "getViewer", cause: decoded.failure }),
|
||||
);
|
||||
}
|
||||
return decoded.success === null
|
||||
? Effect.fail(new BitbucketViewerUnavailableError())
|
||||
: Effect.succeed(decoded.success);
|
||||
}),
|
||||
),
|
||||
|
||||
listPullRequests: (input) =>
|
||||
withRepository(input.repository, (path) => {
|
||||
const search = input.query?.trim() ?? "";
|
||||
// Both narrowings share the one `q` Bitbucket takes, so they are ANDed rather than one
|
||||
// replacing the other. The boundary instant is read inclusively — the rows already sent
|
||||
// at it come back and the caller drops them, which is what keeps their neighbours at the
|
||||
// same instant from being skipped. A date is a bare literal in this grammar, and this one
|
||||
// was checked against a timestamp's shape before it got here.
|
||||
const predicates = [
|
||||
...(search.length === 0 ? [] : [searchFilter(search)]),
|
||||
...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
|
||||
];
|
||||
return listPage({
|
||||
// Reviewers are not on a listing by default, and `viewerReviewRequested` needs them.
|
||||
url: `${path}/pullrequests?${stateParams(input.state)
|
||||
.map((state) => `state=${state}`)
|
||||
.join("&")}&pagelen=${MAX_PAGE_SIZE}&sort=-updated_on&fields=%2Bvalues.reviewers${
|
||||
predicates.length === 0 ? "" : `&q=${encodeURIComponent(predicates.join(" AND "))}`
|
||||
}`,
|
||||
limit: input.limit,
|
||||
page: 1,
|
||||
collected: [],
|
||||
});
|
||||
}),
|
||||
|
||||
getPullRequest: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
readPage({
|
||||
operation: "getPullRequest",
|
||||
url: `${path}/pullrequests/${input.number}`,
|
||||
decode: decodePullRequestJson,
|
||||
}),
|
||||
),
|
||||
|
||||
// Nothing on the repository, the pull request or the workspace states what the credentials
|
||||
// may do, so this endpoint is the one request Bitbucket makes unavoidable. It is asked
|
||||
// alongside the reads the detail was already making, so it costs no round trip of its own.
|
||||
getRepositoryPermission: (input) =>
|
||||
withRepository(input.repository, () =>
|
||||
readPage({
|
||||
operation: "getRepositoryPermission",
|
||||
url: `/user/permissions/repositories?q=${encodeURIComponent(
|
||||
`repository.full_name="${filterLiteral(input.repository.trim())}"`,
|
||||
)}`,
|
||||
decode: decodeRepositoryPermissionJson,
|
||||
}),
|
||||
),
|
||||
|
||||
getPullRequestDiff: (input) =>
|
||||
input.commit !== undefined && !isCommitSha(input.commit)
|
||||
? Effect.fail(new BitbucketDiffCommitError())
|
||||
: withRepository(input.repository, (path) =>
|
||||
// Already a unified patch, so it needs no decoding at all — only a bound, which a
|
||||
// diff of any size would otherwise ignore. A commit's own patch sits beside the pull
|
||||
// request's at `/diff/{sha}` and reads the same way.
|
||||
bitbucket
|
||||
.request({
|
||||
method: "GET",
|
||||
url:
|
||||
input.commit === undefined
|
||||
? `${path}/pullrequests/${input.number}/diff`
|
||||
: `${path}/diff/${input.commit}`,
|
||||
maxBytes: DIFF_MAX_BYTES,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),
|
||||
),
|
||||
),
|
||||
|
||||
getDiffStat: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
diffStatPages({
|
||||
url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
|
||||
totals: { additions: 0, deletions: 0, changedFiles: 0 },
|
||||
}),
|
||||
),
|
||||
|
||||
getMergeability: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
readPage({
|
||||
operation: "getMergeability",
|
||||
url: `${path}/pullrequests/${input.number}/conflicts`,
|
||||
decode: decodeConflictsJson,
|
||||
}),
|
||||
),
|
||||
|
||||
listComments: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
commentsPage({
|
||||
url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
|
||||
page: 1,
|
||||
comments: [],
|
||||
entries: [],
|
||||
}),
|
||||
),
|
||||
|
||||
listCommits: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
itemPages({
|
||||
operation: "listCommits",
|
||||
url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
|
||||
decode: decodeCommitsJson,
|
||||
items: [],
|
||||
prepend: true,
|
||||
}),
|
||||
),
|
||||
|
||||
listChecks: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
itemPages({
|
||||
operation: "listChecks",
|
||||
url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
|
||||
decode: decodeStatusesJson,
|
||||
items: [],
|
||||
prepend: false,
|
||||
}),
|
||||
),
|
||||
|
||||
listReviewerCandidates: (input) =>
|
||||
withRepository(input.repository, (path, workspace) =>
|
||||
Effect.all(
|
||||
[
|
||||
readPage({
|
||||
operation: "getPullRequest",
|
||||
url: `${path}/pullrequests/${input.number}`,
|
||||
decode: decodePullRequestJson,
|
||||
}),
|
||||
readPage({
|
||||
operation: "listReviewerCandidates",
|
||||
url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
|
||||
decode: decodeWorkspaceMembersJson,
|
||||
}),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
).pipe(
|
||||
Effect.map(([pullRequest, members]) => {
|
||||
const requested = new Set(pullRequest.reviewerIds);
|
||||
const author = pullRequest.author?.login;
|
||||
return {
|
||||
// The author is dropped rather than shown unusable: Bitbucket refuses to make the
|
||||
// person who opened a pull request its reviewer.
|
||||
candidates: members.items.flatMap((candidate) =>
|
||||
candidate.login === author
|
||||
? []
|
||||
: [{ ...candidate, isRequested: requested.has(candidate.id) }],
|
||||
),
|
||||
truncated: members.next !== null,
|
||||
};
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
setReviewerRequest: (input) =>
|
||||
withRepository(input.repository, (path) => {
|
||||
const pullRequest = `${path}/pullrequests/${input.number}`;
|
||||
return readPage({
|
||||
operation: "getPullRequest",
|
||||
url: pullRequest,
|
||||
decode: decodePullRequestJson,
|
||||
}).pipe(
|
||||
Effect.flatMap((current) => {
|
||||
// Bitbucket has no endpoint that adds or removes one reviewer: the pull request's
|
||||
// `reviewers` is written whole, so the set that is already there is read first and
|
||||
// the change applied to it. Everything else about the pull request is left out of
|
||||
// the body, which leaves it as it was.
|
||||
const uuids = new Set(current.reviewerIds);
|
||||
for (const reviewer of input.reviewers) {
|
||||
if (input.requested) uuids.add(reviewer.id);
|
||||
else uuids.delete(reviewer.id);
|
||||
}
|
||||
return bitbucket.request({
|
||||
method: "PUT",
|
||||
url: pullRequest,
|
||||
body: JSON.stringify({ reviewers: [...uuids].map((uuid) => ({ uuid })) }),
|
||||
});
|
||||
}),
|
||||
Effect.asVoid,
|
||||
);
|
||||
}),
|
||||
|
||||
runAction: (input) =>
|
||||
withRepository(input.repository, (path) => {
|
||||
const pullRequest = `${path}/pullrequests/${input.number}`;
|
||||
// Only merge and close reach here: the provider declares the others unsupported, so the
|
||||
// surface never offers them.
|
||||
if (input.action === "merge") {
|
||||
return bitbucket
|
||||
.request({
|
||||
method: "POST",
|
||||
url: `${pullRequest}/merge`,
|
||||
body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
|
||||
})
|
||||
.pipe(Effect.asVoid);
|
||||
}
|
||||
return bitbucket
|
||||
.request({ method: "POST", url: `${pullRequest}/decline` })
|
||||
.pipe(Effect.asVoid);
|
||||
}),
|
||||
|
||||
comment: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
bitbucket
|
||||
.request({
|
||||
method: "POST",
|
||||
url: `${path}/pullrequests/${input.number}/comments`,
|
||||
// A JSON document rather than a form field, so the body stays text whatever it says.
|
||||
body: JSON.stringify({ content: { raw: input.body } }),
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
),
|
||||
|
||||
submitReview: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
Effect.gen(function* () {
|
||||
const pullRequest = `${path}/pullrequests/${input.number}`;
|
||||
// Bitbucket has no pending review, so a review is replayed as the requests it is
|
||||
// made of: the line comments, then the summary, then the verdict. The verdict goes
|
||||
// last so a review that fails part-way is never left standing as an approval.
|
||||
yield* Effect.forEach(
|
||||
input.comments,
|
||||
(comment) =>
|
||||
bitbucket.request({
|
||||
method: "POST",
|
||||
url: `${pullRequest}/comments`,
|
||||
body: JSON.stringify({
|
||||
content: { raw: comment.body },
|
||||
inline: {
|
||||
path: comment.path,
|
||||
...(comment.side === "left" ? { from: comment.line } : { to: comment.line }),
|
||||
},
|
||||
}),
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
if (input.body.trim().length > 0) {
|
||||
yield* bitbucket.request({
|
||||
method: "POST",
|
||||
url: `${pullRequest}/comments`,
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
body: JSON.stringify({ content: { raw: input.body } }),
|
||||
});
|
||||
}
|
||||
if (input.verdict === "approve") {
|
||||
yield* bitbucket.request({ method: "POST", url: `${pullRequest}/approve` });
|
||||
}
|
||||
if (input.verdict === "request-changes") {
|
||||
yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
|
||||
}
|
||||
}),
|
||||
),
|
||||
|
||||
replyToComment: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
bitbucket
|
||||
.request({
|
||||
method: "POST",
|
||||
url: `${path}/pullrequests/${input.number}/comments`,
|
||||
body: JSON.stringify({
|
||||
content: { raw: input.body },
|
||||
parent: { id: Number(input.commentId) },
|
||||
}),
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
),
|
||||
|
||||
setCommentResolution: (input) =>
|
||||
withRepository(input.repository, (path) =>
|
||||
bitbucket
|
||||
.request({
|
||||
// Resolving is a sub-resource that is created and deleted, rather than a field.
|
||||
method: input.resolved ? "POST" : "DELETE",
|
||||
url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
|
||||
input.commentId,
|
||||
)}/resolve`,
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(BitbucketPullRequestApi, make);
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
|
||||
import {
|
||||
bitbucketErrorReason,
|
||||
bitbucketViewerPermissions,
|
||||
} from "./BitbucketPullRequestProvider.ts";
|
||||
|
||||
describe("bitbucketErrorReason", () => {
|
||||
it("treats only an HTTP 401 as unusable credentials", () => {
|
||||
const responseError = (status: number) =>
|
||||
new BitbucketApi.BitbucketResponseError({
|
||||
operation: "request",
|
||||
status,
|
||||
responseBodyLength: 0,
|
||||
});
|
||||
|
||||
expect(bitbucketErrorReason(responseError(401))).toBe("unauthenticated");
|
||||
expect(bitbucketErrorReason(responseError(403))).toBe("failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("bitbucketViewerPermissions", () => {
|
||||
it("offers both actions to credentials with write access", () => {
|
||||
expect(bitbucketViewerPermissions({ canWrite: true })).toEqual({
|
||||
actions: ["merge", "close"],
|
||||
comment: true,
|
||||
resolve: true,
|
||||
verdicts: ["comment", "approve", "request-changes"],
|
||||
// Bitbucket says nothing about who may set a reviewer, and an unreported permission is
|
||||
// granted.
|
||||
requestReviewers: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps merge from credentials that can only read the repository", () => {
|
||||
expect(bitbucketViewerPermissions({ canWrite: false })).toEqual({
|
||||
actions: ["close"],
|
||||
comment: true,
|
||||
resolve: true,
|
||||
verdicts: ["comment", "approve", "request-changes"],
|
||||
requestReviewers: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("treats an author with read access as any other reader, which is all Bitbucket says", () => {
|
||||
// The repository permission is the whole of what Bitbucket reports per account; it says
|
||||
// nothing about who opened this pull request, and its author may decline it with read access
|
||||
// alone — so declining stays offered rather than being taken from them.
|
||||
expect(bitbucketViewerPermissions({ canWrite: false }).actions).toEqual(["close"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,290 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
|
||||
|
||||
import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
|
||||
import {
|
||||
PullRequestProviderError,
|
||||
type ProviderChangeRequest,
|
||||
type ProviderChangeRequestActivity,
|
||||
type ProviderChangeRequestDetail,
|
||||
type PullRequestProviderApi,
|
||||
} from "./PullRequestProvider.ts";
|
||||
import type { BitbucketPullRequest } from "./bitbucketPullRequestJson.ts";
|
||||
|
||||
const CAPABILITIES: PullRequestCapabilities = {
|
||||
diff: true,
|
||||
comment: true,
|
||||
// Bitbucket has no endpoint that reopens a declined pull request, and nothing documented that
|
||||
// moves one in or out of draft, so neither is offered rather than failing when pressed.
|
||||
actions: ["merge", "close"],
|
||||
mergeMethods: ["merge", "squash", "rebase"],
|
||||
search: true,
|
||||
review: {
|
||||
inlineComment: true,
|
||||
reply: true,
|
||||
resolve: true,
|
||||
verdicts: ["comment", "approve", "request-changes"],
|
||||
},
|
||||
reviewers: { request: true, listCandidates: true },
|
||||
};
|
||||
|
||||
/**
|
||||
* What the configured account may do here, from the one thing Bitbucket states per viewer: the
|
||||
* repository permission. Merging needs `write` or `admin`, so that is what narrows.
|
||||
*
|
||||
* Declining stays offered whatever the permission. Bitbucket lets the author of a pull request
|
||||
* decline their own with no more than read access, and the permission response says nothing about
|
||||
* who opened this one — so withholding the control from the one person entitled to it is the
|
||||
* worse of the two mistakes. Commenting and reviewing are not narrowed either: read access is
|
||||
* enough to say something, to approve and to ask for changes.
|
||||
*
|
||||
* Asking for a review is left open for the same reason: Bitbucket takes a reviewer set from the
|
||||
* author of a pull request as well as from whoever can write, and says nothing here about which
|
||||
* of the two this account is.
|
||||
*/
|
||||
export function bitbucketViewerPermissions(input: {
|
||||
readonly canWrite: boolean;
|
||||
}): PullRequestViewerPermissions {
|
||||
return {
|
||||
actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.canWrite),
|
||||
comment: true,
|
||||
resolve: true,
|
||||
verdicts: CAPABILITIES.review.verdicts,
|
||||
requestReviewers: true,
|
||||
};
|
||||
}
|
||||
|
||||
/** The failures that mean the credentials are the problem, rather than one request. */
|
||||
export function bitbucketErrorReason(
|
||||
error: BitbucketPullRequestApi.BitbucketPullRequestApiError,
|
||||
): PullRequestProviderError["reason"] {
|
||||
// Bitbucket is read over HTTP with credentials from the environment, so there is no tool to be
|
||||
// missing: unusable always means the credentials are absent or refused.
|
||||
if (error._tag === "BitbucketResponseError" && error.status === 401) {
|
||||
return "unauthenticated";
|
||||
}
|
||||
return "failed";
|
||||
}
|
||||
|
||||
function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeRequest {
|
||||
return {
|
||||
number: pullRequest.number,
|
||||
title: pullRequest.title,
|
||||
url: pullRequest.url,
|
||||
author: pullRequest.author,
|
||||
headBranch: pullRequest.headBranch,
|
||||
baseBranch: pullRequest.baseBranch,
|
||||
state: pullRequest.state,
|
||||
isDraft: pullRequest.isDraft,
|
||||
mergeability: pullRequest.mergeability,
|
||||
// Line counts are a separate read, which only the detail is worth spending on.
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
createdAt: pullRequest.createdAt,
|
||||
updatedAt: pullRequest.updatedAt,
|
||||
reviewRequestLogins: pullRequest.reviewRequestLogins,
|
||||
// Bitbucket has no labels on a pull request.
|
||||
labels: [],
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
|
||||
|
||||
const fail =
|
||||
(operation: string) => (error: BitbucketPullRequestApi.BitbucketPullRequestApiError) =>
|
||||
new PullRequestProviderError({
|
||||
provider: "bitbucket",
|
||||
operation,
|
||||
reason: bitbucketErrorReason(error),
|
||||
// Every Bitbucket failure states its own fact; this names the operation around it, so
|
||||
// the two do not stack into "failed in x: failed in y: ...".
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
});
|
||||
|
||||
const provider: PullRequestProviderApi = {
|
||||
kind: "bitbucket",
|
||||
capabilities: CAPABILITIES,
|
||||
|
||||
// Bitbucket credentials come from the server's environment rather than a checkout, so the
|
||||
// account is the same whichever workspace asks.
|
||||
getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))),
|
||||
|
||||
listChangeRequests: (input) =>
|
||||
api
|
||||
.listPullRequests({
|
||||
repository: input.repository,
|
||||
state: input.state,
|
||||
limit: input.limit,
|
||||
query: input.query,
|
||||
cursor: input.cursor,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(fail("listChangeRequests")),
|
||||
Effect.map((batch) => ({
|
||||
items: batch.items.map(toChangeRequest),
|
||||
truncated: batch.truncated,
|
||||
// Bitbucket is asked for `-updated_on` whether or not it is being carried on from,
|
||||
// so every page it answers is one a cursor can continue.
|
||||
continues: true,
|
||||
})),
|
||||
),
|
||||
|
||||
getChangeRequest: (input) => {
|
||||
const target = { repository: input.repository, number: input.number };
|
||||
return Effect.all(
|
||||
[
|
||||
api.getPullRequest(target),
|
||||
api.getDiffStat(target),
|
||||
api.getMergeability(target).pipe(Effect.orElseSucceed(() => "unknown" as const)),
|
||||
api.listChecks(target).pipe(Effect.orElseSucceed(() => [])),
|
||||
// A permission that could not be read is an unknown one, which is granted: a hidden
|
||||
// Merge leaves someone entitled to it with no way through, and one Bitbucket refuses
|
||||
// at least says why.
|
||||
api.getRepositoryPermission(target).pipe(Effect.orElseSucceed(() => true)),
|
||||
],
|
||||
{ concurrency: 5 },
|
||||
).pipe(
|
||||
Effect.mapError(fail("getChangeRequest")),
|
||||
Effect.map(
|
||||
([
|
||||
pullRequest,
|
||||
diffStat,
|
||||
mergeability,
|
||||
checks,
|
||||
canWrite,
|
||||
]): ProviderChangeRequestDetail => ({
|
||||
...toChangeRequest(pullRequest),
|
||||
mergeability,
|
||||
additions: diffStat.additions,
|
||||
deletions: diffStat.deletions,
|
||||
changedFiles: diffStat.changedFiles,
|
||||
body: pullRequest.body,
|
||||
mergedAt: pullRequest.state === "merged" ? pullRequest.updatedAt : null,
|
||||
closedAt: pullRequest.state === "closed" ? pullRequest.updatedAt : null,
|
||||
reviewers: pullRequest.reviewers,
|
||||
checks,
|
||||
// Bitbucket publishes no per-repository list of allowed strategies, so the ones it
|
||||
// supports are all offered and a strategy the repository forbids fails on merge.
|
||||
mergeCapabilities: { merge: true, squash: true, rebase: true },
|
||||
viewerPermissions: bitbucketViewerPermissions({ canWrite }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
getChangeRequestActivity: (input) => {
|
||||
const target = { repository: input.repository, number: input.number };
|
||||
return Effect.all(
|
||||
[
|
||||
// Reviews ride on the pull request itself, so this inexpensive core read is repeated
|
||||
// here rather than making the core response wait for the conversation endpoints.
|
||||
api.getPullRequest(target),
|
||||
api
|
||||
.listComments(target)
|
||||
.pipe(Effect.orElseSucceed(() => ({ comments: [], threads: [], truncated: true }))),
|
||||
api.listCommits(target).pipe(Effect.orElseSucceed(() => [])),
|
||||
],
|
||||
{ concurrency: 3 },
|
||||
).pipe(
|
||||
Effect.mapError(fail("getChangeRequestActivity")),
|
||||
Effect.map(
|
||||
([pullRequest, comments, commits]): ProviderChangeRequestActivity => ({
|
||||
comments: [...comments.comments, ...pullRequest.reviews].toSorted((left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt),
|
||||
),
|
||||
commentCount: comments.comments.length + pullRequest.reviews.length,
|
||||
commentsTruncated: comments.truncated,
|
||||
reviewThreads: comments.threads,
|
||||
commits,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
getViewerPermissions: (input) =>
|
||||
api.getRepositoryPermission({ repository: input.repository }).pipe(
|
||||
Effect.mapError(fail("getViewerPermissions")),
|
||||
Effect.map((canWrite) => bitbucketViewerPermissions({ canWrite })),
|
||||
),
|
||||
|
||||
// `/diff` answers with the whole patch and pages nothing, so the first slice is the last.
|
||||
getDiff: (input) =>
|
||||
api
|
||||
.getPullRequestDiff({
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
...(input.commit === undefined ? {} : { commit: input.commit }),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(fail("getDiff")),
|
||||
Effect.map((diff) => ({ ...diff, nextCursor: null })),
|
||||
),
|
||||
|
||||
// Users only: Bitbucket requests a review of an account, and has no group that stands in for
|
||||
// one on a pull request.
|
||||
listReviewerCandidates: (input) =>
|
||||
api
|
||||
.listReviewerCandidates({ repository: input.repository, number: input.number })
|
||||
.pipe(Effect.mapError(fail("listReviewerCandidates"))),
|
||||
|
||||
setReviewerRequest: (input) =>
|
||||
api
|
||||
.setReviewerRequest({
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
reviewers: input.reviewers,
|
||||
requested: input.requested,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("setReviewerRequest"))),
|
||||
|
||||
runAction: (input) =>
|
||||
api
|
||||
.runAction({
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
action: input.action,
|
||||
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
|
||||
})
|
||||
.pipe(Effect.mapError(fail("runAction"))),
|
||||
|
||||
comment: (input) =>
|
||||
api
|
||||
.comment({ repository: input.repository, number: input.number, body: input.body })
|
||||
.pipe(Effect.mapError(fail("comment"))),
|
||||
|
||||
submitReview: (input) =>
|
||||
api
|
||||
.submitReview({
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
verdict: input.verdict,
|
||||
body: input.body,
|
||||
comments: input.comments,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("submitReview"))),
|
||||
|
||||
replyToThread: (input) =>
|
||||
api
|
||||
.replyToComment({
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
commentId: input.threadId,
|
||||
body: input.body,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("replyToThread"))),
|
||||
|
||||
setThreadResolution: (input) =>
|
||||
api
|
||||
.setCommentResolution({
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
commentId: input.threadId,
|
||||
resolved: input.resolved,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("setThreadResolution"))),
|
||||
};
|
||||
|
||||
return provider;
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,222 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
|
||||
import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
|
||||
import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
|
||||
|
||||
describe("gitHubViewerPermissions", () => {
|
||||
it("offers everything to a viewer who can write to the repository", () => {
|
||||
expect(gitHubViewerPermissions({ canWrite: true, canUpdate: true, didAuthor: false })).toEqual({
|
||||
actions: ["merge", "ready", "draft", "close", "reopen"],
|
||||
comment: true,
|
||||
resolve: true,
|
||||
verdicts: ["comment", "approve", "request-changes"],
|
||||
requestReviewers: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves a passer-by on a repository they can only read nothing but the review", () => {
|
||||
// Every open-source pull request somebody else opened: GitHub says no to all five actions
|
||||
// and to resolving, and yes to commenting and to every verdict.
|
||||
expect(
|
||||
gitHubViewerPermissions({ canWrite: false, canUpdate: false, didAuthor: false }),
|
||||
).toEqual({
|
||||
actions: [],
|
||||
comment: true,
|
||||
resolve: false,
|
||||
verdicts: ["comment", "approve", "request-changes"],
|
||||
// Asking somebody else to review is the one thing read access never stretches to.
|
||||
requestReviewers: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an author's own pull request theirs to close, with read access and no more", () => {
|
||||
expect(gitHubViewerPermissions({ canWrite: false, canUpdate: true, didAuthor: true })).toEqual({
|
||||
// Merging is the one thing writing is needed for; the rest an author may do.
|
||||
actions: ["ready", "draft", "close", "reopen"],
|
||||
comment: true,
|
||||
resolve: true,
|
||||
// GitHub refuses an author's approval of their own change, so the page does not offer one.
|
||||
verdicts: ["comment"],
|
||||
requestReviewers: false,
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("uses the small viewer-access read for core permissions", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* make;
|
||||
const detail = yield* provider.getChangeRequest({
|
||||
cwd: "/w",
|
||||
repository: "acme/web",
|
||||
host: "github.com",
|
||||
number: 7,
|
||||
});
|
||||
|
||||
expect(detail.viewerPermissions).toEqual({
|
||||
actions: ["ready", "draft", "close", "reopen"],
|
||||
comment: true,
|
||||
resolve: false,
|
||||
verdicts: ["comment", "approve", "request-changes"],
|
||||
requestReviewers: false,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
|
||||
getPullRequestDetail: () =>
|
||||
Effect.succeed({
|
||||
authorId: null,
|
||||
number: 7,
|
||||
title: "Pull request 7",
|
||||
url: "https://github.com/acme/web/pull/7",
|
||||
author: null,
|
||||
headBranch: "feat/page",
|
||||
baseBranch: "main",
|
||||
state: "open",
|
||||
isDraft: false,
|
||||
mergeability: "mergeable",
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
updatedAt: "2026-07-02T00:00:00Z",
|
||||
reviewRequestLogins: [],
|
||||
hasTeamReviewRequest: false,
|
||||
labels: [],
|
||||
body: "",
|
||||
changedFiles: 1,
|
||||
mergedAt: null,
|
||||
closedAt: null,
|
||||
checks: [],
|
||||
comments: [],
|
||||
commits: [],
|
||||
}),
|
||||
getRepositoryAccess: () =>
|
||||
Effect.succeed({
|
||||
canWrite: false,
|
||||
mergeCapabilities: { merge: true, squash: true, rebase: true },
|
||||
}),
|
||||
getViewerAccess: () =>
|
||||
Effect.succeed({ canWrite: false, canUpdate: true, didAuthor: false }),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("getChangeRequest commits", () => {
|
||||
const baseDetail = {
|
||||
authorId: null,
|
||||
number: 7,
|
||||
title: "Pull request 7",
|
||||
url: "https://github.com/acme/web/pull/7",
|
||||
author: null,
|
||||
headBranch: "feat/page",
|
||||
baseBranch: "main",
|
||||
state: "open" as const,
|
||||
isDraft: false,
|
||||
mergeability: "mergeable" as const,
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
updatedAt: "2026-07-02T00:00:00Z",
|
||||
reviewRequestLogins: [],
|
||||
hasTeamReviewRequest: false,
|
||||
labels: [],
|
||||
body: "",
|
||||
changedFiles: 1,
|
||||
mergedAt: null,
|
||||
closedAt: null,
|
||||
checks: [],
|
||||
comments: [],
|
||||
};
|
||||
|
||||
const baseThreadComments = {
|
||||
comments: [],
|
||||
reviewThreads: [],
|
||||
commentCount: 0,
|
||||
truncated: false,
|
||||
reviewers: [],
|
||||
avatarsByLogin: new Map<string, string>(),
|
||||
commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
|
||||
viewer: { canUpdate: true, didAuthor: false },
|
||||
};
|
||||
|
||||
const layerWith = (commits: GitHubReviewThreadComments["commits"]) =>
|
||||
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
|
||||
getPullRequestActivity: () =>
|
||||
Effect.succeed({
|
||||
author: baseDetail.author,
|
||||
comments: baseDetail.comments,
|
||||
commits: [
|
||||
{
|
||||
oid: "view-oldest",
|
||||
messageHeadline: "gh pr view's oldest commit",
|
||||
committedDate: "2026-01-01T00:00:00Z",
|
||||
authors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
listReviewThreadComments: () => Effect.succeed({ ...baseThreadComments, commits }),
|
||||
});
|
||||
|
||||
it.effect("prefers the GraphQL commits, which are the newest, over the gh view list", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* make;
|
||||
const detail = yield* provider.getChangeRequestActivity({
|
||||
cwd: "/w",
|
||||
repository: "acme/web",
|
||||
host: "github.com",
|
||||
number: 7,
|
||||
});
|
||||
|
||||
expect(detail.commits.map((commit) => commit.oid)).toEqual(["graphql-newest"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
layerWith([
|
||||
{
|
||||
oid: "graphql-newest",
|
||||
messageHeadline: "the newest commit gh pr view drops",
|
||||
committedDate: "2026-07-06T00:00:00Z",
|
||||
authors: [],
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back to the gh view list when the GraphQL read has no commits", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* make;
|
||||
const detail = yield* provider.getChangeRequestActivity({
|
||||
cwd: "/w",
|
||||
repository: "acme/web",
|
||||
host: "github.com",
|
||||
number: 7,
|
||||
});
|
||||
|
||||
expect(detail.commits.map((commit) => commit.oid)).toEqual(["view-oldest"]);
|
||||
}).pipe(Effect.provide(layerWith([]))),
|
||||
);
|
||||
});
|
||||
|
||||
describe("loginAvatarUrl", () => {
|
||||
it("serves a user's picture from the host they belong to", () => {
|
||||
expect(loginAvatarUrl("octocat", "github.com")).toBe("https://github.com/octocat.png?size=80");
|
||||
expect(loginAvatarUrl("octocat", "ghe.example.com")).toBe(
|
||||
"https://ghe.example.com/octocat.png?size=80",
|
||||
);
|
||||
});
|
||||
|
||||
it("has nothing for an app, which names no page", () => {
|
||||
// `dependabot[bot]` has a picture, but not at `/dependabot[bot].png` — a guess that 404s is
|
||||
// worse than the initials it would replace.
|
||||
expect(loginAvatarUrl("dependabot[bot]", "github.com")).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses anything that is not a login, rather than building a URL out of it", () => {
|
||||
for (const login of ["../../etc", "a b", "-leading", "x".repeat(40), ""]) {
|
||||
expect(loginAvatarUrl(login, "github.com")).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,352 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import type {
|
||||
PullRequestActor,
|
||||
PullRequestCapabilities,
|
||||
PullRequestViewerPermissions,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
|
||||
import {
|
||||
PullRequestProviderError,
|
||||
type ProviderChangeRequestActivity,
|
||||
type ProviderChangeRequestDetail,
|
||||
type PullRequestProviderApi,
|
||||
} from "./PullRequestProvider.ts";
|
||||
import type { GitHubViewerAccess } from "./gitHubPullRequestJson.ts";
|
||||
|
||||
const CAPABILITIES: PullRequestCapabilities = {
|
||||
diff: true,
|
||||
comment: true,
|
||||
actions: ["merge", "ready", "draft", "close", "reopen"],
|
||||
mergeMethods: ["merge", "squash", "rebase"],
|
||||
search: true,
|
||||
review: {
|
||||
inlineComment: true,
|
||||
reply: true,
|
||||
resolve: true,
|
||||
verdicts: ["comment", "approve", "request-changes"],
|
||||
},
|
||||
reviewers: { request: true, listCandidates: true },
|
||||
};
|
||||
|
||||
/**
|
||||
* What the signed-in account may do here, from the three things GitHub says about it.
|
||||
*
|
||||
* Merging needs a role that can push, which is the one thing a stranger on an open-source
|
||||
* repository never has. The other four actions go by `viewerCanUpdate`, because the author of a
|
||||
* pull request may close it, reopen it and move it in and out of draft with no more than read
|
||||
* access on the repository it was opened against.
|
||||
*
|
||||
* Commenting and reviewing are not gated at all: read access is enough to say something and
|
||||
* enough to approve or ask for changes, which is what open-source review consists of. Resolving a
|
||||
* conversation is the exception — GitHub allows it to whoever can write, and to the author of the
|
||||
* pull request the conversation is on.
|
||||
*
|
||||
* Asking somebody else for a review needs write access, which is the one thing here an author
|
||||
* cannot do on their own pull request: GitHub shows an outside contributor the reviewer control
|
||||
* and refuses the request behind it.
|
||||
*/
|
||||
export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequestViewerPermissions {
|
||||
return {
|
||||
actions: [
|
||||
...(access.canWrite ? (["merge"] as const) : []),
|
||||
...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
|
||||
],
|
||||
comment: true,
|
||||
resolve: access.canWrite || access.didAuthor,
|
||||
// Anyone may review a pull request they can see, except their own: GitHub refuses an author's
|
||||
// approval and their request for changes ("Can not approve your own pull request"), and
|
||||
// leaves them commenting, which is what an author has to say about their own change anyway.
|
||||
verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
|
||||
requestReviewers: access.canWrite,
|
||||
};
|
||||
}
|
||||
|
||||
/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
|
||||
function reasonFor(
|
||||
error: GitHubPullRequestCli.GitHubPullRequestCliError,
|
||||
): PullRequestProviderError["reason"] {
|
||||
if (error._tag === "GitHubCliUnavailableError") return "missing-tool";
|
||||
if (error._tag === "GitHubCliAuthenticationError") return "unauthenticated";
|
||||
return "failed";
|
||||
}
|
||||
|
||||
/**
|
||||
* `gh pr view --json` reports no avatar for anyone, so the ones the GraphQL read collected are
|
||||
* applied here by login. An actor already carrying one keeps it.
|
||||
*
|
||||
* A login GitHub did not answer for falls back to the picture every GitHub install serves at
|
||||
* `/<login>.png`. The lookup is one more request per repository and can be refused — a rate
|
||||
* limit, a slow host — and a face that comes and goes between two loads of the same page reads
|
||||
* as a bug in the page rather than as a request that failed quietly.
|
||||
*/
|
||||
function withAvatar(
|
||||
actor: PullRequestActor | null,
|
||||
avatarsByLogin: ReadonlyMap<string, string>,
|
||||
host: string,
|
||||
): PullRequestActor | null {
|
||||
if (actor === null || actor.avatarUrl !== null) return actor;
|
||||
const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
|
||||
return avatarUrl === null ? actor : { ...actor, avatarUrl };
|
||||
}
|
||||
|
||||
/**
|
||||
* Null for anything that is not a plain user login: an app posts as `dependabot[bot]`, which
|
||||
* names no page, and a guessed URL that 404s is worse than the initials it would replace.
|
||||
*/
|
||||
export function loginAvatarUrl(login: string, host: string): string | null {
|
||||
return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
|
||||
|
||||
const fail = (operation: string) => (error: GitHubPullRequestCli.GitHubPullRequestCliError) =>
|
||||
new PullRequestProviderError({
|
||||
provider: "github",
|
||||
operation,
|
||||
reason: reasonFor(error),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
});
|
||||
|
||||
const provider: PullRequestProviderApi = {
|
||||
kind: "github",
|
||||
capabilities: CAPABILITIES,
|
||||
|
||||
getViewer: (input) =>
|
||||
cli.getViewerLogin({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
|
||||
|
||||
listChangeRequests: (input) =>
|
||||
cli
|
||||
.listPullRequests({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
host: input.host,
|
||||
state: input.state,
|
||||
involvement: input.involvement,
|
||||
viewer: input.viewer,
|
||||
limit: input.limit,
|
||||
query: input.query,
|
||||
cursor: input.cursor,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(fail("listChangeRequests")),
|
||||
Effect.flatMap((page) =>
|
||||
cli
|
||||
.listActorAvatars({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
host: input.host,
|
||||
ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
|
||||
})
|
||||
// A listing without faces is still a listing, so a failed lookup falls back to
|
||||
// the initials rather than taking the rows down with it.
|
||||
.pipe(
|
||||
Effect.orElseSucceed(() => new Map<string, string>()),
|
||||
Effect.map((avatarsByLogin) => ({
|
||||
...page,
|
||||
items: page.items.map((item) => ({
|
||||
...item,
|
||||
author: withAvatar(item.author, avatarsByLogin, input.host),
|
||||
})),
|
||||
})),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
/**
|
||||
* The same listing for a whole host in one search. The avatar lookup the per-repository read
|
||||
* needs is not here: a search reports an author's picture itself, so a face costs no request
|
||||
* of its own — `withAvatar` still stands behind it for the login GitHub answered nothing for.
|
||||
*/
|
||||
listChangeRequestsAcross: (input) =>
|
||||
cli
|
||||
.searchPullRequests({
|
||||
cwd: input.cwd,
|
||||
host: input.host,
|
||||
repositories: input.repositories,
|
||||
state: input.state,
|
||||
involvement: input.involvement,
|
||||
viewer: input.viewer,
|
||||
limit: input.limit,
|
||||
query: input.query,
|
||||
cursor: input.cursor,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(fail("listChangeRequestsAcross")),
|
||||
Effect.map((batch) => ({
|
||||
truncated: batch.truncated,
|
||||
items: batch.items.map((item) => ({
|
||||
...item,
|
||||
author: withAvatar(item.author, new Map<string, string>(), input.host),
|
||||
})),
|
||||
})),
|
||||
),
|
||||
|
||||
listChangeRequestStats: (input) =>
|
||||
cli
|
||||
.listPullRequestStats({
|
||||
cwd: input.cwd,
|
||||
host: input.host,
|
||||
changeRequests: input.changeRequests,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("listChangeRequestStats"))),
|
||||
|
||||
getChangeRequest: (input) =>
|
||||
Effect.all(
|
||||
[
|
||||
cli.getPullRequestDetail(input),
|
||||
cli.getRepositoryAccess({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
host: input.host,
|
||||
}),
|
||||
// A small permissions query replaces the deeply paginated review-thread walk on the
|
||||
// core path. Writes ask again immediately before mutating, so this is presentation.
|
||||
cli.getViewerAccess(input),
|
||||
],
|
||||
{ concurrency: 3 },
|
||||
).pipe(
|
||||
Effect.mapError(fail("getChangeRequest")),
|
||||
Effect.map(
|
||||
([pullRequest, repository, viewerAccess]): ProviderChangeRequestDetail => ({
|
||||
...pullRequest,
|
||||
reviewers: pullRequest.reviewRequestLogins.map((login) => ({
|
||||
login,
|
||||
name: null,
|
||||
avatarUrl: null,
|
||||
})),
|
||||
mergeCapabilities: repository.mergeCapabilities,
|
||||
viewerPermissions: gitHubViewerPermissions(viewerAccess),
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
getChangeRequestActivity: (input) =>
|
||||
Effect.all(
|
||||
[
|
||||
cli.getPullRequestActivity(input),
|
||||
// Line comments live on review threads, which `gh pr view --json` cannot reach. A
|
||||
// GraphQL hiccup degrades to a truncated conversation rather than blanking activity.
|
||||
cli.listReviewThreadComments(input).pipe(
|
||||
Effect.orElseSucceed(() => ({
|
||||
comments: [],
|
||||
reviewThreads: [],
|
||||
commentCount: 0,
|
||||
truncated: true,
|
||||
reviewers: [],
|
||||
avatarsByLogin: new Map<string, string>(),
|
||||
commitStats: new Map<
|
||||
string,
|
||||
{ readonly additions: number; readonly deletions: number }
|
||||
>(),
|
||||
commits: [],
|
||||
viewer: { canUpdate: true, didAuthor: false },
|
||||
})),
|
||||
),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
).pipe(
|
||||
Effect.mapError(fail("getChangeRequestActivity")),
|
||||
Effect.map(
|
||||
([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
|
||||
author: withAvatar(pullRequest.author, reviewThreads.avatarsByLogin, input.host),
|
||||
reviewers: reviewThreads.reviewers,
|
||||
commits: (reviewThreads.commits.length > 0
|
||||
? reviewThreads.commits
|
||||
: pullRequest.commits
|
||||
).map((commit) => ({
|
||||
...commit,
|
||||
...reviewThreads.commitStats.get(commit.oid),
|
||||
authors: commit.authors?.map(
|
||||
(author) => withAvatar(author, reviewThreads.avatarsByLogin, input.host) ?? author,
|
||||
),
|
||||
})),
|
||||
comments: [...pullRequest.comments, ...reviewThreads.comments]
|
||||
.map((comment) => ({
|
||||
...comment,
|
||||
author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
|
||||
}))
|
||||
.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
|
||||
// `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
|
||||
// are always whole and only the thread walk can stop short of the host.
|
||||
commentCount: pullRequest.comments.length + reviewThreads.commentCount,
|
||||
commentsTruncated: reviewThreads.truncated,
|
||||
reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
|
||||
...thread,
|
||||
comments: thread.comments.map((comment) => ({
|
||||
...comment,
|
||||
author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
|
||||
})),
|
||||
})),
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
getViewerPermissions: (input) =>
|
||||
cli
|
||||
.getViewerAccess(input)
|
||||
.pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitHubViewerPermissions)),
|
||||
|
||||
getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
|
||||
|
||||
getDiffFileContents: (input) =>
|
||||
cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
|
||||
|
||||
listReviewerCandidates: (input) =>
|
||||
cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
|
||||
|
||||
setReviewerRequest: (input) =>
|
||||
cli
|
||||
.setReviewerRequest({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
host: input.host,
|
||||
number: input.number,
|
||||
reviewers: input.reviewers,
|
||||
requested: input.requested,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("setReviewerRequest"))),
|
||||
|
||||
runAction: (input) =>
|
||||
cli
|
||||
.runPullRequestAction({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
host: input.host,
|
||||
number: input.number,
|
||||
action: input.action,
|
||||
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
|
||||
})
|
||||
.pipe(Effect.mapError(fail("runAction"))),
|
||||
|
||||
comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
|
||||
|
||||
submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
|
||||
|
||||
replyToThread: (input) =>
|
||||
cli
|
||||
.replyToReviewThread({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
host: input.host,
|
||||
threadId: input.threadId,
|
||||
body: input.body,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("replyToThread"))),
|
||||
|
||||
setThreadResolution: (input) =>
|
||||
cli
|
||||
.setReviewThreadResolution({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
host: input.host,
|
||||
threadId: input.threadId,
|
||||
resolved: input.resolved,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("setThreadResolution"))),
|
||||
};
|
||||
|
||||
return provider;
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { gitLabViewerPermissions } from "./GitLabPullRequestProvider.ts";
|
||||
|
||||
describe("gitLabViewerPermissions", () => {
|
||||
it("offers everything to a viewer GitLab says can merge", () => {
|
||||
expect(gitLabViewerPermissions({ viewerCanMerge: true })).toEqual({
|
||||
actions: ["merge", "ready", "draft", "close", "reopen"],
|
||||
comment: true,
|
||||
resolve: true,
|
||||
verdicts: ["comment", "approve"],
|
||||
// GitLab says nothing about who may set a reviewer, and an unreported permission is granted.
|
||||
requestReviewers: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps merge from a viewer GitLab says cannot", () => {
|
||||
// `user.can_merge` already accounts for the role, the approval rules and a protected target
|
||||
// branch, so it is the one answer here that does not have to be inferred.
|
||||
expect(gitLabViewerPermissions({ viewerCanMerge: false })).toEqual({
|
||||
actions: ["ready", "draft", "close", "reopen"],
|
||||
comment: true,
|
||||
resolve: true,
|
||||
verdicts: ["comment", "approve"],
|
||||
requestReviewers: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("treats an author with read access as any other reader, which is all GitLab says", () => {
|
||||
// Its REST API names no relationship between the viewer and the merge request beyond
|
||||
// `can_merge`, so the four an author keeps stay offered to everyone rather than being taken
|
||||
// from the one person entitled to them.
|
||||
expect(gitLabViewerPermissions({ viewerCanMerge: false }).actions).toEqual([
|
||||
"ready",
|
||||
"draft",
|
||||
"close",
|
||||
"reopen",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
|
||||
|
||||
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
|
||||
import {
|
||||
PullRequestProviderError,
|
||||
type ProviderChangeRequestActivity,
|
||||
type ProviderChangeRequestDetail,
|
||||
type PullRequestProviderApi,
|
||||
} from "./PullRequestProvider.ts";
|
||||
|
||||
const CAPABILITIES: PullRequestCapabilities = {
|
||||
diff: true,
|
||||
comment: true,
|
||||
actions: ["merge", "ready", "draft", "close", "reopen"],
|
||||
// GitLab offers all three, though a project settles on one; `mergeCapabilities` narrows it.
|
||||
mergeMethods: ["merge", "squash", "rebase"],
|
||||
search: true,
|
||||
review: {
|
||||
inlineComment: true,
|
||||
reply: true,
|
||||
resolve: true,
|
||||
// No "changes requested": GitLab has approval and unresolved discussions, and nothing that
|
||||
// says a merge request has been reviewed and rejected.
|
||||
verdicts: ["comment", "approve"],
|
||||
},
|
||||
reviewers: { request: true, listCandidates: true },
|
||||
};
|
||||
|
||||
/**
|
||||
* What the signed-in account may do here. GitLab answers exactly one of these questions per
|
||||
* viewer, on the merge request itself: `user.can_merge`, which is why merging is the only thing
|
||||
* narrowed.
|
||||
*
|
||||
* The rest stay granted. GitLab's REST API reports the viewer's role on the project but never
|
||||
* whether they opened this merge request — and its author may close it, reopen it and move it in
|
||||
* and out of draft whatever their role, just as the author of a note may resolve the discussion
|
||||
* it started. Withholding those controls from the one person entitled to them is the worse of the
|
||||
* two mistakes, so they are offered and GitLab explains any refusal itself.
|
||||
*
|
||||
* Asking for a review is granted for the same reason: GitLab takes a reviewer set from the author
|
||||
* and from anyone with the Developer role, and states neither of those two facts here.
|
||||
*/
|
||||
export function gitLabViewerPermissions(input: {
|
||||
readonly viewerCanMerge: boolean;
|
||||
}): PullRequestViewerPermissions {
|
||||
return {
|
||||
actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.viewerCanMerge),
|
||||
comment: true,
|
||||
resolve: true,
|
||||
verdicts: CAPABILITIES.review.verdicts,
|
||||
requestReviewers: true,
|
||||
};
|
||||
}
|
||||
|
||||
/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
|
||||
function reasonFor(
|
||||
error: GitLabPullRequestCli.GitLabPullRequestCliError,
|
||||
): PullRequestProviderError["reason"] {
|
||||
if (error._tag === "GitLabCliUnavailableError") return "missing-tool";
|
||||
if (error._tag === "GitLabCliAuthenticationError") return "unauthenticated";
|
||||
return "failed";
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
|
||||
|
||||
const fail = (operation: string) => (error: GitLabPullRequestCli.GitLabPullRequestCliError) =>
|
||||
new PullRequestProviderError({
|
||||
provider: "gitlab",
|
||||
operation,
|
||||
reason: reasonFor(error),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
});
|
||||
|
||||
const provider: PullRequestProviderApi = {
|
||||
kind: "gitlab",
|
||||
capabilities: CAPABILITIES,
|
||||
|
||||
getViewer: (input) =>
|
||||
cli.getViewerUsername({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
|
||||
|
||||
listChangeRequests: (input) =>
|
||||
cli
|
||||
.listMergeRequests({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
state: input.state,
|
||||
involvement: input.involvement,
|
||||
viewer: input.viewer,
|
||||
limit: input.limit,
|
||||
query: input.query,
|
||||
cursor: input.cursor,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(fail("listChangeRequests")),
|
||||
// GitLab is asked for its merge requests by update, newest first, whether or not it is
|
||||
// being carried on from — so every page it answers is one a cursor can continue.
|
||||
Effect.map((batch) => ({ ...batch, continues: true })),
|
||||
),
|
||||
|
||||
getChangeRequest: (input) =>
|
||||
Effect.all(
|
||||
[
|
||||
cli.getMergeRequestDetail(input),
|
||||
cli.getProjectMergeCapabilities({ cwd: input.cwd, repository: input.repository }),
|
||||
],
|
||||
{ concurrency: 2 },
|
||||
).pipe(
|
||||
Effect.mapError(fail("getChangeRequest")),
|
||||
Effect.map(
|
||||
([mergeRequest, mergeCapabilities]): ProviderChangeRequestDetail => ({
|
||||
...mergeRequest,
|
||||
mergeCapabilities,
|
||||
viewerPermissions: gitLabViewerPermissions(mergeRequest),
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
getChangeRequestActivity: (input) =>
|
||||
Effect.all(
|
||||
[
|
||||
cli
|
||||
.listNotes(input)
|
||||
.pipe(Effect.orElseSucceed(() => ({ comments: [], truncated: true }))),
|
||||
cli.listCommits(input).pipe(Effect.orElseSucceed(() => [])),
|
||||
cli
|
||||
.listDiscussions(input)
|
||||
.pipe(Effect.orElseSucceed(() => ({ threads: [], truncated: true }))),
|
||||
],
|
||||
{ concurrency: 3 },
|
||||
).pipe(
|
||||
Effect.mapError(fail("getChangeRequestActivity")),
|
||||
Effect.map(
|
||||
([notes, commits, discussions]): ProviderChangeRequestActivity => ({
|
||||
comments: notes.comments,
|
||||
// GitLab reports no count of its own, so the walk's own total is the host's: the
|
||||
// notes endpoint carries every comment on the merge request, including the ones
|
||||
// written under a discussion, and it is read until GitLab runs out.
|
||||
commentCount: notes.comments.length,
|
||||
commentsTruncated: notes.truncated || discussions.truncated,
|
||||
reviewThreads: discussions.threads,
|
||||
commits,
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
// The same read the detail takes it from, on its own: `user.can_merge` lives on the merge
|
||||
// request, so there is no cheaper thing to ask GitLab.
|
||||
getViewerPermissions: (input) =>
|
||||
cli
|
||||
.getMergeRequestDetail(input)
|
||||
.pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
|
||||
|
||||
getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
|
||||
|
||||
// Users only: GitLab requests a review of a person, and the groups that can stand in for one
|
||||
// appear in approval rules rather than in a merge request's reviewers.
|
||||
listReviewerCandidates: (input) =>
|
||||
cli
|
||||
.listReviewerCandidates({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("listReviewerCandidates"))),
|
||||
|
||||
setReviewerRequest: (input) =>
|
||||
cli
|
||||
.setReviewerRequest({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
reviewers: input.reviewers,
|
||||
requested: input.requested,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("setReviewerRequest"))),
|
||||
|
||||
runAction: (input) =>
|
||||
cli
|
||||
.runMergeRequestAction({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
action: input.action,
|
||||
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
|
||||
})
|
||||
.pipe(Effect.mapError(fail("runAction"))),
|
||||
|
||||
comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
|
||||
|
||||
submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
|
||||
|
||||
replyToThread: (input) =>
|
||||
cli
|
||||
.replyToDiscussion({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
discussionId: input.threadId,
|
||||
body: input.body,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("replyToThread"))),
|
||||
|
||||
setThreadResolution: (input) =>
|
||||
cli
|
||||
.setDiscussionResolution({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
number: input.number,
|
||||
discussionId: input.threadId,
|
||||
resolved: input.resolved,
|
||||
})
|
||||
.pipe(Effect.mapError(fail("setThreadResolution"))),
|
||||
};
|
||||
|
||||
return provider;
|
||||
});
|
||||
@@ -0,0 +1,387 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type {
|
||||
PullRequestAction,
|
||||
PullRequestActor,
|
||||
PullRequestCapabilities,
|
||||
PullRequestCheck,
|
||||
PullRequestComment,
|
||||
PullRequestCommit,
|
||||
PullRequestInvolvement,
|
||||
PullRequestLabel,
|
||||
PullRequestListState,
|
||||
PullRequestMergeCapabilities,
|
||||
PullRequestMergeMethod,
|
||||
PullRequestMergeability,
|
||||
PullRequestReviewCommentDraft,
|
||||
PullRequestReviewThread,
|
||||
PullRequestReviewVerdict,
|
||||
PullRequestReviewerCandidateList,
|
||||
PullRequestReviewerKind,
|
||||
PullRequestState,
|
||||
PullRequestViewerPermissions,
|
||||
SourceControlProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { SourceControlProviderKind as SourceControlProviderKindSchema } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* The one failure shape every provider reports, so the service can decide what a failure means
|
||||
* without knowing which CLI or API produced it.
|
||||
*
|
||||
* `reason` is the part the service acts on: a missing or unauthenticated tool disables the
|
||||
* provider for the whole workspace, while anything else is specific to the request.
|
||||
*/
|
||||
export class PullRequestProviderError extends Schema.TaggedErrorClass<PullRequestProviderError>()(
|
||||
"PullRequestProviderError",
|
||||
{
|
||||
provider: SourceControlProviderKindSchema,
|
||||
operation: Schema.String,
|
||||
reason: Schema.Literals(["missing-tool", "unauthenticated", "failed"]),
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.provider} failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** A change request as the provider sees it, before the service attaches project context. */
|
||||
export interface ProviderChangeRequest {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly author: PullRequestActor | null;
|
||||
readonly headBranch: string;
|
||||
readonly baseBranch: string;
|
||||
readonly state: PullRequestState;
|
||||
readonly isDraft: boolean;
|
||||
readonly mergeability: PullRequestMergeability;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
/** Accounts with a review requested. Team-level requests are excluded by each provider. */
|
||||
readonly reviewRequestLogins: ReadonlyArray<string>;
|
||||
readonly labels: ReadonlyArray<PullRequestLabel>;
|
||||
}
|
||||
|
||||
export interface ProviderChangeRequestPage {
|
||||
readonly items: ReadonlyArray<ProviderChangeRequest>;
|
||||
/** True when the host has more rows than the page size asked for. */
|
||||
readonly truncated: boolean;
|
||||
/**
|
||||
* Optional count-based cursor advance. Most hosts advance by the rows delivered after local
|
||||
* de-duplication; an offset-paged host may need to count malformed raw rows it consumed too.
|
||||
*/
|
||||
readonly cursorAdvance?: number;
|
||||
/**
|
||||
* This page can be carried on from, so the service may hand the caller a cursor for it. False
|
||||
* where the host answered in an order a cursor means nothing in, which leaves a larger `limit`
|
||||
* as the only way to the rest — what every listing did before there were cursors.
|
||||
*/
|
||||
readonly continues: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a repository's next slice starts, as the provider that has to ask for it needs it. Built
|
||||
* by the service out of the slice it just handed over, so the boundary that decides whether a row
|
||||
* arrives twice or not at all is decided in one place rather than in four.
|
||||
*/
|
||||
export interface ProviderListCursor {
|
||||
/**
|
||||
* The instant of the oldest row already handed over, checked against a timestamp's shape before
|
||||
* it gets here because it goes into a host's own filter. Asked for inclusively: several rows
|
||||
* share one instant often enough — a bot that touches eight change requests writes one timestamp
|
||||
* on all eight — and asking for strictly older would lose whichever of them the slice ended
|
||||
* before. The service drops the ones it has already sent.
|
||||
*/
|
||||
readonly updatedBefore: string;
|
||||
/**
|
||||
* How many provider rows this repository has consumed so far, for a host that carries on by
|
||||
* counting rather than by date. Usually this is the number handed over; malformed raw rows may
|
||||
* count too when the provider reports a `cursorAdvance`.
|
||||
*/
|
||||
readonly delivered: number;
|
||||
}
|
||||
|
||||
/** One repository's row inside an answer that spans several of them. */
|
||||
export interface ProviderBatchedChangeRequest extends ProviderChangeRequest {
|
||||
/** Provider-native identity, exactly as it was asked for, so the caller can file the row. */
|
||||
readonly repository: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One slice of a host read across several repositories at once, newest update first across all
|
||||
* of them. There is no per-repository page here because the host was asked one question: the
|
||||
* caller splits the rows by `repository` and works out where each of them carries on from the
|
||||
* oldest row in the slice, which every repository the slice covers is now read up to.
|
||||
*/
|
||||
export interface ProviderBatchedChangeRequestPage {
|
||||
readonly items: ReadonlyArray<ProviderBatchedChangeRequest>;
|
||||
/** True when the host has more rows than the slice asked for, for any of the repositories. */
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
/** The line counts for one change request, which a listing may leave for a second read. */
|
||||
export interface ProviderChangeRequestStat {
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
|
||||
export interface ProviderChangeRequestDetail extends ProviderChangeRequest {
|
||||
readonly body: string;
|
||||
readonly changedFiles: number;
|
||||
readonly mergedAt: string | null;
|
||||
readonly closedAt: string | null;
|
||||
readonly reviewers: ReadonlyArray<PullRequestActor>;
|
||||
readonly checks: ReadonlyArray<PullRequestCheck>;
|
||||
readonly mergeCapabilities: PullRequestMergeCapabilities;
|
||||
readonly viewerPermissions: PullRequestViewerPermissions;
|
||||
}
|
||||
|
||||
/** The conversation-shaped half of a detail, loaded after the core can already render. */
|
||||
export interface ProviderChangeRequestActivity {
|
||||
/** An optional richer actor, e.g. after GitHub's GraphQL read supplies an avatar. */
|
||||
readonly author?: PullRequestActor | null;
|
||||
/** Optional because most hosts already report their reviewer list in the core detail. */
|
||||
readonly reviewers?: ReadonlyArray<PullRequestActor>;
|
||||
readonly comments: ReadonlyArray<PullRequestComment>;
|
||||
/**
|
||||
* The host's own count of the conversation, which a bounded read can fall short of. A host
|
||||
* that reports no count of its own answers with what it handed over, which is the same number
|
||||
* once the read went to the end.
|
||||
*/
|
||||
readonly commentCount: number;
|
||||
readonly commentsTruncated: boolean;
|
||||
readonly reviewThreads: ReadonlyArray<PullRequestReviewThread>;
|
||||
readonly commits: ReadonlyArray<PullRequestCommit>;
|
||||
}
|
||||
|
||||
export interface ProviderDiffSlice {
|
||||
readonly patch: string;
|
||||
/** Something in this slice could not be shown, as opposed to there being more slices. */
|
||||
readonly truncated: boolean;
|
||||
readonly nextCursor: string | null;
|
||||
}
|
||||
|
||||
export interface ProviderDiffFileContents {
|
||||
readonly oldContents: string;
|
||||
readonly newContents: string;
|
||||
}
|
||||
|
||||
export interface ProviderRepositoryRef {
|
||||
readonly cwd: string;
|
||||
/** Provider-native repository identity, e.g. `owner/repo` or `group/subgroup/project`. */
|
||||
readonly repository: string;
|
||||
/**
|
||||
* The host it lives on, which `repository` deliberately leaves out — the same `owner/repo`
|
||||
* exists on github.com and on a GitHub Enterprise install, and only the caller knows which
|
||||
* one a project's remote points at.
|
||||
*/
|
||||
readonly host: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One host's change requests. Implementations own their own tool and JSON shapes and hand back
|
||||
* the neutral types above; anything a host cannot do is declared in `capabilities` rather than
|
||||
* failing at call time.
|
||||
*/
|
||||
export interface PullRequestProviderApi {
|
||||
readonly kind: SourceControlProviderKind;
|
||||
readonly capabilities: PullRequestCapabilities;
|
||||
|
||||
/** The signed-in account, which is what involvement filtering compares against. */
|
||||
readonly getViewer: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<string, PullRequestProviderError>;
|
||||
|
||||
readonly listChangeRequests: (
|
||||
input: ProviderRepositoryRef & {
|
||||
readonly state: PullRequestListState;
|
||||
readonly involvement: PullRequestInvolvement;
|
||||
readonly viewer: string;
|
||||
readonly limit: number;
|
||||
/**
|
||||
* Free text to narrow the listing by, as the host understands it. A host with no text
|
||||
* filter of its own ignores it and answers with the page it would have answered with
|
||||
* anyway — the caller narrows what it gets, so an unfiltered page is a wider answer
|
||||
* rather than a wrong one.
|
||||
*/
|
||||
readonly query?: string | undefined;
|
||||
/**
|
||||
* Where to carry on from, rather than reading this repository from its newest row. Absent
|
||||
* asks for the first slice, which is every listing that has not been continued.
|
||||
*/
|
||||
readonly cursor?: ProviderListCursor | undefined;
|
||||
},
|
||||
) => Effect.Effect<ProviderChangeRequestPage, PullRequestProviderError>;
|
||||
|
||||
/**
|
||||
* The same listing for a whole host in one request, for a host that has a search across
|
||||
* repositories. Optional: three of the four hosts here have no such API, and breaking the port
|
||||
* for them to spare GitHub a fan-out would be paying for the fix with everyone else's clarity.
|
||||
* The caller falls back to `listChangeRequests` per repository where this is absent, and where
|
||||
* it fails.
|
||||
*
|
||||
* `limit` is the whole slice rather than a size per repository, because that is the shape of
|
||||
* the answer: the newest `limit` rows across every repository named, which is exactly the rows
|
||||
* a page ordered by update shows.
|
||||
*
|
||||
* `cursor` is one boundary for all of them, so a caller with repositories standing at different
|
||||
* boundaries asks in groups rather than in one call.
|
||||
*/
|
||||
readonly listChangeRequestsAcross?: (input: {
|
||||
/** Any checkout on the host, which is what the tool is run in. */
|
||||
readonly cwd: string;
|
||||
readonly host: string;
|
||||
readonly repositories: ReadonlyArray<string>;
|
||||
readonly state: PullRequestListState;
|
||||
readonly involvement: PullRequestInvolvement;
|
||||
readonly viewer: string;
|
||||
readonly limit: number;
|
||||
readonly query?: string | undefined;
|
||||
readonly cursor?: ProviderListCursor | undefined;
|
||||
}) => Effect.Effect<ProviderBatchedChangeRequestPage, PullRequestProviderError>;
|
||||
|
||||
/**
|
||||
* The line counts for rows a listing has already handed over. Only implemented by a provider
|
||||
* whose listing leaves them out — for everyone else the numbers arrived with the row, and the
|
||||
* caller has nothing to ask for.
|
||||
*/
|
||||
readonly listChangeRequestStats?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly host: string;
|
||||
readonly changeRequests: ReadonlyArray<{
|
||||
readonly repository: string;
|
||||
readonly number: number;
|
||||
}>;
|
||||
}) => Effect.Effect<ReadonlyArray<ProviderChangeRequestStat>, PullRequestProviderError>;
|
||||
|
||||
readonly getChangeRequest: (
|
||||
input: ProviderRepositoryRef & { readonly number: number },
|
||||
) => Effect.Effect<ProviderChangeRequestDetail, PullRequestProviderError>;
|
||||
|
||||
/** Comments, line threads, and commits, kept off the critical path for the core detail. */
|
||||
readonly getChangeRequestActivity: (
|
||||
input: ProviderRepositoryRef & { readonly number: number },
|
||||
) => Effect.Effect<ProviderChangeRequestActivity, PullRequestProviderError>;
|
||||
|
||||
/**
|
||||
* The same answer `getChangeRequest` carries, on its own. Asked before anything is written, so
|
||||
* a request that reached the server without going past the page is refused by what the host
|
||||
* says rather than by what the client claimed — and asked freshly, because access granted or
|
||||
* taken away since the page loaded is exactly the case this guards.
|
||||
*
|
||||
* Implementations read the cheapest thing that answers it, which for a host with nothing to say
|
||||
* is no request at all.
|
||||
*/
|
||||
readonly getViewerPermissions: (
|
||||
input: ProviderRepositoryRef & { readonly number: number },
|
||||
) => Effect.Effect<PullRequestViewerPermissions, PullRequestProviderError>;
|
||||
|
||||
/**
|
||||
* One slice of the patch. Only called when `capabilities.diff` is true. A provider that can
|
||||
* serve the whole diff at once answers with `nextCursor: null` and is done; one that pages
|
||||
* hands back whatever it needs to find the next slice.
|
||||
*/
|
||||
readonly getDiff: (
|
||||
input: ProviderRepositoryRef & {
|
||||
readonly number: number;
|
||||
readonly cursor?: string | undefined;
|
||||
/** One commit's own changes, rather than everything the change request carries. */
|
||||
readonly commit?: string | undefined;
|
||||
},
|
||||
) => Effect.Effect<ProviderDiffSlice, PullRequestProviderError>;
|
||||
|
||||
/**
|
||||
* Full files at the exact revisions the host used for its patch. Optional where the provider
|
||||
* exposes no diff at all; the service refuses expansion there just as it refuses the patch.
|
||||
*/
|
||||
readonly getDiffFileContents?: (
|
||||
input: ProviderRepositoryRef & {
|
||||
readonly number: number;
|
||||
readonly commit?: string | undefined;
|
||||
readonly changeType: "change" | "rename-pure" | "rename-changed" | "new" | "deleted";
|
||||
readonly oldPath: string;
|
||||
readonly newPath: string;
|
||||
},
|
||||
) => Effect.Effect<ProviderDiffFileContents, PullRequestProviderError>;
|
||||
|
||||
readonly runAction: (
|
||||
input: ProviderRepositoryRef & {
|
||||
readonly number: number;
|
||||
readonly action: PullRequestAction;
|
||||
readonly mergeMethod?: PullRequestMergeMethod;
|
||||
},
|
||||
) => Effect.Effect<void, PullRequestProviderError>;
|
||||
|
||||
readonly comment: (
|
||||
input: ProviderRepositoryRef & { readonly number: number; readonly body: string },
|
||||
) => Effect.Effect<void, PullRequestProviderError>;
|
||||
|
||||
/**
|
||||
* Sends a whole review at once. Only called for a verdict the host declared in
|
||||
* `capabilities.review.verdicts`, and with line comments only where it declared
|
||||
* `inlineComment`.
|
||||
*/
|
||||
readonly submitReview: (
|
||||
input: ProviderRepositoryRef & {
|
||||
readonly number: number;
|
||||
readonly verdict: PullRequestReviewVerdict;
|
||||
readonly body: string;
|
||||
readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
|
||||
},
|
||||
) => Effect.Effect<void, PullRequestProviderError>;
|
||||
|
||||
/**
|
||||
* The people this viewer may ask for a review, with whoever has already been asked marked as
|
||||
* such. Only called when `capabilities.reviewers.listCandidates` is true.
|
||||
*
|
||||
* The author is left out by each provider rather than by the caller, because only the provider
|
||||
* knows how the host spells the same person in a candidate list and on a pull request.
|
||||
*/
|
||||
readonly listReviewerCandidates: (
|
||||
input: ProviderRepositoryRef & { readonly number: number },
|
||||
) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestProviderError>;
|
||||
|
||||
/**
|
||||
* Asks for a review, or takes the request back. Only called when
|
||||
* `capabilities.reviewers.request` is true.
|
||||
*
|
||||
* One call for both directions, because that is what every host does with them: GitHub posts and
|
||||
* deletes the same collection, and GitLab and Bitbucket write the whole reviewer set either way.
|
||||
* Asking again somebody who has already reviewed is a request like any other — which is how a
|
||||
* re-request is made.
|
||||
*/
|
||||
readonly setReviewerRequest: (
|
||||
input: ProviderRepositoryRef & {
|
||||
readonly number: number;
|
||||
readonly reviewers: ReadonlyArray<{
|
||||
readonly id: string;
|
||||
readonly kind: PullRequestReviewerKind;
|
||||
}>;
|
||||
readonly requested: boolean;
|
||||
},
|
||||
) => Effect.Effect<void, PullRequestProviderError>;
|
||||
|
||||
/** Only called when `capabilities.review.reply` is true. */
|
||||
readonly replyToThread: (
|
||||
input: ProviderRepositoryRef & {
|
||||
readonly number: number;
|
||||
readonly threadId: string;
|
||||
readonly body: string;
|
||||
},
|
||||
) => Effect.Effect<void, PullRequestProviderError>;
|
||||
|
||||
/** Only called when `capabilities.review.resolve` is true. */
|
||||
readonly setThreadResolution: (
|
||||
input: ProviderRepositoryRef & {
|
||||
readonly number: number;
|
||||
readonly threadId: string;
|
||||
readonly resolved: boolean;
|
||||
},
|
||||
) => Effect.Effect<void, PullRequestProviderError>;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type { SourceControlProviderKind } from "@t3tools/contracts";
|
||||
|
||||
import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";
|
||||
import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
|
||||
import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
|
||||
import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
|
||||
import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
|
||||
import * as BitbucketPullRequestProvider from "./BitbucketPullRequestProvider.ts";
|
||||
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
|
||||
import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
|
||||
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
|
||||
import * as GitLabPullRequestProvider from "./GitLabPullRequestProvider.ts";
|
||||
import type { PullRequestProviderApi } from "./PullRequestProvider.ts";
|
||||
|
||||
export class PullRequestProviderRegistry extends Context.Service<
|
||||
PullRequestProviderRegistry,
|
||||
{
|
||||
/** Null for a host with no implementation, which the service reports as unsupported. */
|
||||
readonly get: (kind: SourceControlProviderKind) => PullRequestProviderApi | null;
|
||||
readonly kinds: ReadonlyArray<SourceControlProviderKind>;
|
||||
}
|
||||
>()("t3/pullRequest/PullRequestProviderRegistry") {}
|
||||
|
||||
/** Exported for tests, which stand a registry up from providers they supply themselves. */
|
||||
export function fromProviders(
|
||||
providers: ReadonlyArray<PullRequestProviderApi>,
|
||||
): PullRequestProviderRegistry["Service"] {
|
||||
const byKind = new Map(providers.map((provider) => [provider.kind, provider]));
|
||||
return {
|
||||
get: (kind) => byKind.get(kind) ?? null,
|
||||
kinds: providers.map((provider) => provider.kind),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The hosts this build can read change requests from. A host with no entry here still shows up
|
||||
* in the provider list as unimplemented, so its projects are explained rather than missing.
|
||||
*/
|
||||
export const make = Effect.map(
|
||||
Effect.all([
|
||||
GitHubPullRequestProvider.make,
|
||||
GitLabPullRequestProvider.make,
|
||||
BitbucketPullRequestProvider.make,
|
||||
AzureDevOpsPullRequestProvider.make,
|
||||
]),
|
||||
fromProviders,
|
||||
);
|
||||
|
||||
export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(
|
||||
Layer.provide(GitHubPullRequestCli.layer.pipe(Layer.provide(GitHubCli.layer))),
|
||||
Layer.provide(GitLabPullRequestCli.layer.pipe(Layer.provide(GitLabCli.layer))),
|
||||
Layer.provide(BitbucketPullRequestApi.layer.pipe(Layer.provide(BitbucketApi.layer))),
|
||||
Layer.provide(AzureDevOpsPullRequestCli.layer.pipe(Layer.provide(AzureDevOpsCli.layer))),
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,300 @@
|
||||
import * as Result from "effect/Result";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
decodePullRequestJson,
|
||||
decodePullRequestListJson,
|
||||
decodeThreadsJson,
|
||||
decodeViewerJson,
|
||||
} from "./azureDevOpsPullRequestJson.ts";
|
||||
|
||||
const REST_URL =
|
||||
"https://dev.azure.com/acme/_apis/git/repositories/6f9c9b7f-0000-0000-0000-000000000000/pullRequests/42";
|
||||
|
||||
/** Shaped after Azure's `GitPullRequest`, trimmed to the fields that are read. */
|
||||
function pullRequest(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
pullRequestId: 42,
|
||||
title: "Add the change requests page",
|
||||
description: "Ships the page.",
|
||||
status: "active",
|
||||
isDraft: false,
|
||||
mergeStatus: "succeeded",
|
||||
createdBy: { displayName: "Bilal Hassan", uniqueName: "[email protected]" },
|
||||
sourceRefName: "refs/heads/feat/page",
|
||||
targetRefName: "refs/heads/main",
|
||||
creationDate: "2026-07-01T00:00:00Z",
|
||||
url: REST_URL,
|
||||
repository: { name: "web", project: { name: "platform" } },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function expectSuccess<A>(result: Result.Result<A, unknown>): A {
|
||||
expect(Result.isSuccess(result)).toBe(true);
|
||||
if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
|
||||
return result.success;
|
||||
}
|
||||
|
||||
const asJson = (value: unknown) => JSON.stringify(value);
|
||||
|
||||
describe("decodePullRequestListJson", () => {
|
||||
it("reads a pull request as a change request", () => {
|
||||
const batch = expectSuccess(decodePullRequestListJson(asJson([pullRequest()])));
|
||||
|
||||
expect(batch.items).toHaveLength(1);
|
||||
expect(batch.items[0]).toMatchObject({
|
||||
number: 42,
|
||||
title: "Add the change requests page",
|
||||
// The login is an email, because that is what `az account show` reports to compare with.
|
||||
author: { login: "[email protected]", name: "Bilal Hassan" },
|
||||
// Azure prefixes its refs, which no other host does.
|
||||
headBranch: "feat/page",
|
||||
baseBranch: "main",
|
||||
state: "open",
|
||||
isDraft: false,
|
||||
mergeability: "mergeable",
|
||||
});
|
||||
});
|
||||
|
||||
it("assembles a browser url when Azure reports no web link", () => {
|
||||
const batch = expectSuccess(decodePullRequestListJson(asJson([pullRequest()])));
|
||||
|
||||
expect(batch.items[0]?.url).toBe("https://dev.azure.com/acme/platform/_git/web/pullrequest/42");
|
||||
});
|
||||
|
||||
it("prefers the web link Azure sends when asked for one", () => {
|
||||
const batch = expectSuccess(
|
||||
decodePullRequestListJson(
|
||||
asJson([
|
||||
pullRequest({
|
||||
_links: {
|
||||
web: { href: "https://dev.azure.com/acme/platform/_git/web/pullrequest/42" },
|
||||
},
|
||||
}),
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(batch.items[0]?.url).toBe("https://dev.azure.com/acme/platform/_git/web/pullrequest/42");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["active", "open"],
|
||||
["completed", "merged"],
|
||||
["abandoned", "closed"],
|
||||
["something new", "open"],
|
||||
])("reads the %s status as %s", (status, expected) => {
|
||||
const batch = expectSuccess(decodePullRequestListJson(asJson([pullRequest({ status })])));
|
||||
|
||||
expect(batch.items[0]?.state).toBe(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["succeeded", "mergeable"],
|
||||
["conflicts", "conflicting"],
|
||||
["rejectedByPolicy", "conflicting"],
|
||||
["queued", "unknown"],
|
||||
["notSet", "unknown"],
|
||||
])("reads the %s merge status as %s", (mergeStatus, expected) => {
|
||||
const batch = expectSuccess(decodePullRequestListJson(asJson([pullRequest({ mergeStatus })])));
|
||||
|
||||
expect(batch.items[0]?.mergeability).toBe(expected);
|
||||
});
|
||||
|
||||
it("stands the closing time in for a last-touched time Azure does not keep", () => {
|
||||
const batch = expectSuccess(
|
||||
decodePullRequestListJson(
|
||||
asJson([pullRequest({ status: "completed", closedDate: "2026-07-05T00:00:00Z" })]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(batch.items[0]).toMatchObject({
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
updatedAt: "2026-07-05T00:00:00Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("skips a malformed row but still counts it, so paging does not stop early", () => {
|
||||
const batch = expectSuccess(
|
||||
decodePullRequestListJson(asJson([{ pullRequestId: "nope" }, pullRequest()])),
|
||||
);
|
||||
|
||||
expect(batch.items).toHaveLength(1);
|
||||
expect(batch.rawCount).toBe(2);
|
||||
expect(batch.rawIndexes).toEqual([1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodePullRequestJson", () => {
|
||||
it("reads reviewers as review requests", () => {
|
||||
const detail = expectSuccess(
|
||||
decodePullRequestJson(
|
||||
asJson(
|
||||
pullRequest({
|
||||
reviewers: [{ displayName: "Julius", uniqueName: "[email protected]", vote: 10 }],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(detail?.reviewRequestLogins).toEqual(["[email protected]"]);
|
||||
expect(detail?.reviewers).toEqual([
|
||||
{ login: "[email protected]", name: "Julius", avatarUrl: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it("works out where the conversation lives from what Azure returned", () => {
|
||||
const detail = expectSuccess(decodePullRequestJson(asJson(pullRequest())));
|
||||
|
||||
expect(detail?.threadsUrl).toBe(
|
||||
"https://dev.azure.com/acme/platform/_apis/git/repositories/web/pullRequests/42/threads",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports no conversation url when Azure said too little to build one", () => {
|
||||
// A web link places the pull request, but without the REST url and repository there is
|
||||
// nothing to hang a threads collection off.
|
||||
const detail = expectSuccess(
|
||||
decodePullRequestJson(
|
||||
asJson(
|
||||
pullRequest({
|
||||
url: null,
|
||||
repository: null,
|
||||
_links: {
|
||||
web: { href: "https://dev.azure.com/acme/platform/_git/web/pullrequest/42" },
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(detail?.threadsUrl).toBeNull();
|
||||
});
|
||||
|
||||
it("returns nothing when Azure gave no way to place the pull request at all", () => {
|
||||
const detail = expectSuccess(
|
||||
decodePullRequestJson(asJson(pullRequest({ url: null, repository: null }))),
|
||||
);
|
||||
|
||||
expect(detail).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeViewerJson", () => {
|
||||
it("reads the signed-in account name", () => {
|
||||
expect(expectSuccess(decodeViewerJson(asJson({ user: { name: "[email protected]" } })))).toBe(
|
||||
"[email protected]",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns nothing when nobody is signed in", () => {
|
||||
expect(expectSuccess(decodeViewerJson(asJson({ user: null })))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeThreadsJson", () => {
|
||||
it("takes every real comment of every thread, oldest first", () => {
|
||||
const comments = expectSuccess(
|
||||
decodeThreadsJson(
|
||||
asJson({
|
||||
value: [
|
||||
{
|
||||
id: 2,
|
||||
comments: [
|
||||
{
|
||||
id: 1,
|
||||
content: "Second remark.",
|
||||
author: { displayName: "Julius", uniqueName: "[email protected]" },
|
||||
publishedDate: "2026-07-03T00:00:00Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
comments: [
|
||||
// Azure's own activity notes are events rather than remarks.
|
||||
{ id: 1, content: "Bilal voted", commentType: "system", publishedDate: "x" },
|
||||
{
|
||||
id: 2,
|
||||
content: "First remark.",
|
||||
author: { displayName: "Bilal", uniqueName: "[email protected]" },
|
||||
publishedDate: "2026-07-02T00:00:00Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(comments.map((comment) => comment.body)).toEqual(["First remark.", "Second remark."]);
|
||||
expect(comments[0]).toMatchObject({
|
||||
kind: "issue-comment",
|
||||
author: { login: "[email protected]" },
|
||||
});
|
||||
});
|
||||
|
||||
it("reads a thread pinned to a file as a review comment", () => {
|
||||
const comments = expectSuccess(
|
||||
decodeThreadsJson(
|
||||
asJson({
|
||||
value: [
|
||||
{
|
||||
id: 3,
|
||||
threadContext: { filePath: "/src/app.ts" },
|
||||
comments: [{ id: 1, content: "Rename this.", publishedDate: "2026-07-02T00:00:00Z" }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(comments[0]).toMatchObject({ kind: "review-comment", path: "/src/app.ts" });
|
||||
});
|
||||
|
||||
it("keeps the replies under a thread, which are as much of the conversation", () => {
|
||||
const comments = expectSuccess(
|
||||
decodeThreadsJson(
|
||||
asJson({
|
||||
value: [
|
||||
{
|
||||
id: 4,
|
||||
threadContext: { filePath: "/src/app.ts" },
|
||||
comments: [
|
||||
{ id: 1, content: "Rename this.", publishedDate: "2026-07-02T00:00:00Z" },
|
||||
{ id: 2, content: "Renamed.", publishedDate: "2026-07-02T01:00:00Z" },
|
||||
{ id: 3, content: "Thanks.", publishedDate: "2026-07-02T02:00:00Z" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(comments.map((comment) => comment.id)).toEqual(["4:1", "4:2", "4:3"]);
|
||||
});
|
||||
|
||||
it("drops deleted threads and threads with nothing to show", () => {
|
||||
const comments = expectSuccess(
|
||||
decodeThreadsJson(
|
||||
asJson({
|
||||
value: [
|
||||
{
|
||||
id: 1,
|
||||
isDeleted: true,
|
||||
comments: [{ id: 1, content: "gone", publishedDate: "2026-07-02T00:00:00Z" }],
|
||||
},
|
||||
{ id: 2, comments: [] },
|
||||
{
|
||||
id: 3,
|
||||
comments: [{ id: 1, content: " ", publishedDate: "2026-07-02T00:00:00Z" }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(comments).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,333 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type {
|
||||
PullRequestActor,
|
||||
PullRequestComment,
|
||||
PullRequestMergeability,
|
||||
PullRequestState,
|
||||
} from "@t3tools/contracts";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import {
|
||||
azureDevOpsOrganizationBaseFromRestApiUrl,
|
||||
azureDevOpsPullRequestWebUrl,
|
||||
} from "../sourceControl/azureDevOpsPullRequests.ts";
|
||||
|
||||
/**
|
||||
* Azure's enums are decoded as plain strings and normalized here, in the same tolerant style as
|
||||
* the other hosts: a new merge status must not fail a whole payload. Every field beyond the
|
||||
* identity is optional, because `az repos pr` returns rather more or less of the REST object
|
||||
* depending on the command.
|
||||
*/
|
||||
const RawIdentitySchema = Schema.Struct({
|
||||
displayName: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
/** An email or UPN, which is what `az account show` reports for the signed-in user. */
|
||||
uniqueName: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
const RawPullRequestSchema = Schema.Struct({
|
||||
pullRequestId: Schema.Int,
|
||||
title: Schema.String,
|
||||
description: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
status: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isDraft: Schema.optional(Schema.NullOr(Schema.Boolean)),
|
||||
mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
|
||||
reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
|
||||
// Required, and required to be non-empty: the wire contract will not carry a change request
|
||||
// without a branch or a created time, so a row missing one is skipped rather than breaking the
|
||||
// response it travels in.
|
||||
sourceRefName: TrimmedNonEmptyString,
|
||||
targetRefName: TrimmedNonEmptyString,
|
||||
creationDate: TrimmedNonEmptyString,
|
||||
closedDate: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
url: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
repository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
webUrl: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
project: Schema.optional(
|
||||
Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
_links: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
web: Schema.optional(
|
||||
Schema.NullOr(Schema.Struct({ href: Schema.optional(Schema.String) })),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
/** A pull request thread, which is how Azure keeps its conversation. */
|
||||
const RawThreadSchema = Schema.Struct({
|
||||
id: Schema.Int,
|
||||
isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
|
||||
threadContext: Schema.optional(
|
||||
Schema.NullOr(Schema.Struct({ filePath: Schema.optional(Schema.NullOr(Schema.String)) })),
|
||||
),
|
||||
comments: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
id: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
content: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
author: Schema.optional(Schema.NullOr(RawIdentitySchema)),
|
||||
publishedDate: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
|
||||
/** `system` marks the notes Azure writes itself, which are events, not comments. */
|
||||
commentType: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawThreadPageSchema = Schema.Struct({
|
||||
value: Schema.Array(Schema.Unknown),
|
||||
});
|
||||
|
||||
const RawViewerSchema = Schema.Struct({
|
||||
user: Schema.optional(
|
||||
Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
|
||||
),
|
||||
});
|
||||
|
||||
export interface AzureDevOpsPullRequest {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly author: PullRequestActor | null;
|
||||
readonly headBranch: string;
|
||||
readonly baseBranch: string;
|
||||
readonly state: PullRequestState;
|
||||
readonly isDraft: boolean;
|
||||
readonly mergeability: PullRequestMergeability;
|
||||
readonly createdAt: string;
|
||||
/**
|
||||
* Azure records no last-touched time on a pull request, so the closing time stands in where
|
||||
* there is one and the creation time otherwise. The same fallback the rest of the app uses.
|
||||
*/
|
||||
readonly updatedAt: string;
|
||||
readonly closedAt: string | null;
|
||||
readonly body: string;
|
||||
readonly reviewRequestLogins: ReadonlyArray<string>;
|
||||
readonly reviewers: ReadonlyArray<PullRequestActor>;
|
||||
/** Where this pull request's threads live, when Azure said enough to work it out. */
|
||||
readonly threadsUrl: string | null;
|
||||
}
|
||||
|
||||
function trimmed(value: string | null | undefined): string | null {
|
||||
const text = value?.trim() ?? "";
|
||||
return text.length > 0 ? text : null;
|
||||
}
|
||||
|
||||
function normalizeRefName(refName: string): string {
|
||||
return refName.trim().replace(/^refs\/heads\//, "");
|
||||
}
|
||||
|
||||
/** A login has to compare against `az account show`, which reports an email. */
|
||||
function toActor(raw: Schema.Schema.Type<typeof RawIdentitySchema> | null | undefined) {
|
||||
const login = trimmed(raw?.uniqueName) ?? trimmed(raw?.displayName);
|
||||
return login === null
|
||||
? null
|
||||
: { login, name: trimmed(raw?.displayName), avatarUrl: trimmed(raw?.imageUrl) };
|
||||
}
|
||||
|
||||
function toState(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): PullRequestState {
|
||||
switch (raw.status?.trim().toLowerCase()) {
|
||||
case "completed":
|
||||
return "merged";
|
||||
case "abandoned":
|
||||
return "closed";
|
||||
default:
|
||||
return "open";
|
||||
}
|
||||
}
|
||||
|
||||
function toMergeability(value: string | null | undefined): PullRequestMergeability {
|
||||
switch (value?.trim().toLowerCase()) {
|
||||
case "succeeded":
|
||||
return "mergeable";
|
||||
case "conflicts":
|
||||
case "failure":
|
||||
case "rejectedbypolicy":
|
||||
return "conflicting";
|
||||
default:
|
||||
// `queued` and `notSet` mean Azure has not finished checking.
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The REST collection a pull request's threads hang from. Built from what Azure returned rather
|
||||
* than from the local remote, whose shape differs between the modern, legacy and SSH forms.
|
||||
*/
|
||||
function toThreadsUrl(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): string | null {
|
||||
const base = azureDevOpsOrganizationBaseFromRestApiUrl(raw.url);
|
||||
const project = trimmed(raw.repository?.project?.name);
|
||||
const repository = trimmed(raw.repository?.name);
|
||||
if (base === null || project === null || repository === null) return null;
|
||||
return `${base}/${encodeURIComponent(project)}/_apis/git/repositories/${encodeURIComponent(repository)}/pullRequests/${raw.pullRequestId}/threads`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Null when Azure said too little to place the pull request: a row with no browser url and no
|
||||
* branch left after its prefix is dropped cannot be rendered or opened, and the wire contract
|
||||
* refuses to carry it either.
|
||||
*/
|
||||
function toPullRequest(
|
||||
raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
|
||||
): AzureDevOpsPullRequest | null {
|
||||
const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
|
||||
const actor = toActor(reviewer);
|
||||
return actor === null ? [] : [actor];
|
||||
});
|
||||
const closedAt = trimmed(raw.closedDate);
|
||||
const url = trimmed(
|
||||
azureDevOpsPullRequestWebUrl({
|
||||
pullRequestId: raw.pullRequestId,
|
||||
webLink: raw._links?.web?.href,
|
||||
repositoryWebUrl: raw.repository?.webUrl,
|
||||
restApiUrl: raw.url,
|
||||
projectName: raw.repository?.project?.name,
|
||||
repositoryName: raw.repository?.name,
|
||||
}),
|
||||
);
|
||||
const headBranch = trimmed(normalizeRefName(raw.sourceRefName));
|
||||
const baseBranch = trimmed(normalizeRefName(raw.targetRefName));
|
||||
if (url === null || headBranch === null || baseBranch === null) return null;
|
||||
return {
|
||||
number: raw.pullRequestId,
|
||||
title: raw.title,
|
||||
url,
|
||||
author: toActor(raw.createdBy),
|
||||
headBranch,
|
||||
baseBranch,
|
||||
state: toState(raw),
|
||||
isDraft: raw.isDraft ?? false,
|
||||
mergeability: toMergeability(raw.mergeStatus),
|
||||
createdAt: raw.creationDate,
|
||||
updatedAt: closedAt ?? raw.creationDate,
|
||||
closedAt,
|
||||
body: raw.description ?? "",
|
||||
reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
|
||||
reviewers,
|
||||
threadsUrl: toThreadsUrl(raw),
|
||||
};
|
||||
}
|
||||
|
||||
const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
|
||||
const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
|
||||
const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
|
||||
const decodeThreadPage = decodeJsonResult(RawThreadPageSchema);
|
||||
const decodeThreadEntry = Schema.decodeUnknownExit(RawThreadSchema);
|
||||
const decodeViewer = decodeJsonResult(RawViewerSchema);
|
||||
|
||||
type DecodeFailure = Cause.Cause<Schema.SchemaError>;
|
||||
|
||||
export interface AzureDevOpsPullRequestBatch {
|
||||
readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
|
||||
/** Zero-based positions of the decoded items in Azure's raw page. */
|
||||
readonly rawIndexes: ReadonlyArray<number>;
|
||||
/** Rows Azure returned, counted before decoding, so a skipped row cannot hide a next page. */
|
||||
readonly rawCount: number;
|
||||
}
|
||||
|
||||
/** Malformed entries are skipped rather than failing the batch, as on the other hosts. */
|
||||
export function decodePullRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<AzureDevOpsPullRequestBatch, DecodeFailure> {
|
||||
const decoded = decodeUnknownList(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const items: AzureDevOpsPullRequest[] = [];
|
||||
const rawIndexes: number[] = [];
|
||||
for (const [rawIndex, entry] of decoded.success.entries()) {
|
||||
const item = decodePullRequestEntry(entry);
|
||||
if (Exit.isFailure(item)) continue;
|
||||
const pullRequest = toPullRequest(item.value);
|
||||
if (pullRequest !== null) {
|
||||
items.push(pullRequest);
|
||||
rawIndexes.push(rawIndex);
|
||||
}
|
||||
}
|
||||
return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
|
||||
}
|
||||
|
||||
/** Null carries "Azure answered, but with too little to use", which the caller reports. */
|
||||
export function decodePullRequestJson(
|
||||
raw: string,
|
||||
): Result.Result<AzureDevOpsPullRequest | null, DecodeFailure> {
|
||||
const decoded = decodePullRequest(raw);
|
||||
return Result.isSuccess(decoded)
|
||||
? Result.succeed(toPullRequest(decoded.success))
|
||||
: Result.fail(decoded.failure);
|
||||
}
|
||||
|
||||
/** `az account show --query user` reports the signed-in account, whose name is an email. */
|
||||
export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
|
||||
const decoded = decodeViewer(raw);
|
||||
return Result.isSuccess(decoded)
|
||||
? Result.succeed(trimmed(decoded.success.user?.name))
|
||||
: Result.fail(decoded.failure);
|
||||
}
|
||||
|
||||
/**
|
||||
* Azure keeps its conversation as threads of comments, and every one of them is a remark
|
||||
* somebody wrote: a reply under a thread is as much of the conversation as the line that opened
|
||||
* it. A thread pinned to a file is a line-level review comment.
|
||||
*
|
||||
* Azure answers the whole thread collection in one response, with no cursor and no page to
|
||||
* follow, so what this returns is everything the host has.
|
||||
*/
|
||||
export function decodeThreadsJson(
|
||||
raw: string,
|
||||
): Result.Result<ReadonlyArray<PullRequestComment>, DecodeFailure> {
|
||||
const decoded = decodeThreadPage(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const comments: PullRequestComment[] = [];
|
||||
for (const entry of decoded.success.value) {
|
||||
const decodedThread = decodeThreadEntry(entry);
|
||||
if (Exit.isFailure(decodedThread)) continue;
|
||||
const thread = decodedThread.value;
|
||||
if (thread.isDeleted === true) continue;
|
||||
const path = trimmed(thread.threadContext?.filePath);
|
||||
for (const comment of thread.comments ?? []) {
|
||||
const publishedDate = trimmed(comment.publishedDate);
|
||||
if (
|
||||
comment.isDeleted === true ||
|
||||
comment.commentType?.trim().toLowerCase() === "system" ||
|
||||
(comment.content ?? "").trim().length === 0 ||
|
||||
publishedDate === null
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
comments.push({
|
||||
id: `${thread.id}:${comment.id ?? 0}`,
|
||||
kind: path === null ? "issue-comment" : "review-comment",
|
||||
author: toActor(comment.author),
|
||||
body: comment.content ?? "",
|
||||
createdAt: publishedDate,
|
||||
url: null,
|
||||
path,
|
||||
reviewState: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
return Result.succeed(
|
||||
comments.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import * as Result from "effect/Result";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
decodeCommentsJson,
|
||||
decodeCommitsJson,
|
||||
decodeConflictsJson,
|
||||
decodeDiffstatJson,
|
||||
decodePullRequestJson,
|
||||
decodePullRequestPageJson,
|
||||
decodeRepositoryPermissionJson,
|
||||
decodeStatusesJson,
|
||||
decodeViewerJson,
|
||||
} from "./bitbucketPullRequestJson.ts";
|
||||
|
||||
/** Shaped after a real api.bitbucket.org pull request, trimmed to the fields that are read. */
|
||||
function pullRequest(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
id: 897,
|
||||
title: "Add trustabl-pipe",
|
||||
description: "# Add trustabl-pipe",
|
||||
state: "OPEN",
|
||||
draft: false,
|
||||
created_on: "2026-06-16T05:04:32.258456+00:00",
|
||||
updated_on: "2026-06-16T05:04:33.750542+00:00",
|
||||
author: { display_name: "Bilal Hassan", nickname: "bilal", type: "user" },
|
||||
source: { branch: { name: "feat/page" } },
|
||||
destination: { branch: { name: "master" } },
|
||||
links: { html: { href: "https://bitbucket.org/acme/web/pull-requests/897" } },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function page(values: ReadonlyArray<unknown>, extra: Record<string, unknown> = {}): string {
|
||||
return JSON.stringify({ pagelen: 50, page: 1, size: values.length, values, ...extra });
|
||||
}
|
||||
|
||||
function expectSuccess<A>(result: Result.Result<A, unknown>): A {
|
||||
expect(Result.isSuccess(result)).toBe(true);
|
||||
if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
|
||||
return result.success;
|
||||
}
|
||||
|
||||
describe("decodePullRequestPageJson", () => {
|
||||
it("reads a pull request as a change request", () => {
|
||||
const decoded = expectSuccess(decodePullRequestPageJson(page([pullRequest()])));
|
||||
|
||||
expect(decoded.items).toHaveLength(1);
|
||||
expect(decoded.items[0]).toMatchObject({
|
||||
number: 897,
|
||||
title: "Add trustabl-pipe",
|
||||
url: "https://bitbucket.org/acme/web/pull-requests/897",
|
||||
author: { login: "bilal", name: "Bilal Hassan" },
|
||||
headBranch: "feat/page",
|
||||
baseBranch: "master",
|
||||
state: "open",
|
||||
isDraft: false,
|
||||
// Bitbucket says nothing about conflicts on the pull request itself.
|
||||
mergeability: "unknown",
|
||||
});
|
||||
expect(decoded.next).toBeNull();
|
||||
});
|
||||
|
||||
it("normalizes Bitbucket's offset timestamps, which the page sorts against other hosts", () => {
|
||||
const decoded = expectSuccess(decodePullRequestPageJson(page([pullRequest()])));
|
||||
|
||||
expect(decoded.items[0]).toMatchObject({
|
||||
createdAt: "2026-06-16T05:04:32.258Z",
|
||||
updatedAt: "2026-06-16T05:04:33.750Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports the next page as the whole URL Bitbucket sends", () => {
|
||||
const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
|
||||
const decoded = expectSuccess(decodePullRequestPageJson(page([pullRequest()], { next })));
|
||||
|
||||
expect(decoded.next).toBe(next);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["MERGED", "merged"],
|
||||
["DECLINED", "closed"],
|
||||
["SUPERSEDED", "closed"],
|
||||
["OPEN", "open"],
|
||||
["something new", "open"],
|
||||
])("reads the %s state as %s", (state, expected) => {
|
||||
const decoded = expectSuccess(decodePullRequestPageJson(page([pullRequest({ state })])));
|
||||
|
||||
expect(decoded.items[0]?.state).toBe(expected);
|
||||
});
|
||||
|
||||
it("skips a malformed row rather than failing the page", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodePullRequestPageJson(page([{ id: "not a number" }, pullRequest()])),
|
||||
);
|
||||
|
||||
expect(decoded.items).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("fails when Bitbucket did not answer with a page", () => {
|
||||
expect(Result.isFailure(decodePullRequestPageJson(JSON.stringify({ error: "nope" })))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodePullRequestJson", () => {
|
||||
it("reads reviewers as review requests", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodePullRequestJson(
|
||||
JSON.stringify(
|
||||
pullRequest({
|
||||
reviewers: [{ nickname: "julius", display_name: "Julius" }],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(decoded.reviewRequestLogins).toEqual(["julius"]);
|
||||
expect(decoded.reviewers).toEqual([{ login: "julius", name: "Julius", avatarUrl: null }]);
|
||||
});
|
||||
|
||||
it("reads a participant's vote as a review", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodePullRequestJson(
|
||||
JSON.stringify(
|
||||
pullRequest({
|
||||
participants: [
|
||||
{
|
||||
user: { nickname: "julius", display_name: "Julius" },
|
||||
role: "REVIEWER",
|
||||
approved: true,
|
||||
state: "approved",
|
||||
participated_on: "2026-06-17T09:00:00+00:00",
|
||||
},
|
||||
// Added as a reviewer but has not voted, so there is no verdict to show.
|
||||
{
|
||||
user: { nickname: "sam", display_name: "Sam" },
|
||||
role: "REVIEWER",
|
||||
approved: false,
|
||||
state: null,
|
||||
participated_on: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(decoded.reviews).toHaveLength(1);
|
||||
expect(decoded.reviews[0]).toMatchObject({
|
||||
kind: "review",
|
||||
author: { login: "julius" },
|
||||
reviewState: "approved",
|
||||
createdAt: "2026-06-17T09:00:00.000Z",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeViewerJson", () => {
|
||||
it("reads the signed-in nickname", () => {
|
||||
const decoded = decodeViewerJson(JSON.stringify({ nickname: "bilal", display_name: "Bilal" }));
|
||||
|
||||
expect(expectSuccess(decoded)).toBe("bilal");
|
||||
});
|
||||
|
||||
it("falls back to the display name, which app accounts have instead", () => {
|
||||
const decoded = decodeViewerJson(JSON.stringify({ display_name: "Release Bot" }));
|
||||
|
||||
expect(expectSuccess(decoded)).toBe("Release Bot");
|
||||
});
|
||||
|
||||
it("returns nothing when the account has neither", () => {
|
||||
expect(expectSuccess(decodeViewerJson(JSON.stringify({})))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeCommentsJson", () => {
|
||||
it("keeps a posted comment and drops deleted and unposted ones", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodeCommentsJson(
|
||||
page([
|
||||
{
|
||||
id: 797230941,
|
||||
content: { raw: "The issue is ready for review." },
|
||||
user: { display_name: "Release Bot", type: "app_user" },
|
||||
created_on: "2026-05-15T01:58:38.220690+00:00",
|
||||
deleted: false,
|
||||
pending: false,
|
||||
links: { html: { href: "https://bitbucket.org/acme/web/pull-requests/892#c1" } },
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
content: { raw: "gone" },
|
||||
created_on: "2026-05-15T02:00:00+00:00",
|
||||
deleted: true,
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
content: { raw: "wip" },
|
||||
created_on: "2026-05-15T02:00:00+00:00",
|
||||
pending: true,
|
||||
},
|
||||
{ id: 4, content: { raw: " " }, created_on: "2026-05-15T02:00:00+00:00" },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(decoded.comments).toHaveLength(1);
|
||||
expect(decoded.comments[0]).toMatchObject({
|
||||
id: "797230941",
|
||||
kind: "issue-comment",
|
||||
// An app account has no nickname, so its display name is the only handle it has.
|
||||
author: { login: "Release Bot" },
|
||||
createdAt: "2026-05-15T01:58:38.220Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("reads a comment pinned to a file as a review comment", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodeCommentsJson(
|
||||
page([
|
||||
{
|
||||
id: 5,
|
||||
content: { raw: "Rename this." },
|
||||
created_on: "2026-05-15T02:00:00+00:00",
|
||||
inline: { path: "src/app.ts" },
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(decoded.comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeCommitsJson", () => {
|
||||
it("returns commits oldest first with only the subject line", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodeCommitsJson(
|
||||
page([
|
||||
{ hash: "bbb", message: "second\n\nbody text\n", date: "2026-06-16T04:51:00+00:00" },
|
||||
{
|
||||
hash: "aaa",
|
||||
message: "first\n",
|
||||
date: "2026-06-16T04:50:49+00:00",
|
||||
author: {
|
||||
raw: "Ada Lovelace <[email protected]>",
|
||||
user: { nickname: "ada", display_name: "Ada Lovelace" },
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(decoded.items.map((commit) => commit.oid)).toEqual(["aaa", "bbb"]);
|
||||
expect(decoded.items[0]?.authors).toEqual([
|
||||
{ login: "ada", name: "Ada Lovelace", avatarUrl: null },
|
||||
]);
|
||||
expect(decoded.items[1]?.messageHeadline).toBe("second");
|
||||
expect(decoded.next).toBeNull();
|
||||
});
|
||||
|
||||
it("skips commits whose hash is empty", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodeCommitsJson(
|
||||
page([
|
||||
{ hash: " ", message: "invalid", date: "2026-06-16T04:51:00+00:00" },
|
||||
{ hash: "aaa", date: "2026-06-16T04:50:49+00:00" },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(decoded.items.map((commit) => commit.oid)).toEqual(["aaa"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeStatusesJson", () => {
|
||||
it("reads a build status as a check", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodeStatusesJson(
|
||||
page([
|
||||
{
|
||||
key: "custom:check-version-and-pr",
|
||||
name: "Pipeline - custom: check-version-and-pr",
|
||||
state: "SUCCESSFUL",
|
||||
description: "",
|
||||
url: "https://bitbucket.org/acme/web/pipelines/results/8126",
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(decoded).toEqual({
|
||||
items: [
|
||||
{
|
||||
name: "Pipeline - custom: check-version-and-pr",
|
||||
status: "success",
|
||||
description: null,
|
||||
url: "https://bitbucket.org/acme/web/pipelines/results/8126",
|
||||
},
|
||||
],
|
||||
next: null,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["SUCCESSFUL", "success"],
|
||||
["FAILED", "failure"],
|
||||
["INPROGRESS", "pending"],
|
||||
["STOPPED", "cancelled"],
|
||||
["something new", "neutral"],
|
||||
])("reads the %s build state as %s", (state, expected) => {
|
||||
const decoded = expectSuccess(decodeStatusesJson(page([{ name: "Pipeline", state }])));
|
||||
|
||||
expect(decoded.items[0]?.status).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeDiffstatJson", () => {
|
||||
it("adds up the per-file counts", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodeDiffstatJson(
|
||||
page([
|
||||
{ lines_added: 9, lines_removed: 2 },
|
||||
{ lines_added: 32, lines_removed: 14 },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(decoded).toEqual({ additions: 41, deletions: 16, changedFiles: 2, next: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeConflictsJson", () => {
|
||||
it("calls an empty conflict list mergeable", () => {
|
||||
expect(expectSuccess(decodeConflictsJson(page([])))).toBe("mergeable");
|
||||
});
|
||||
|
||||
it("calls any reported conflict conflicting", () => {
|
||||
expect(expectSuccess(decodeConflictsJson(page([{ path: "src/app.ts" }])))).toBe("conflicting");
|
||||
});
|
||||
});
|
||||
|
||||
describe("repository permission decoding", () => {
|
||||
const permissionPage = (permission: string) =>
|
||||
page([{ type: "repository_permission", permission }]);
|
||||
|
||||
it("counts admin and write as write, and read as not", () => {
|
||||
expect(expectSuccess(decodeRepositoryPermissionJson(permissionPage("admin")))).toBe(true);
|
||||
expect(expectSuccess(decodeRepositoryPermissionJson(permissionPage("write")))).toBe(true);
|
||||
expect(expectSuccess(decodeRepositoryPermissionJson(permissionPage("read")))).toBe(false);
|
||||
});
|
||||
|
||||
it("grants write where Bitbucket named no permission at all", () => {
|
||||
// An empty page is Bitbucket declining to say, which is an unknown standing rather than a
|
||||
// refusal — and an unknown one is granted.
|
||||
expect(expectSuccess(decodeRepositoryPermissionJson(page([])))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,614 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type {
|
||||
PullRequestActor,
|
||||
PullRequestCheck,
|
||||
PullRequestCheckStatus,
|
||||
PullRequestComment,
|
||||
PullRequestCommit,
|
||||
PullRequestMergeability,
|
||||
PullRequestReviewThread,
|
||||
PullRequestReviewerCandidate,
|
||||
PullRequestState,
|
||||
} from "@t3tools/contracts";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
/**
|
||||
* Bitbucket's enums are decoded as plain strings and normalized here, in the same tolerant
|
||||
* style as the GitHub and GitLab decoders: a new pull request state or build status must not
|
||||
* fail a whole payload.
|
||||
*/
|
||||
const RawUserSchema = Schema.Struct({
|
||||
/**
|
||||
* How Bitbucket addresses an account when a reviewer set is written; the handles it shows are
|
||||
* not accepted there. Braced, and sent back exactly as it arrived.
|
||||
*/
|
||||
uuid: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
/** Absent on an app account, which is why `display_name` has to stand in for it. */
|
||||
nickname: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
display_name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
links: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
avatar: Schema.optional(
|
||||
Schema.NullOr(Schema.Struct({ href: Schema.optional(Schema.String) })),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
/**
|
||||
* Required, and required to be non-empty: the wire contract will not carry a change request
|
||||
* without a branch or a link, so a row missing one is skipped rather than breaking the response
|
||||
* it travels in.
|
||||
*/
|
||||
const RawBranchSchema = Schema.Struct({
|
||||
branch: Schema.Struct({ name: TrimmedNonEmptyString }),
|
||||
});
|
||||
|
||||
const RawLinkSchema = Schema.Struct({ href: Schema.optional(Schema.String) });
|
||||
|
||||
const RawPullRequestSchema = Schema.Struct({
|
||||
id: Schema.Int,
|
||||
title: Schema.String,
|
||||
description: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
draft: Schema.optional(Schema.Boolean),
|
||||
author: Schema.optional(Schema.NullOr(RawUserSchema)),
|
||||
source: RawBranchSchema,
|
||||
destination: RawBranchSchema,
|
||||
created_on: Schema.String,
|
||||
updated_on: Schema.String,
|
||||
reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
|
||||
participants: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
user: Schema.optional(Schema.NullOr(RawUserSchema)),
|
||||
role: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
approved: Schema.optional(Schema.Boolean),
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
participated_on: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
links: Schema.Struct({ html: Schema.Struct({ href: TrimmedNonEmptyString }) }),
|
||||
});
|
||||
|
||||
const RawPageSchema = Schema.Struct({
|
||||
values: Schema.Array(Schema.Unknown),
|
||||
/** A total count, which Bitbucket omits on some endpoints. */
|
||||
size: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
/** Present only while a further page exists. */
|
||||
next: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
const RawCommentSchema = Schema.Struct({
|
||||
id: Schema.Int,
|
||||
content: Schema.optional(Schema.NullOr(Schema.Struct({ raw: Schema.optional(Schema.String) }))),
|
||||
user: Schema.optional(Schema.NullOr(RawUserSchema)),
|
||||
created_on: Schema.String,
|
||||
deleted: Schema.optional(Schema.Boolean),
|
||||
/** A comment still being drafted by its author. */
|
||||
pending: Schema.optional(Schema.Boolean),
|
||||
/** Set on a reply, to the comment it answers — which may itself be a reply. */
|
||||
parent: Schema.optional(Schema.NullOr(Schema.Struct({ id: Schema.Int }))),
|
||||
inline: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
path: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
/** The line in the file as it was; set instead of `to` on a removed line. */
|
||||
from: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
/** The line in the file as it is now. */
|
||||
to: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
outdated: Schema.optional(Schema.NullOr(Schema.Boolean)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
/** Non-null once someone has marked the thread resolved. */
|
||||
resolution: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
links: Schema.optional(
|
||||
Schema.NullOr(Schema.Struct({ html: Schema.optional(Schema.NullOr(RawLinkSchema)) })),
|
||||
),
|
||||
});
|
||||
|
||||
const RawCommitSchema = Schema.Struct({
|
||||
hash: TrimmedNonEmptyString,
|
||||
message: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
date: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
author: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
raw: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
user: Schema.optional(Schema.NullOr(RawUserSchema)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawStatusSchema = Schema.Struct({
|
||||
key: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
description: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
url: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
const RawDiffstatSchema = Schema.Struct({
|
||||
lines_added: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
lines_removed: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
});
|
||||
|
||||
/** One row of `/workspaces/{workspace}/members`, which wraps the account it is about. */
|
||||
const RawMemberSchema = Schema.Struct({
|
||||
user: Schema.optional(Schema.NullOr(RawUserSchema)),
|
||||
});
|
||||
|
||||
const RawViewerSchema = Schema.Struct({
|
||||
nickname: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
display_name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
/**
|
||||
* `/user/permissions/repositories` filtered to one repository, which is the only place Bitbucket
|
||||
* states what the credentials may do with it: nothing on the repository, the pull request or the
|
||||
* workspace carries it. One row, or none where Bitbucket names no permission for this account.
|
||||
*/
|
||||
const RawRepositoryPermissionsSchema = Schema.Struct({
|
||||
values: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Array(Schema.Struct({ permission: Schema.optional(Schema.NullOr(Schema.String)) })),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
export interface BitbucketPullRequest {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly author: PullRequestActor | null;
|
||||
readonly headBranch: string;
|
||||
readonly baseBranch: string;
|
||||
readonly state: PullRequestState;
|
||||
readonly isDraft: boolean;
|
||||
/**
|
||||
* Bitbucket reports no conflict state on a pull request, so the list leaves it unknown. The
|
||||
* detail read asks the conflicts endpoint, which does answer.
|
||||
*/
|
||||
readonly mergeability: PullRequestMergeability;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
readonly body: string;
|
||||
readonly reviewRequestLogins: ReadonlyArray<string>;
|
||||
readonly reviewers: ReadonlyArray<PullRequestActor>;
|
||||
/** The reviewers as Bitbucket addresses them, which is what writing the set back takes. */
|
||||
readonly reviewerIds: ReadonlyArray<string>;
|
||||
/** Approvals and change requests, which Bitbucket keeps on its participants. */
|
||||
readonly reviews: ReadonlyArray<PullRequestComment>;
|
||||
}
|
||||
|
||||
function trimmed(value: string | null | undefined): string | null {
|
||||
const text = value?.trim() ?? "";
|
||||
return text.length > 0 ? text : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bitbucket stamps times as `+00:00` with microseconds. The page sorts change requests from
|
||||
* every host against each other as plain strings, so they are normalized to the same `Z` form
|
||||
* the other hosts already use.
|
||||
*/
|
||||
function toIsoUtc(value: string): string {
|
||||
return Option.match(DateTime.make(value), {
|
||||
onNone: () => value,
|
||||
onSome: DateTime.formatIso,
|
||||
});
|
||||
}
|
||||
|
||||
/** An app account has no nickname, so the display name is the only handle it has. */
|
||||
function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
|
||||
const login = trimmed(raw?.nickname) ?? trimmed(raw?.display_name);
|
||||
return login === null
|
||||
? null
|
||||
: {
|
||||
login,
|
||||
name: trimmed(raw?.display_name),
|
||||
avatarUrl: trimmed(raw?.links?.avatar?.href),
|
||||
};
|
||||
}
|
||||
|
||||
function toState(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): PullRequestState {
|
||||
switch (raw.state?.trim().toUpperCase()) {
|
||||
case "MERGED":
|
||||
return "merged";
|
||||
case "DECLINED":
|
||||
case "SUPERSEDED":
|
||||
return "closed";
|
||||
default:
|
||||
return "open";
|
||||
}
|
||||
}
|
||||
|
||||
function toBuildStatus(value: string | null | undefined): PullRequestCheckStatus {
|
||||
switch (value?.trim().toUpperCase()) {
|
||||
case "SUCCESSFUL":
|
||||
return "success";
|
||||
case "FAILED":
|
||||
return "failure";
|
||||
case "STOPPED":
|
||||
return "cancelled";
|
||||
case "INPROGRESS":
|
||||
return "pending";
|
||||
default:
|
||||
return "neutral";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A participant who has voted is the closest Bitbucket has to a review, so it reads as one in
|
||||
* the conversation. Participants who have only been added carry no verdict and are skipped.
|
||||
*/
|
||||
function toReviews(
|
||||
raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
|
||||
): ReadonlyArray<PullRequestComment> {
|
||||
return (raw.participants ?? []).flatMap((participant): ReadonlyArray<PullRequestComment> => {
|
||||
const author = toActor(participant.user);
|
||||
const votedAt = trimmed(participant.participated_on);
|
||||
const reviewState =
|
||||
trimmed(participant.state) ?? (participant.approved === true ? "approved" : null);
|
||||
if (author === null || votedAt === null || reviewState === null) return [];
|
||||
return [
|
||||
{
|
||||
id: `${raw.id}:${author.login}`,
|
||||
kind: "review",
|
||||
author,
|
||||
body: "",
|
||||
createdAt: toIsoUtc(votedAt),
|
||||
url: null,
|
||||
path: null,
|
||||
reviewState,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function toPullRequest(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): BitbucketPullRequest {
|
||||
const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
|
||||
const actor = toActor(reviewer);
|
||||
return actor === null ? [] : [actor];
|
||||
});
|
||||
return {
|
||||
number: raw.id,
|
||||
title: raw.title,
|
||||
url: raw.links.html.href,
|
||||
author: toActor(raw.author),
|
||||
headBranch: raw.source.branch.name,
|
||||
baseBranch: raw.destination.branch.name,
|
||||
state: toState(raw),
|
||||
isDraft: raw.draft ?? false,
|
||||
mergeability: "unknown",
|
||||
createdAt: toIsoUtc(raw.created_on),
|
||||
updatedAt: toIsoUtc(raw.updated_on),
|
||||
body: raw.description ?? "",
|
||||
reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
|
||||
reviewers,
|
||||
reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) => trimmed(reviewer.uuid) ?? []),
|
||||
reviews: toReviews(raw),
|
||||
};
|
||||
}
|
||||
|
||||
const decodePage = decodeJsonResult(RawPageSchema);
|
||||
const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
|
||||
const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
|
||||
const decodeCommentEntry = Schema.decodeUnknownExit(RawCommentSchema);
|
||||
const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
|
||||
const decodeStatusEntry = Schema.decodeUnknownExit(RawStatusSchema);
|
||||
const decodeDiffstatEntry = Schema.decodeUnknownExit(RawDiffstatSchema);
|
||||
const decodeMemberEntry = Schema.decodeUnknownExit(RawMemberSchema);
|
||||
const decodeViewer = decodeJsonResult(RawViewerSchema);
|
||||
const decodeConflicts = decodeJsonResult(RawPageSchema);
|
||||
const decodeRepositoryPermissions = decodeJsonResult(RawRepositoryPermissionsSchema);
|
||||
|
||||
type DecodeFailure = Cause.Cause<Schema.SchemaError>;
|
||||
|
||||
export interface BitbucketPage<A> {
|
||||
readonly items: ReadonlyArray<A>;
|
||||
/** The whole URL of the next page, which Bitbucket sends rather than an offset. */
|
||||
readonly next: string | null;
|
||||
}
|
||||
|
||||
/** Malformed entries are skipped rather than failing the page, as on the other hosts. */
|
||||
export function decodePullRequestPageJson(
|
||||
raw: string,
|
||||
): Result.Result<BitbucketPage<BitbucketPullRequest>, DecodeFailure> {
|
||||
const decoded = decodePage(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const items: BitbucketPullRequest[] = [];
|
||||
for (const entry of decoded.success.values) {
|
||||
const item = decodePullRequestEntry(entry);
|
||||
if (Exit.isSuccess(item)) {
|
||||
items.push(toPullRequest(item.value));
|
||||
}
|
||||
}
|
||||
return Result.succeed({ items, next: trimmed(decoded.success.next) });
|
||||
}
|
||||
|
||||
export function decodePullRequestJson(
|
||||
raw: string,
|
||||
): Result.Result<BitbucketPullRequest, DecodeFailure> {
|
||||
const decoded = decodePullRequest(raw);
|
||||
return Result.isSuccess(decoded)
|
||||
? Result.succeed(toPullRequest(decoded.success))
|
||||
: Result.fail(decoded.failure);
|
||||
}
|
||||
|
||||
export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
|
||||
const decoded = decodeViewer(raw);
|
||||
return Result.isSuccess(decoded)
|
||||
? Result.succeed(trimmed(decoded.success.nickname) ?? trimmed(decoded.success.display_name))
|
||||
: Result.fail(decoded.failure);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the configured credentials can write to the repository, which is what merging needs.
|
||||
* Bitbucket answers `admin`, `write` or `read`, and an empty page means it named no permission at
|
||||
* all for this account — an unknown standing, which is granted rather than guessed away.
|
||||
*/
|
||||
export function decodeRepositoryPermissionJson(raw: string): Result.Result<boolean, DecodeFailure> {
|
||||
const decoded = decodeRepositoryPermissions(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const permission = trimmed(decoded.success.values?.[0]?.permission)?.toLowerCase() ?? null;
|
||||
return Result.succeed(permission === null || permission === "admin" || permission === "write");
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace's members, which is the nearest thing Bitbucket has to "who may review this".
|
||||
* Nothing on a repository lists the people with access to it — `permissions-config/users` is for
|
||||
* administrators only — and a pull request can be sent to anyone in the workspace, so this is the
|
||||
* list Bitbucket's own reviewer field is filled from too.
|
||||
*
|
||||
* Nobody is marked requested here: who has been asked lives on the pull request, and only the
|
||||
* caller holds both.
|
||||
*/
|
||||
export function decodeWorkspaceMembersJson(
|
||||
raw: string,
|
||||
): Result.Result<BitbucketPage<PullRequestReviewerCandidate>, DecodeFailure> {
|
||||
const decoded = decodePage(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const items: PullRequestReviewerCandidate[] = [];
|
||||
for (const entry of decoded.success.values) {
|
||||
const member = decodeMemberEntry(entry);
|
||||
if (Exit.isFailure(member)) continue;
|
||||
const uuid = trimmed(member.value.user?.uuid);
|
||||
const actor = toActor(member.value.user);
|
||||
if (uuid === null || actor === null) continue;
|
||||
items.push({ ...actor, id: uuid, kind: "user", isRequested: false });
|
||||
}
|
||||
return Result.succeed({ items, next: trimmed(decoded.success.next) });
|
||||
}
|
||||
|
||||
/** One comment as Bitbucket sent it, kept so threads can be assembled across pages. */
|
||||
export type BitbucketRawComment = Schema.Schema.Type<typeof RawCommentSchema>;
|
||||
|
||||
export interface BitbucketComments {
|
||||
readonly comments: ReadonlyArray<PullRequestComment>;
|
||||
/**
|
||||
* The same comments unread, for `buildReviewThreads`. A reply and the remark it answers can
|
||||
* land on different pages, and only the caller holding every page can put them together.
|
||||
*/
|
||||
readonly entries: ReadonlyArray<BitbucketRawComment>;
|
||||
readonly next: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bitbucket returns one flat list, so a thread is reassembled from it: a comment pinned to a
|
||||
* line opens a thread, and every reply that leads back to it belongs in it. A reply whose
|
||||
* parent is on a page that was not read has nowhere to go, and is left out rather than shown
|
||||
* as a thread of its own — it still stands in the flat conversation, which needs no parent.
|
||||
*/
|
||||
export function buildReviewThreads(
|
||||
comments: ReadonlyArray<BitbucketRawComment>,
|
||||
): ReadonlyArray<PullRequestReviewThread> {
|
||||
const byId = new Map(comments.map((comment) => [comment.id, comment]));
|
||||
const rootOf = (comment: Schema.Schema.Type<typeof RawCommentSchema>) => {
|
||||
// Bounded by the number of comments read, so a parent cycle cannot spin here.
|
||||
let current = comment;
|
||||
for (let step = 0; step < byId.size; step += 1) {
|
||||
const parent = current.parent === null ? undefined : byId.get(current.parent?.id ?? -1);
|
||||
if (parent === undefined) return current;
|
||||
current = parent;
|
||||
}
|
||||
return current;
|
||||
};
|
||||
|
||||
const threads = new Map<number, PullRequestReviewThread>();
|
||||
const replies = new Map<number, Array<Schema.Schema.Type<typeof RawCommentSchema>>>();
|
||||
for (const comment of comments) {
|
||||
const root = rootOf(comment);
|
||||
const inline = root.inline;
|
||||
const path = trimmed(inline?.path);
|
||||
if (path === null) continue;
|
||||
if (root.id === comment.id) {
|
||||
// `to` is the line as the file stands now, `from` the line it replaced; a comment that
|
||||
// carries only `from` was written against the removed side.
|
||||
const side = inline?.to === null || inline?.to === undefined ? "left" : "right";
|
||||
const line = side === "left" ? inline?.from : inline?.to;
|
||||
threads.set(root.id, {
|
||||
id: String(root.id),
|
||||
path,
|
||||
line: typeof line === "number" && line > 0 ? line : null,
|
||||
side,
|
||||
isResolved: root.resolution !== null && root.resolution !== undefined,
|
||||
isOutdated: inline?.outdated === true,
|
||||
comments: [],
|
||||
});
|
||||
}
|
||||
const bucket = replies.get(root.id);
|
||||
if (bucket === undefined) replies.set(root.id, [comment]);
|
||||
else bucket.push(comment);
|
||||
}
|
||||
|
||||
return [...threads.values()].flatMap((thread) => {
|
||||
const entries = (replies.get(Number(thread.id)) ?? [])
|
||||
.toSorted((left, right) => left.created_on.localeCompare(right.created_on))
|
||||
.map((comment) => ({
|
||||
id: String(comment.id),
|
||||
author: toActor(comment.user),
|
||||
body: comment.content?.raw ?? "",
|
||||
createdAt: toIsoUtc(comment.created_on),
|
||||
url: trimmed(comment.links?.html?.href),
|
||||
}));
|
||||
return entries.length === 0 ? [] : [{ ...thread, comments: entries }];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleted comments and ones their author has not posted yet carry nothing to show. A comment
|
||||
* pinned to a file is a line-level review comment, which is what that kind means.
|
||||
*/
|
||||
export function decodeCommentsJson(raw: string): Result.Result<BitbucketComments, DecodeFailure> {
|
||||
const decoded = decodePage(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const comments: PullRequestComment[] = [];
|
||||
const kept: Array<BitbucketRawComment> = [];
|
||||
for (const entry of decoded.success.values) {
|
||||
const decodedComment = decodeCommentEntry(entry);
|
||||
if (Exit.isFailure(decodedComment)) continue;
|
||||
const comment = decodedComment.value;
|
||||
if (comment.deleted === true || comment.pending === true) continue;
|
||||
const body = comment.content?.raw ?? "";
|
||||
if (body.trim().length === 0) continue;
|
||||
kept.push(comment);
|
||||
const path = trimmed(comment.inline?.path);
|
||||
comments.push({
|
||||
id: String(comment.id),
|
||||
kind: path === null ? "issue-comment" : "review-comment",
|
||||
author: toActor(comment.user),
|
||||
body,
|
||||
createdAt: toIsoUtc(comment.created_on),
|
||||
url: trimmed(comment.links?.html?.href),
|
||||
path,
|
||||
reviewState: null,
|
||||
});
|
||||
}
|
||||
return Result.succeed({ comments, entries: kept, next: trimmed(decoded.success.next) });
|
||||
}
|
||||
|
||||
export function decodeCommitsJson(
|
||||
raw: string,
|
||||
): Result.Result<BitbucketPage<PullRequestCommit>, DecodeFailure> {
|
||||
const decoded = decodePage(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const commits: PullRequestCommit[] = [];
|
||||
for (const entry of decoded.success.values) {
|
||||
const decodedCommit = decodeCommitEntry(entry);
|
||||
if (Exit.isFailure(decodedCommit)) continue;
|
||||
const commit = decodedCommit.value;
|
||||
const committedDate = trimmed(commit.date);
|
||||
if (committedDate === null) continue;
|
||||
const linkedAuthor = toActor(commit.author?.user);
|
||||
const rawAuthor = trimmed(commit.author?.raw);
|
||||
commits.push({
|
||||
oid: commit.hash,
|
||||
messageHeadline: (commit.message ?? "").split("\n")[0] ?? "",
|
||||
committedDate: toIsoUtc(committedDate),
|
||||
authors:
|
||||
linkedAuthor !== null
|
||||
? [linkedAuthor]
|
||||
: rawAuthor === null
|
||||
? []
|
||||
: [{ login: rawAuthor, name: rawAuthor, avatarUrl: null }],
|
||||
});
|
||||
}
|
||||
// Bitbucket lists a pull request's commits newest first; the timeline reads oldest first.
|
||||
return Result.succeed({ items: commits.toReversed(), next: trimmed(decoded.success.next) });
|
||||
}
|
||||
|
||||
export function decodeStatusesJson(
|
||||
raw: string,
|
||||
): Result.Result<BitbucketPage<PullRequestCheck>, DecodeFailure> {
|
||||
const decoded = decodePage(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const checks: PullRequestCheck[] = [];
|
||||
for (const entry of decoded.success.values) {
|
||||
const decodedStatus = decodeStatusEntry(entry);
|
||||
if (Exit.isFailure(decodedStatus)) continue;
|
||||
const status = decodedStatus.value;
|
||||
const name = trimmed(status.name) ?? trimmed(status.key);
|
||||
if (name === null) continue;
|
||||
checks.push({
|
||||
name,
|
||||
status: toBuildStatus(status.state),
|
||||
description: trimmed(status.description),
|
||||
url: trimmed(status.url),
|
||||
});
|
||||
}
|
||||
return Result.succeed({ items: checks, next: trimmed(decoded.success.next) });
|
||||
}
|
||||
|
||||
export interface BitbucketDiffStat {
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
readonly changedFiles: number;
|
||||
}
|
||||
|
||||
export interface BitbucketDiffStatPage extends BitbucketDiffStat {
|
||||
readonly next: string | null;
|
||||
}
|
||||
|
||||
/** One entry per changed file, each carrying that file's line counts. */
|
||||
export function decodeDiffstatJson(
|
||||
raw: string,
|
||||
): Result.Result<BitbucketDiffStatPage, DecodeFailure> {
|
||||
const decoded = decodePage(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
let changedFiles = 0;
|
||||
for (const entry of decoded.success.values) {
|
||||
const decodedStat = decodeDiffstatEntry(entry);
|
||||
if (Exit.isFailure(decodedStat)) continue;
|
||||
additions += decodedStat.value.lines_added ?? 0;
|
||||
deletions += decodedStat.value.lines_removed ?? 0;
|
||||
changedFiles += 1;
|
||||
}
|
||||
return Result.succeed({
|
||||
additions,
|
||||
deletions,
|
||||
changedFiles,
|
||||
next: trimmed(decoded.success.next),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The conflicts endpoint answers with one entry per conflicting path, so an empty page is the
|
||||
* only statement Bitbucket makes that a pull request merges cleanly.
|
||||
*/
|
||||
export function decodeConflictsJson(
|
||||
raw: string,
|
||||
): Result.Result<PullRequestMergeability, DecodeFailure> {
|
||||
const decoded = decodeConflicts(raw);
|
||||
return Result.isSuccess(decoded)
|
||||
? Result.succeed(decoded.success.values.length === 0 ? "mergeable" : "conflicting")
|
||||
: Result.fail(decoded.failure);
|
||||
}
|
||||
@@ -0,0 +1,959 @@
|
||||
import * as Result from "effect/Result";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildReviewSubmissionJson,
|
||||
buildReviewerRequestJson,
|
||||
decodePullRequestActivityJson,
|
||||
decodePullRequestDetailJson,
|
||||
decodePullRequestFilesJson,
|
||||
decodePullRequestListJson,
|
||||
decodeRepositoryAccessJson,
|
||||
decodeReviewerCandidatesJson,
|
||||
decodeReviewThreadCommentsJson,
|
||||
decodeReviewThreadsJson,
|
||||
decodeViewerPermissionsJson,
|
||||
reviewThreadConversation,
|
||||
} from "./gitHubPullRequestJson.ts";
|
||||
|
||||
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
|
||||
return JSON.stringify(
|
||||
entries.map((entry) => ({
|
||||
number: 1,
|
||||
title: "Add the pull requests page",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1",
|
||||
headRefName: "feat/page",
|
||||
baseRefName: "main",
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
updatedAt: "2026-07-02T00:00:00Z",
|
||||
...entry,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
function expectSuccess<A>(result: Result.Result<A, unknown>): A {
|
||||
expect(Result.isSuccess(result)).toBe(true);
|
||||
if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
|
||||
return result.success;
|
||||
}
|
||||
|
||||
describe("pull request list decoding", () => {
|
||||
it("treats a merge timestamp as merged even when the state still says closed", () => {
|
||||
const [entry] = expectSuccess(
|
||||
decodePullRequestListJson(listJson([{ state: "CLOSED", mergedAt: "2026-07-03T00:00:00Z" }])),
|
||||
).items;
|
||||
expect(entry?.state).toBe("merged");
|
||||
});
|
||||
|
||||
it("normalizes mergeability and defaults unknown values", () => {
|
||||
const batch = expectSuccess(
|
||||
decodePullRequestListJson(
|
||||
listJson([{ mergeable: "CONFLICTING" }, { mergeable: "SOMETHING_NEW" }, {}]),
|
||||
),
|
||||
);
|
||||
expect(batch.items.map((entry) => entry.mergeability)).toEqual([
|
||||
"conflicting",
|
||||
"unknown",
|
||||
"unknown",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps user review requests and drops team ones, which are not logins", () => {
|
||||
const [entry] = expectSuccess(
|
||||
decodePullRequestListJson(
|
||||
listJson([{ reviewRequests: [{ login: "octocat" }, { slug: "web-platform" }] }]),
|
||||
),
|
||||
).items;
|
||||
expect(entry?.reviewRequestLogins).toEqual(["octocat"]);
|
||||
});
|
||||
|
||||
it("skips malformed entries but still counts them, so paging does not stop early", () => {
|
||||
const raw = `[${listJson([{}]).slice(1, -1)},{"number":"not-a-number"}]`;
|
||||
const batch = expectSuccess(decodePullRequestListJson(raw));
|
||||
expect(batch.items).toHaveLength(1);
|
||||
expect(batch.rawCount).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pull request detail decoding", () => {
|
||||
const detailJson = JSON.stringify({
|
||||
number: 7,
|
||||
title: "Detail",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/7",
|
||||
headRefName: "feat/detail",
|
||||
baseRefName: "main",
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
updatedAt: "2026-07-05T00:00:00Z",
|
||||
body: "Body",
|
||||
statusCheckRollup: [
|
||||
{ __typename: "CheckRun", name: "build", status: "IN_PROGRESS" },
|
||||
{ __typename: "CheckRun", name: "test", status: "COMPLETED", conclusion: "FAILURE" },
|
||||
{ __typename: "StatusContext", context: "ci/legacy", state: "SUCCESS" },
|
||||
],
|
||||
comments: [{ id: "c1", body: "second", createdAt: "2026-07-04T00:00:00Z" }],
|
||||
reviews: [
|
||||
{ id: "r1", body: "first", state: "CHANGES_REQUESTED", submittedAt: "2026-07-03T00:00:00Z" },
|
||||
{ id: "r2", body: " ", state: "APPROVED", submittedAt: "2026-07-06T00:00:00Z" },
|
||||
],
|
||||
commits: [
|
||||
{
|
||||
oid: "abc1234",
|
||||
messageHeadline: "Ship the timeline",
|
||||
committedDate: "2026-07-05T00:00:00Z",
|
||||
authors: [
|
||||
{ login: "octocat", name: "Octo Cat", email: "[email protected]" },
|
||||
{ name: "Pair Author", email: "[email protected]" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
it("maps check-run status and commit-status state onto one vocabulary", () => {
|
||||
const detail = expectSuccess(decodePullRequestDetailJson(detailJson));
|
||||
expect(detail.checks.map((check) => [check.name, check.status])).toEqual([
|
||||
["build", "pending"],
|
||||
["test", "failure"],
|
||||
["ci/legacy", "success"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("merges reviews with comments in time order and keeps a bodyless approval", () => {
|
||||
const detail = expectSuccess(decodePullRequestActivityJson(detailJson));
|
||||
// r2 approved without writing anything, which is still the event worth seeing.
|
||||
expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]);
|
||||
expect(detail.comments.at(-1)?.reviewState).toBe("APPROVED");
|
||||
});
|
||||
|
||||
it("keeps every attributed commit author, including an unlinked signature", () => {
|
||||
const detail = expectSuccess(decodePullRequestActivityJson(detailJson));
|
||||
expect(detail.commits[0]?.authors).toEqual([
|
||||
{ login: "octocat", name: "Octo Cat", avatarUrl: null },
|
||||
{ login: "Pair Author", name: "Pair Author", avatarUrl: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops the bodyless review GitHub opens to hold line comments", () => {
|
||||
const raw = JSON.parse(detailJson) as Record<string, unknown>;
|
||||
const detail = expectSuccess(
|
||||
decodePullRequestActivityJson(
|
||||
JSON.stringify({
|
||||
...raw,
|
||||
reviews: [
|
||||
// What a reviewer leaving inline comments produces: a container with a state but
|
||||
// nothing to read. Its comments come from the review threads instead.
|
||||
{ id: "r4", body: "", state: "COMMENTED", submittedAt: "2026-07-07T00:00:00Z" },
|
||||
{
|
||||
id: "r5",
|
||||
body: "Looks good.",
|
||||
state: "COMMENTED",
|
||||
submittedAt: "2026-07-08T00:00:00Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(detail.comments.map((comment) => comment.id)).toEqual(["c1", "r5"]);
|
||||
});
|
||||
|
||||
it.each(["APPROVED", "CHANGES_REQUESTED", "DISMISSED"])(
|
||||
"keeps a bodyless %s review, which is the event itself",
|
||||
(state) => {
|
||||
const raw = JSON.parse(detailJson) as Record<string, unknown>;
|
||||
const detail = expectSuccess(
|
||||
decodePullRequestActivityJson(
|
||||
JSON.stringify({
|
||||
...raw,
|
||||
reviews: [{ id: "r6", body: "", state, submittedAt: "2026-07-07T00:00:00Z" }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(detail.comments.map((comment) => comment.id)).toContain("r6");
|
||||
},
|
||||
);
|
||||
|
||||
it("drops a review that carries neither a body nor a state", () => {
|
||||
const raw = JSON.parse(detailJson) as Record<string, unknown>;
|
||||
const detail = expectSuccess(
|
||||
decodePullRequestActivityJson(
|
||||
JSON.stringify({
|
||||
...raw,
|
||||
reviews: [{ id: "r3", body: " ", submittedAt: "2026-07-07T00:00:00Z" }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(detail.comments.map((comment) => comment.id)).toEqual(["c1"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("review thread decoding", () => {
|
||||
const threadsJson = (
|
||||
nodes: ReadonlyArray<Record<string, unknown>>,
|
||||
totalCount = nodes.length,
|
||||
pageInfo: Record<string, unknown> = { hasNextPage: false, endCursor: null },
|
||||
): string =>
|
||||
JSON.stringify({
|
||||
data: { repository: { pullRequest: { reviewThreads: { totalCount, pageInfo, nodes } } } },
|
||||
});
|
||||
|
||||
/** The same query carries the review roster, so it is built alongside the threads. */
|
||||
const reviewJson = (input: {
|
||||
readonly requested?: ReadonlyArray<unknown>;
|
||||
readonly reviewed?: ReadonlyArray<unknown>;
|
||||
}): string =>
|
||||
JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
pullRequest: {
|
||||
reviewThreads: { totalCount: 0, nodes: [] },
|
||||
reviewRequests: {
|
||||
nodes: (input.requested ?? []).map((r) => ({ requestedReviewer: r })),
|
||||
},
|
||||
latestReviews: { nodes: (input.reviewed ?? []).map((a) => ({ author: a })) },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
it("keeps a reviewer who has already reviewed, app or person, with their avatar", () => {
|
||||
const result = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
reviewJson({
|
||||
requested: [{ login: "julius", name: "Julius", avatarUrl: "https://avatars/j.png" }],
|
||||
// An app that has reviewed is no longer an outstanding request, which is why asking
|
||||
// only for requests reported nobody on a pull request a bot had reviewed.
|
||||
reviewed: [{ login: "macroscopeapp", avatarUrl: "https://avatars/in/900172.png" }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.reviewers).toEqual([
|
||||
{ login: "julius", name: "Julius", avatarUrl: "https://avatars/j.png" },
|
||||
{ login: "macroscopeapp", name: null, avatarUrl: "https://avatars/in/900172.png" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("carries per-commit line counts from the pull-request connection", () => {
|
||||
const result = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
pullRequest: {
|
||||
reviewThreads: { totalCount: 0, nodes: [] },
|
||||
commits: {
|
||||
nodes: [
|
||||
{ commit: { oid: "abc123", additions: 18, deletions: 7 } },
|
||||
{ commit: { oid: "def456", additions: 3, deletions: 0 } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect([...result.commitStats]).toEqual([
|
||||
["abc123", { additions: 18, deletions: 7 }],
|
||||
["def456", { additions: 3, deletions: 0 }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("decodes the newest commits off the same connection, oldest to newest", () => {
|
||||
const result = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
pullRequest: {
|
||||
reviewThreads: { totalCount: 0, nodes: [] },
|
||||
commits: {
|
||||
nodes: [
|
||||
{
|
||||
commit: {
|
||||
oid: "abc123",
|
||||
messageHeadline: "Ship the timeline",
|
||||
committedDate: "2026-07-05T00:00:00Z",
|
||||
additions: 18,
|
||||
deletions: 7,
|
||||
authors: { nodes: [{ name: "Julius", user: { login: "julius" } }] },
|
||||
},
|
||||
},
|
||||
{
|
||||
commit: {
|
||||
oid: "def456",
|
||||
messageHeadline: "Fix the flaky test",
|
||||
committedDate: "2026-07-06T00:00:00Z",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.commits).toEqual([
|
||||
{
|
||||
oid: "abc123",
|
||||
messageHeadline: "Ship the timeline",
|
||||
committedDate: "2026-07-05T00:00:00Z",
|
||||
authors: [{ login: "julius", name: "Julius", avatarUrl: null }],
|
||||
},
|
||||
{
|
||||
oid: "def456",
|
||||
messageHeadline: "Fix the flaky test",
|
||||
committedDate: "2026-07-06T00:00:00Z",
|
||||
authors: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists someone who was asked and then answered only once", () => {
|
||||
const result = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
reviewJson({
|
||||
requested: [{ login: "julius", avatarUrl: "https://avatars/j.png" }],
|
||||
reviewed: [{ login: "julius", avatarUrl: "https://avatars/j.png" }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.reviewers).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("skips a team request, which names nobody to show", () => {
|
||||
const result = expectSuccess(decodeReviewThreadsJson(reviewJson({ requested: [null] })));
|
||||
|
||||
expect(result.reviewers).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps the conversation when a request is from a team, which has no login", () => {
|
||||
// GraphQL answers with an empty object for a union member the query has no fragment for.
|
||||
// Failing on it would take the whole response down, comments included.
|
||||
const result = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
reviewJson({ requested: [{}, { login: "julius", avatarUrl: "https://avatars/j.png" }] }),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.reviewers).toEqual([
|
||||
{ login: "julius", name: null, avatarUrl: "https://avatars/j.png" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("carries a resolved thread into the conversation, which was still said", () => {
|
||||
const result = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
threadsJson([
|
||||
{
|
||||
id: "PRRT_a",
|
||||
isResolved: false,
|
||||
path: "apps/server/src/ws.ts",
|
||||
comments: {
|
||||
nodes: [{ id: "t1", body: "fix this", createdAt: "2026-07-01T00:00:00Z" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "PRRT_b",
|
||||
isResolved: true,
|
||||
path: "apps/web/src/main.tsx",
|
||||
comments: { nodes: [{ id: "t2", body: "done", createdAt: "2026-07-01T00:00:00Z" }] },
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
const comments = reviewThreadConversation(result.threads.map((entry) => entry.thread));
|
||||
expect(comments.map((comment) => comment.id)).toEqual(["t1", "t2"]);
|
||||
expect(comments[0]).toMatchObject({
|
||||
id: "t1",
|
||||
kind: "review-comment",
|
||||
path: "apps/server/src/ws.ts",
|
||||
});
|
||||
});
|
||||
|
||||
it("carries every reply, not only the remark each thread opened with", () => {
|
||||
const result = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
threadsJson([
|
||||
{
|
||||
id: "PRRT_c",
|
||||
isResolved: false,
|
||||
path: "apps/server/src/ws.ts",
|
||||
comments: {
|
||||
nodes: [
|
||||
{ id: "t1", body: "fix this", createdAt: "2026-07-01T00:00:00Z" },
|
||||
{ id: "t2", body: "fixed", createdAt: "2026-07-01T01:00:00Z" },
|
||||
],
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
const comments = reviewThreadConversation(result.threads.map((entry) => entry.thread));
|
||||
expect(comments.map((comment) => comment.id)).toEqual(["t1", "t2"]);
|
||||
});
|
||||
|
||||
it("hands back the cursor the next page of threads carries on from", () => {
|
||||
const result = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
threadsJson(
|
||||
[
|
||||
{
|
||||
id: "PRRT_d",
|
||||
path: "apps/server/src/ws.ts",
|
||||
isResolved: false,
|
||||
comments: { nodes: [{ id: "t1", createdAt: "2026-07-01T00:00:00Z" }] },
|
||||
},
|
||||
],
|
||||
80,
|
||||
{ hasNextPage: true, endCursor: "Y3Vyc29yOjE" },
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(result.nextCursor).toBe("Y3Vyc29yOjE");
|
||||
});
|
||||
|
||||
it("keeps GitHub's own count of a thread whose comments were not all read", () => {
|
||||
const result = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
threadsJson([
|
||||
{
|
||||
id: "PRRT_e",
|
||||
path: "apps/server/src/ws.ts",
|
||||
isResolved: false,
|
||||
comments: {
|
||||
totalCount: 140,
|
||||
pageInfo: { hasNextPage: true, endCursor: "Y3Vyc29yOjI" },
|
||||
nodes: [{ id: "t1", createdAt: "2026-07-01T00:00:00Z" }],
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(result.threads[0]).toMatchObject({
|
||||
commentCount: 140,
|
||||
nextCommentCursor: "Y3Vyc29yOjI",
|
||||
});
|
||||
});
|
||||
|
||||
it("ends a thread's walk on the last page, which still names a cursor", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodeReviewThreadCommentsJson(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
node: {
|
||||
comments: {
|
||||
pageInfo: { hasNextPage: false, endCursor: "Y3Vyc29yOjk" },
|
||||
nodes: [{ id: "t9", body: "last", createdAt: "2026-07-01T00:00:00Z" }],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(decoded.comments.map((comment) => comment.id)).toEqual(["t9"]);
|
||||
expect(decoded.nextCursor).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("repository access decoding", () => {
|
||||
const repositoryJson = (viewerPermission?: string | null) =>
|
||||
JSON.stringify({
|
||||
mergeCommitAllowed: true,
|
||||
squashMergeAllowed: false,
|
||||
rebaseMergeAllowed: true,
|
||||
...(viewerPermission === undefined ? {} : { viewerPermission }),
|
||||
});
|
||||
|
||||
it("reads the three settings gh reports", () => {
|
||||
expect(
|
||||
expectSuccess(decodeRepositoryAccessJson(repositoryJson("ADMIN"))).mergeCapabilities,
|
||||
).toEqual({ merge: true, squash: false, rebase: true });
|
||||
});
|
||||
|
||||
it("fails rather than defaulting open when a setting is missing", () => {
|
||||
const decoded = decodeRepositoryAccessJson(JSON.stringify({ mergeCommitAllowed: true }));
|
||||
expect(Result.isSuccess(decoded)).toBe(false);
|
||||
});
|
||||
|
||||
it("counts the roles that can push as write, and the ones that cannot as read", () => {
|
||||
for (const permission of ["ADMIN", "MAINTAIN", "WRITE"]) {
|
||||
expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson(permission))).canWrite).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
for (const permission of ["TRIAGE", "READ", "NONE"]) {
|
||||
expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson(permission))).canWrite).toBe(
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("withholds write where gh names no permission, which is not a standing it gave", () => {
|
||||
// The one place an unknown answer is not granted: a Merge button a reader cannot use wastes
|
||||
// the press, where a missing one still leaves the pull request open on its host.
|
||||
expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson())).canWrite).toBe(false);
|
||||
expect(expectSuccess(decodeRepositoryAccessJson(repositoryJson(null))).canWrite).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("viewer permission decoding", () => {
|
||||
const viewerJson = (repository: Record<string, unknown>) =>
|
||||
JSON.stringify({ data: { repository } });
|
||||
|
||||
it("reads the repository's role and the pull request's own viewer fields together", () => {
|
||||
expect(
|
||||
expectSuccess(
|
||||
decodeViewerPermissionsJson(
|
||||
viewerJson({
|
||||
viewerPermission: "READ",
|
||||
pullRequest: { viewerCanUpdate: true, viewerDidAuthor: true },
|
||||
}),
|
||||
),
|
||||
),
|
||||
).toEqual({ canWrite: false, canUpdate: true, didAuthor: true });
|
||||
});
|
||||
|
||||
it("says no to a passer-by on a repository they can only read", () => {
|
||||
expect(
|
||||
expectSuccess(
|
||||
decodeViewerPermissionsJson(
|
||||
viewerJson({
|
||||
viewerPermission: "READ",
|
||||
pullRequest: { viewerCanUpdate: false, viewerDidAuthor: false },
|
||||
}),
|
||||
),
|
||||
),
|
||||
).toEqual({ canWrite: false, canUpdate: false, didAuthor: false });
|
||||
});
|
||||
|
||||
it("reads silence as permission, but not as authorship", () => {
|
||||
// A node the viewer cannot see comes back null. Updating is a permission, so an unknown
|
||||
// answer grants it and lets the host refuse; authorship is a fact about who wrote the change,
|
||||
// and claiming it for someone who did not is how an author's own rules get handed out.
|
||||
expect(expectSuccess(decodeViewerPermissionsJson(viewerJson({ pullRequest: null })))).toEqual({
|
||||
canWrite: false,
|
||||
canUpdate: true,
|
||||
didAuthor: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("review thread decoding", () => {
|
||||
const threadsJson = (
|
||||
nodes: ReadonlyArray<Record<string, unknown>>,
|
||||
pullRequest: Record<string, unknown> = {},
|
||||
) =>
|
||||
JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
pullRequest: {
|
||||
reviewThreads: { totalCount: nodes.length, nodes },
|
||||
author: null,
|
||||
comments: { nodes: [] },
|
||||
reviewRequests: { nodes: [] },
|
||||
latestReviews: { nodes: [] },
|
||||
...pullRequest,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
it("carries what the reader may do with the pull request, off the conversation read", () => {
|
||||
// The same response the threads arrive in, so knowing this costs no request of its own.
|
||||
expect(
|
||||
expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
threadsJson([], { viewerCanUpdate: false, viewerDidAuthor: false }),
|
||||
),
|
||||
).viewer,
|
||||
).toEqual({ canUpdate: false, didAuthor: false });
|
||||
expect(expectSuccess(decodeReviewThreadsJson(threadsJson([]))).viewer).toEqual({
|
||||
canUpdate: true,
|
||||
didAuthor: false,
|
||||
});
|
||||
});
|
||||
|
||||
const comment = (id: string, body: string) => ({
|
||||
id,
|
||||
author: { login: "bilal", avatarUrl: "https://avatars/b.png" },
|
||||
body,
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
url: `https://github.com/acme/web/pull/1#discussion_r${id}`,
|
||||
});
|
||||
|
||||
it("anchors a thread to its line and side, keeping the whole conversation", () => {
|
||||
const reviewThreads = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
threadsJson([
|
||||
{
|
||||
id: "PRRT_1",
|
||||
isResolved: false,
|
||||
isOutdated: false,
|
||||
path: "src/a.ts",
|
||||
line: 42,
|
||||
diffSide: "LEFT",
|
||||
comments: { totalCount: 2, nodes: [comment("c1", "first"), comment("c2", "second")] },
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(reviewThreads.threads.map((entry) => entry.thread)).toEqual([
|
||||
{
|
||||
id: "PRRT_1",
|
||||
path: "src/a.ts",
|
||||
line: 42,
|
||||
side: "left",
|
||||
isResolved: false,
|
||||
isOutdated: false,
|
||||
comments: [
|
||||
{
|
||||
id: "c1",
|
||||
author: { login: "bilal", name: null, avatarUrl: "https://avatars/b.png" },
|
||||
body: "first",
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
url: "https://github.com/acme/web/pull/1#discussion_rc1",
|
||||
},
|
||||
{
|
||||
id: "c2",
|
||||
author: { login: "bilal", name: null, avatarUrl: "https://avatars/b.png" },
|
||||
body: "second",
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
url: "https://github.com/acme/web/pull/1#discussion_rc2",
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves an outdated thread without a line rather than pinning it to a stale one", () => {
|
||||
const reviewThreads = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
threadsJson([
|
||||
{
|
||||
id: "PRRT_2",
|
||||
isResolved: true,
|
||||
isOutdated: true,
|
||||
path: "src/a.ts",
|
||||
// GitHub reports no current line once the thread has fallen off the diff.
|
||||
line: null,
|
||||
diffSide: "RIGHT",
|
||||
comments: { totalCount: 1, nodes: [comment("c3", "stale")] },
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(reviewThreads.threads[0]?.thread).toMatchObject({
|
||||
line: null,
|
||||
isOutdated: true,
|
||||
isResolved: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a resolved thread in the conversation as well as against its line", () => {
|
||||
const decoded = expectSuccess(
|
||||
decodeReviewThreadsJson(
|
||||
threadsJson([
|
||||
{
|
||||
id: "PRRT_3",
|
||||
isResolved: true,
|
||||
path: "src/a.ts",
|
||||
line: 7,
|
||||
diffSide: "RIGHT",
|
||||
comments: { totalCount: 1, nodes: [comment("c4", "done")] },
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
// A resolved conversation is finished work, not unsaid work: the timeline reads it and the
|
||||
// diff pins it to its line, the same as any other.
|
||||
const threads = decoded.threads.map((entry) => entry.thread);
|
||||
expect(reviewThreadConversation(threads).map((comment) => comment.id)).toEqual(["c4"]);
|
||||
expect(threads).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reviewer candidate decoding", () => {
|
||||
const candidatesJson = (input: {
|
||||
readonly assignable: ReadonlyArray<Record<string, unknown> | null>;
|
||||
readonly requested?: ReadonlyArray<Record<string, unknown> | null>;
|
||||
readonly author?: string;
|
||||
readonly hasNextPage?: boolean;
|
||||
}) =>
|
||||
JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
assignableUsers: {
|
||||
pageInfo: { hasNextPage: input.hasNextPage ?? false },
|
||||
nodes: input.assignable,
|
||||
},
|
||||
pullRequest: {
|
||||
author: input.author === undefined ? null : { login: input.author },
|
||||
reviewRequests: {
|
||||
nodes: (input.requested ?? []).map((requestedReviewer) => ({ requestedReviewer })),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
it("leaves the author out of the people their own pull request can be sent to", () => {
|
||||
const list = expectSuccess(
|
||||
decodeReviewerCandidatesJson(
|
||||
candidatesJson({
|
||||
assignable: [{ login: "bilal" }, { login: "octocat", name: "The Octocat" }],
|
||||
author: "bilal",
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(list.candidates).toEqual([
|
||||
{
|
||||
id: "octocat",
|
||||
kind: "user",
|
||||
login: "octocat",
|
||||
name: "The Octocat",
|
||||
avatarUrl: null,
|
||||
isRequested: false,
|
||||
},
|
||||
]);
|
||||
expect(list.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it("marks whoever has already been asked, and leaves the rest to be asked", () => {
|
||||
const list = expectSuccess(
|
||||
decodeReviewerCandidatesJson(
|
||||
candidatesJson({
|
||||
assignable: [{ login: "octocat" }, { login: "hubot" }],
|
||||
requested: [{ login: "octocat" }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(list.candidates.map((candidate) => [candidate.login, candidate.isRequested])).toEqual([
|
||||
["octocat", true],
|
||||
["hubot", false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a requested team apart from the people, so the request can be taken back", () => {
|
||||
// A team is never among the assignable users, and a request that cannot be seen cannot be
|
||||
// undone — so the ones GitHub reports are carried, marked as the teams they are.
|
||||
const list = expectSuccess(
|
||||
decodeReviewerCandidatesJson(
|
||||
candidatesJson({
|
||||
assignable: [{ login: "octocat" }],
|
||||
requested: [{ slug: "reviewers", name: "Reviewers" }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(list.candidates).toEqual([
|
||||
{
|
||||
id: "reviewers",
|
||||
kind: "team",
|
||||
login: "reviewers",
|
||||
name: "Reviewers",
|
||||
avatarUrl: null,
|
||||
isRequested: true,
|
||||
},
|
||||
{
|
||||
id: "octocat",
|
||||
kind: "user",
|
||||
login: "octocat",
|
||||
name: null,
|
||||
avatarUrl: null,
|
||||
isRequested: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("says so when the repository has more people than the read asked for", () => {
|
||||
expect(
|
||||
expectSuccess(
|
||||
decodeReviewerCandidatesJson(
|
||||
candidatesJson({ assignable: [{ login: "octocat" }], hasNextPage: true }),
|
||||
),
|
||||
).truncated,
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reviewer request payload", () => {
|
||||
it("sends people and teams in the two lists GitHub keeps them in", () => {
|
||||
expect(
|
||||
JSON.parse(
|
||||
buildReviewerRequestJson([
|
||||
{ id: "octocat", kind: "user" },
|
||||
{ id: "reviewers", kind: "team" },
|
||||
{ id: "hubot", kind: "user" },
|
||||
]),
|
||||
),
|
||||
).toEqual({ reviewers: ["octocat", "hubot"], team_reviewers: ["reviewers"] });
|
||||
});
|
||||
|
||||
it("sends both lists even where one of them is empty, which is what GitHub reads", () => {
|
||||
expect(JSON.parse(buildReviewerRequestJson([{ id: "octocat", kind: "user" }]))).toEqual({
|
||||
reviewers: ["octocat"],
|
||||
team_reviewers: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("review submission payload", () => {
|
||||
it("sends the verdict, the summary and every line comment in one body", () => {
|
||||
const payload = JSON.parse(
|
||||
buildReviewSubmissionJson({
|
||||
verdict: "request-changes",
|
||||
body: "Two things.",
|
||||
comments: [
|
||||
{ path: "src/a.ts", line: 12, side: "right", body: "rename this" },
|
||||
{ path: "src/b.ts", line: 3, side: "left", body: "why remove?" },
|
||||
],
|
||||
}),
|
||||
) as Record<string, unknown>;
|
||||
expect(payload).toEqual({
|
||||
event: "REQUEST_CHANGES",
|
||||
body: "Two things.",
|
||||
comments: [
|
||||
{ path: "src/a.ts", line: 12, side: "RIGHT", body: "rename this" },
|
||||
{ path: "src/b.ts", line: 3, side: "LEFT", body: "why remove?" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("sends an approval with no words and no comments", () => {
|
||||
expect(
|
||||
JSON.parse(buildReviewSubmissionJson({ verdict: "approve", body: "", comments: [] })),
|
||||
).toEqual({ event: "APPROVE", body: "", comments: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodePullRequestFilesJson", () => {
|
||||
it("assembles a unified patch the files API does not return", () => {
|
||||
const result = expectSuccess(
|
||||
decodePullRequestFilesJson(
|
||||
JSON.stringify([
|
||||
{ filename: "src/app.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.patch).toBe(
|
||||
[
|
||||
"diff --git a/src/app.ts b/src/app.ts",
|
||||
"--- a/src/app.ts",
|
||||
"+++ b/src/app.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
expect(result.truncated).toBe(false);
|
||||
expect(result.rawCount).toBe(1);
|
||||
});
|
||||
|
||||
it("points an added file at /dev/null on the left and a removed one on the right", () => {
|
||||
const result = expectSuccess(
|
||||
decodePullRequestFilesJson(
|
||||
JSON.stringify([
|
||||
{ filename: "src/new.ts", status: "added", patch: "@@ -0,0 +1 @@\n+hello" },
|
||||
{ filename: "src/gone.ts", status: "removed", patch: "@@ -1 +0,0 @@\n-bye" },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.patch).toBe(
|
||||
[
|
||||
"diff --git a/src/new.ts b/src/new.ts",
|
||||
"new file mode 100644",
|
||||
"--- /dev/null",
|
||||
"+++ b/src/new.ts",
|
||||
"@@ -0,0 +1 @@",
|
||||
"+hello",
|
||||
"diff --git a/src/gone.ts b/src/gone.ts",
|
||||
"deleted file mode 100644",
|
||||
"--- a/src/gone.ts",
|
||||
"+++ /dev/null",
|
||||
"@@ -1 +0,0 @@",
|
||||
"-bye",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("names both paths of a rename, counting its hunks against the old one", () => {
|
||||
const result = expectSuccess(
|
||||
decodePullRequestFilesJson(
|
||||
JSON.stringify([
|
||||
{
|
||||
filename: "src/new.ts",
|
||||
status: "renamed",
|
||||
previous_filename: "src/old.ts",
|
||||
patch: "@@ -1 +1 @@\n-old\n+new",
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.patch).toBe(
|
||||
[
|
||||
"diff --git a/src/old.ts b/src/new.ts",
|
||||
"rename from src/old.ts",
|
||||
"rename to src/new.ts",
|
||||
"--- a/src/old.ts",
|
||||
"+++ b/src/new.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("still lists a file GitHub sent no hunks for, and says what was withheld", () => {
|
||||
const result = expectSuccess(
|
||||
decodePullRequestFilesJson(
|
||||
JSON.stringify([
|
||||
// Binary: it changed, and none of it can be shown.
|
||||
{ filename: "logo.png", status: "modified", additions: 4, deletions: 2 },
|
||||
{
|
||||
filename: "src/app.ts",
|
||||
status: "modified",
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
patch: "@@ -1 +1 @@\n-old\n+new",
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
// Dropping it would take the file out of the change altogether, not just its contents.
|
||||
expect(result.patch).toContain("diff --git a/logo.png b/logo.png");
|
||||
expect(result.patch).toContain("diff --git a/src/app.ts b/src/app.ts");
|
||||
expect(result.truncated).toBe(true);
|
||||
expect(result.rawCount).toBe(2);
|
||||
});
|
||||
|
||||
it("does not call a pure rename incomplete, since it has no hunks to withhold", () => {
|
||||
const result = expectSuccess(
|
||||
decodePullRequestFilesJson(
|
||||
JSON.stringify([
|
||||
{
|
||||
filename: "src/new.ts",
|
||||
previous_filename: "src/old.ts",
|
||||
status: "renamed",
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.patch).toContain("rename from src/old.ts");
|
||||
expect(result.truncated).toBe(false);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,455 @@
|
||||
import * as Result from "effect/Result";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
decodeCommitsJson,
|
||||
decodeMergeRequestDetailJson,
|
||||
decodeMergeRequestDiffsJson,
|
||||
decodeMergeRequestListJson,
|
||||
decodeNotesJson,
|
||||
decodeViewerJson,
|
||||
} from "./gitLabMergeRequestJson.ts";
|
||||
|
||||
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
|
||||
return JSON.stringify(
|
||||
entries.map((entry) => ({
|
||||
iid: 1,
|
||||
title: "Add the merge requests page",
|
||||
web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
|
||||
source_branch: "feat/page",
|
||||
target_branch: "main",
|
||||
created_at: "2026-07-01T00:00:00Z",
|
||||
updated_at: "2026-07-02T00:00:00Z",
|
||||
...entry,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
function detailJson(entry: Record<string, unknown>): string {
|
||||
return JSON.stringify({
|
||||
iid: 1,
|
||||
title: "Add the merge requests page",
|
||||
web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
|
||||
source_branch: "feat/page",
|
||||
target_branch: "main",
|
||||
created_at: "2026-07-01T00:00:00Z",
|
||||
updated_at: "2026-07-02T00:00:00Z",
|
||||
...entry,
|
||||
});
|
||||
}
|
||||
|
||||
function expectSuccess<A>(result: Result.Result<A, unknown>): A {
|
||||
expect(Result.isSuccess(result)).toBe(true);
|
||||
if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
|
||||
return result.success;
|
||||
}
|
||||
|
||||
describe("decodeMergeRequestListJson", () => {
|
||||
it("reads a merge request as a change request", () => {
|
||||
const batch = expectSuccess(
|
||||
decodeMergeRequestListJson(
|
||||
listJson([
|
||||
{
|
||||
iid: 42,
|
||||
author: { username: "bilal", name: "Bilal" },
|
||||
state: "opened",
|
||||
merge_status: "can_be_merged",
|
||||
draft: false,
|
||||
reviewers: [{ username: "julius" }],
|
||||
labels: ["backend", " "],
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(batch.items).toHaveLength(1);
|
||||
expect(batch.items[0]).toMatchObject({
|
||||
number: 42,
|
||||
author: { login: "bilal", name: "Bilal" },
|
||||
headBranch: "feat/page",
|
||||
baseBranch: "main",
|
||||
state: "open",
|
||||
isDraft: false,
|
||||
mergeability: "mergeable",
|
||||
reviewRequestLogins: ["julius"],
|
||||
labels: [{ name: "backend", color: null }],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports no line counts, which GitLab does not expose", () => {
|
||||
const batch = expectSuccess(decodeMergeRequestListJson(listJson([{}])));
|
||||
|
||||
expect(batch.items[0]).toMatchObject({ additions: 0, deletions: 0 });
|
||||
});
|
||||
|
||||
it("treats a merged timestamp as merged whatever the state says", () => {
|
||||
const batch = expectSuccess(
|
||||
decodeMergeRequestListJson(
|
||||
listJson([{ state: "opened", merged_at: "2026-07-03T00:00:00Z" }]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(batch.items[0]?.state).toBe("merged");
|
||||
});
|
||||
|
||||
it("keeps a locked merge request open", () => {
|
||||
const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ state: "locked" }])));
|
||||
|
||||
expect(batch.items[0]?.state).toBe("open");
|
||||
});
|
||||
|
||||
it("reads the legacy draft flag", () => {
|
||||
const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ work_in_progress: true }])));
|
||||
|
||||
expect(batch.items[0]?.isDraft).toBe(true);
|
||||
});
|
||||
|
||||
it("calls a conflicted merge request conflicting even while the merge check is pending", () => {
|
||||
const batch = expectSuccess(
|
||||
decodeMergeRequestListJson(listJson([{ merge_status: "checking", has_conflicts: true }])),
|
||||
);
|
||||
|
||||
expect(batch.items[0]?.mergeability).toBe("conflicting");
|
||||
});
|
||||
|
||||
it("leaves an unfinished merge check unknown", () => {
|
||||
const batch = expectSuccess(
|
||||
decodeMergeRequestListJson(listJson([{ merge_status: "checking" }])),
|
||||
);
|
||||
|
||||
expect(batch.items[0]?.mergeability).toBe("unknown");
|
||||
});
|
||||
|
||||
it("skips a malformed row but still counts it, so paging does not stop early", () => {
|
||||
const batch = expectSuccess(
|
||||
decodeMergeRequestListJson(
|
||||
JSON.stringify([{ iid: "not a number" }, ...JSON.parse(listJson([{}]))]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(batch.items).toHaveLength(1);
|
||||
expect(batch.rawIndexes).toEqual([1]);
|
||||
expect(batch.rawCount).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeMergeRequestDetailJson", () => {
|
||||
it("reads the description, file count and pipeline", () => {
|
||||
const detail = expectSuccess(
|
||||
decodeMergeRequestDetailJson(
|
||||
detailJson({
|
||||
description: "Ships the page.",
|
||||
changes_count: "3",
|
||||
reviewers: [{ username: "julius", name: "Julius" }],
|
||||
head_pipeline: {
|
||||
status: "success",
|
||||
web_url: "https://gitlab.com/acme/web/-/pipelines/9",
|
||||
source: "merge_request_event",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(detail.body).toBe("Ships the page.");
|
||||
expect(detail.changedFiles).toBe(3);
|
||||
expect(detail.reviewers).toEqual([{ login: "julius", name: "Julius", avatarUrl: null }]);
|
||||
expect(detail.checks).toEqual([
|
||||
{
|
||||
name: "Pipeline",
|
||||
status: "success",
|
||||
description: "merge_request_event",
|
||||
url: "https://gitlab.com/acme/web/-/pipelines/9",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("reads an uncounted change set as its floor", () => {
|
||||
const detail = expectSuccess(
|
||||
decodeMergeRequestDetailJson(detailJson({ changes_count: "1000+" })),
|
||||
);
|
||||
|
||||
expect(detail.changedFiles).toBe(1000);
|
||||
});
|
||||
|
||||
it("falls back to no file count when GitLab omits one", () => {
|
||||
const detail = expectSuccess(decodeMergeRequestDetailJson(detailJson({})));
|
||||
|
||||
expect(detail.changedFiles).toBe(0);
|
||||
});
|
||||
|
||||
it("maps a pipeline waiting on a person to neutral, not failure", () => {
|
||||
const detail = expectSuccess(
|
||||
decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
|
||||
);
|
||||
|
||||
expect(detail.checks[0]?.status).toBe("neutral");
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeViewerJson", () => {
|
||||
it("reads the signed-in username", () => {
|
||||
expect(expectSuccess(decodeViewerJson(JSON.stringify({ username: "bilal" })))).toBe("bilal");
|
||||
});
|
||||
|
||||
it("returns nothing when the account has no username", () => {
|
||||
expect(expectSuccess(decodeViewerJson(JSON.stringify({ username: " " })))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeNotesJson", () => {
|
||||
it("keeps comments and drops GitLab's own activity notes", () => {
|
||||
const notes = expectSuccess(
|
||||
decodeNotesJson(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: 1,
|
||||
body: "assigned to @bilal",
|
||||
system: true,
|
||||
created_at: "2026-07-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
body: "Looks good.",
|
||||
author: { username: "julius" },
|
||||
created_at: "2026-07-02T00:00:00Z",
|
||||
},
|
||||
{ id: 3, body: " ", created_at: "2026-07-03T00:00:00Z" },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(notes.comments).toHaveLength(1);
|
||||
expect(notes.comments[0]).toMatchObject({
|
||||
id: "2",
|
||||
kind: "issue-comment",
|
||||
body: "Looks good.",
|
||||
});
|
||||
// The raw count keeps the dropped notes visible to the caller, which needs them to page.
|
||||
expect(notes.rawCount).toBe(3);
|
||||
});
|
||||
|
||||
it("reads a line note as a review comment on its file", () => {
|
||||
const notes = expectSuccess(
|
||||
decodeNotesJson(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: 7,
|
||||
type: "DiffNote",
|
||||
body: "Rename this.",
|
||||
created_at: "2026-07-02T00:00:00Z",
|
||||
position: { new_path: "src/app.ts", old_path: "src/old.ts" },
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(notes.comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
|
||||
});
|
||||
|
||||
it("falls back to the old path for a note on a deleted line", () => {
|
||||
const notes = expectSuccess(
|
||||
decodeNotesJson(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: 8,
|
||||
type: "DiffNote",
|
||||
body: "Gone.",
|
||||
created_at: "2026-07-02T00:00:00Z",
|
||||
position: { new_path: null, old_path: "src/old.ts" },
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(notes.comments[0]?.path).toBe("src/old.ts");
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeCommitsJson", () => {
|
||||
it("returns commits oldest first", () => {
|
||||
const commits = expectSuccess(
|
||||
decodeCommitsJson(
|
||||
JSON.stringify([
|
||||
{ id: "bbb", title: "second", committed_date: "2026-07-02T00:00:00Z" },
|
||||
{ id: "aaa", title: "first", committed_date: "2026-07-01T00:00:00Z" },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(commits.map((commit) => commit.oid)).toEqual(["aaa", "bbb"]);
|
||||
});
|
||||
|
||||
it("skips commits whose id is empty", () => {
|
||||
const commits = expectSuccess(
|
||||
decodeCommitsJson(
|
||||
JSON.stringify([
|
||||
{ id: " ", title: "invalid", committed_date: "2026-07-02T00:00:00Z" },
|
||||
{ id: "aaa", committed_date: "2026-07-01T00:00:00Z" },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(commits.map((commit) => commit.oid)).toEqual(["aaa"]);
|
||||
});
|
||||
|
||||
it("falls back to the creation timestamp when there is no commit date", () => {
|
||||
const commits = expectSuccess(
|
||||
decodeCommitsJson(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "aaa",
|
||||
created_at: "2026-07-01T00:00:00+08:00",
|
||||
author_name: "Ada Lovelace",
|
||||
author_email: "[email protected]",
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(commits[0]).toMatchObject({
|
||||
oid: "aaa",
|
||||
committedDate: "2026-07-01T00:00:00+08:00",
|
||||
authors: [{ login: "Ada Lovelace", name: "Ada Lovelace", avatarUrl: null }],
|
||||
});
|
||||
});
|
||||
|
||||
it("carries commit additions and deletions when GitLab returns stats", () => {
|
||||
const commits = expectSuccess(
|
||||
decodeCommitsJson(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "aaa",
|
||||
committed_date: "2026-07-01T00:00:00Z",
|
||||
stats: { additions: 21, deletions: 8, total: 29 },
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(commits[0]).toMatchObject({ additions: 21, deletions: 8 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeMergeRequestDiffsJson", () => {
|
||||
it("assembles a unified patch GitLab does not return", () => {
|
||||
const result = expectSuccess(
|
||||
decodeMergeRequestDiffsJson(
|
||||
JSON.stringify([
|
||||
{
|
||||
old_path: "src/app.ts",
|
||||
new_path: "src/app.ts",
|
||||
diff: "@@ -1 +1 @@\n-old\n+new\n",
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.patch).toBe(
|
||||
[
|
||||
"diff --git a/src/app.ts b/src/app.ts",
|
||||
"--- a/src/app.ts",
|
||||
"+++ b/src/app.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
expect(result.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it("points a new file at /dev/null on the left and a deleted file on the right", () => {
|
||||
const result = expectSuccess(
|
||||
decodeMergeRequestDiffsJson(
|
||||
JSON.stringify([
|
||||
{
|
||||
old_path: "src/new.ts",
|
||||
new_path: "src/new.ts",
|
||||
new_file: true,
|
||||
b_mode: "100755",
|
||||
diff: "@@ -0,0 +1 @@\n+hello\n",
|
||||
},
|
||||
{
|
||||
old_path: "src/gone.ts",
|
||||
new_path: "src/gone.ts",
|
||||
deleted_file: true,
|
||||
diff: "@@ -1 +0,0 @@\n-bye\n",
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.patch).toContain("new file mode 100755");
|
||||
expect(result.patch).toContain("--- /dev/null");
|
||||
expect(result.patch).toContain("deleted file mode 100644");
|
||||
expect(result.patch).toContain("+++ /dev/null");
|
||||
});
|
||||
|
||||
it("records a rename so the patch names both paths", () => {
|
||||
const result = expectSuccess(
|
||||
decodeMergeRequestDiffsJson(
|
||||
JSON.stringify([
|
||||
{ old_path: "src/old.ts", new_path: "src/new.ts", renamed_file: true, diff: "" },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.patch).toContain("rename from src/old.ts");
|
||||
expect(result.patch).toContain("rename to src/new.ts");
|
||||
});
|
||||
|
||||
it("reports truncation for a file GitLab refused to inline", () => {
|
||||
const result = expectSuccess(
|
||||
decodeMergeRequestDiffsJson(
|
||||
JSON.stringify([{ old_path: "big.bin", new_path: "big.bin", diff: "", too_large: true }]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.truncated).toBe(true);
|
||||
expect(result.patch).toContain("diff --git a/big.bin b/big.bin");
|
||||
});
|
||||
|
||||
it("reports how many files GitLab returned, so the caller can page", () => {
|
||||
const result = expectSuccess(
|
||||
decodeMergeRequestDiffsJson(
|
||||
JSON.stringify(
|
||||
Array.from({ length: 3 }, (_, index) => ({
|
||||
old_path: `src/${index}.ts`,
|
||||
new_path: `src/${index}.ts`,
|
||||
diff: "@@ -1 +1 @@\n-a\n+b\n",
|
||||
})),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.rawCount).toBe(3);
|
||||
expect(result.truncated).toBe(false);
|
||||
expect(result.patch).toContain("src/2.ts");
|
||||
});
|
||||
|
||||
it("fails when GitLab did not return a list", () => {
|
||||
expect(Result.isFailure(decodeMergeRequestDiffsJson('{"message":"404"}'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("merge request viewer fields", () => {
|
||||
it("carries GitLab's own answer for whether this viewer can merge", () => {
|
||||
expect(
|
||||
expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: { can_merge: false } })))
|
||||
.viewerCanMerge,
|
||||
).toBe(false);
|
||||
expect(
|
||||
expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: { can_merge: true } })))
|
||||
.viewerCanMerge,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves merging permitted where GitLab answered without the field", () => {
|
||||
// Only the single-merge-request endpoint carries `user`, and an install that answers without
|
||||
// it has said nothing about the viewer rather than said no.
|
||||
expect(expectSuccess(decodeMergeRequestDetailJson(detailJson({}))).viewerCanMerge).toBe(true);
|
||||
expect(
|
||||
expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: null }))).viewerCanMerge,
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,698 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type {
|
||||
PullRequestActor,
|
||||
PullRequestCheck,
|
||||
PullRequestCheckStatus,
|
||||
PullRequestComment,
|
||||
PullRequestCommit,
|
||||
PullRequestLabel,
|
||||
PullRequestMergeability,
|
||||
PullRequestMergeCapabilities,
|
||||
PullRequestReviewThread,
|
||||
PullRequestReviewerCandidate,
|
||||
PullRequestState,
|
||||
} from "@t3tools/contracts";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
/**
|
||||
* GitLab's REST enums are decoded as plain strings and normalized here: a GitLab release that
|
||||
* adds a pipeline status or a merge status must not fail the whole payload.
|
||||
*/
|
||||
const RawUserSchema = Schema.Struct({
|
||||
/**
|
||||
* GitLab writes a merge request's reviewers as numeric ids and takes no usernames there, so the
|
||||
* id is carried alongside the handle rather than looked up again when a review is asked for.
|
||||
*/
|
||||
id: Schema.optional(Schema.Int),
|
||||
username: Schema.String,
|
||||
name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
const RawPipelineSchema = Schema.Struct({
|
||||
status: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
web_url: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
source: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
const RawMergeRequestSchema = Schema.Struct({
|
||||
iid: Schema.Int,
|
||||
title: Schema.String,
|
||||
web_url: Schema.String,
|
||||
description: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
author: Schema.optional(Schema.NullOr(RawUserSchema)),
|
||||
source_branch: Schema.String,
|
||||
target_branch: Schema.String,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
draft: Schema.optional(Schema.Boolean),
|
||||
work_in_progress: Schema.optional(Schema.Boolean),
|
||||
merge_status: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
has_conflicts: Schema.optional(Schema.NullOr(Schema.Boolean)),
|
||||
created_at: Schema.String,
|
||||
updated_at: Schema.String,
|
||||
merged_at: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
closed_at: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
|
||||
labels: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
|
||||
// A string, and "1000+" past GitLab's counting limit, so it is parsed rather than decoded.
|
||||
changes_count: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
head_pipeline: Schema.optional(Schema.NullOr(RawPipelineSchema)),
|
||||
/**
|
||||
* What the requesting account may do, which only the single-merge-request endpoint carries.
|
||||
* GitLab answers `can_merge` for this viewer against this merge request, so it already accounts
|
||||
* for the role, the approval rules and a protected target branch — none of which a project's
|
||||
* access level on its own would tell apart.
|
||||
*/
|
||||
user: Schema.optional(
|
||||
Schema.NullOr(Schema.Struct({ can_merge: Schema.optional(Schema.Boolean) })),
|
||||
),
|
||||
});
|
||||
|
||||
const RawNoteSchema = Schema.Struct({
|
||||
id: Schema.Int,
|
||||
body: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
author: Schema.optional(Schema.NullOr(RawUserSchema)),
|
||||
created_at: Schema.String,
|
||||
/** True for notes GitLab writes itself ("assigned to…"), which are events, not comments. */
|
||||
system: Schema.optional(Schema.Boolean),
|
||||
type: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
position: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
new_path: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
old_path: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
/**
|
||||
* A discussion note carrying its place in the diff, which is the shape the whole thread view
|
||||
* is built from. `resolved` lives on the note rather than on the discussion: GitLab calls a
|
||||
* discussion resolved once every resolvable note in it is.
|
||||
*/
|
||||
const RawDiscussionNoteSchema = Schema.Struct({
|
||||
id: Schema.Int,
|
||||
body: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
author: Schema.optional(Schema.NullOr(RawUserSchema)),
|
||||
created_at: Schema.String,
|
||||
system: Schema.optional(Schema.Boolean),
|
||||
resolvable: Schema.optional(Schema.Boolean),
|
||||
resolved: Schema.optional(Schema.NullOr(Schema.Boolean)),
|
||||
position: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
position_type: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
new_path: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
old_path: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
new_line: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
old_line: Schema.optional(Schema.NullOr(Schema.Int)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawDiscussionSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
notes: Schema.optional(Schema.NullOr(Schema.Array(RawDiscussionNoteSchema))),
|
||||
});
|
||||
|
||||
const RawDiffRefsSchema = Schema.Struct({
|
||||
diff_refs: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
base_sha: Schema.String,
|
||||
head_sha: Schema.String,
|
||||
start_sha: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawCommitSchema = Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
title: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
committed_date: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
created_at: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
parent_ids: Schema.optional(Schema.Array(Schema.String)),
|
||||
author_name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
author_email: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
stats: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
additions: Schema.optional(Schema.Int),
|
||||
deletions: Schema.optional(Schema.Int),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawDiffSchema = Schema.Struct({
|
||||
old_path: Schema.String,
|
||||
new_path: Schema.String,
|
||||
a_mode: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
b_mode: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
new_file: Schema.optional(Schema.Boolean),
|
||||
renamed_file: Schema.optional(Schema.Boolean),
|
||||
deleted_file: Schema.optional(Schema.Boolean),
|
||||
diff: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
/** GitLab omits the hunks for a file it considers too large to inline. */
|
||||
too_large: Schema.optional(Schema.NullOr(Schema.Boolean)),
|
||||
/** And for one it collapsed, which withholds them the same way. */
|
||||
collapsed: Schema.optional(Schema.NullOr(Schema.Boolean)),
|
||||
});
|
||||
|
||||
const RawViewerSchema = Schema.Struct({
|
||||
username: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
/** A GitLab project settles on one merge strategy plus an optional squash. */
|
||||
const RawProjectMergeSettingsSchema = Schema.Struct({
|
||||
merge_method: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
squash_option: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
export interface GitLabMergeRequestListItem {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly author: PullRequestActor | null;
|
||||
readonly headBranch: string;
|
||||
readonly baseBranch: string;
|
||||
readonly state: PullRequestState;
|
||||
readonly isDraft: boolean;
|
||||
readonly mergeability: PullRequestMergeability;
|
||||
/**
|
||||
* GitLab reports neither added nor removed lines on a merge request, so both stay zero and
|
||||
* the surface omits the stat. The Code tab counts them from the patch it already fetched.
|
||||
*/
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
readonly reviewRequestLogins: ReadonlyArray<string>;
|
||||
readonly labels: ReadonlyArray<PullRequestLabel>;
|
||||
}
|
||||
|
||||
export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
|
||||
readonly body: string;
|
||||
readonly changedFiles: number;
|
||||
readonly mergedAt: string | null;
|
||||
readonly closedAt: string | null;
|
||||
readonly reviewers: ReadonlyArray<PullRequestActor>;
|
||||
readonly checks: ReadonlyArray<PullRequestCheck>;
|
||||
/** False only where GitLab said so; an answer without the field leaves merging permitted. */
|
||||
readonly viewerCanMerge: boolean;
|
||||
/** The reviewers as GitLab addresses them, which is what writing the set back takes. */
|
||||
readonly reviewerIds: ReadonlyArray<number>;
|
||||
}
|
||||
|
||||
function trimmed(value: string | null | undefined): string | null {
|
||||
const text = value?.trim() ?? "";
|
||||
return text.length > 0 ? text : null;
|
||||
}
|
||||
|
||||
function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
|
||||
const login = trimmed(raw?.username);
|
||||
return login === null
|
||||
? null
|
||||
: { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
|
||||
}
|
||||
|
||||
function toState(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): PullRequestState {
|
||||
if (trimmed(raw.merged_at) !== null) return "merged";
|
||||
switch (raw.state?.trim().toLowerCase()) {
|
||||
case "merged":
|
||||
return "merged";
|
||||
case "closed":
|
||||
return "closed";
|
||||
default:
|
||||
// `locked` is an open merge request whose discussion is locked.
|
||||
return "open";
|
||||
}
|
||||
}
|
||||
|
||||
function toMergeability(
|
||||
raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
|
||||
): PullRequestMergeability {
|
||||
if (raw.has_conflicts === true) return "conflicting";
|
||||
switch (raw.merge_status?.trim().toLowerCase()) {
|
||||
case "can_be_merged":
|
||||
return "mergeable";
|
||||
case "cannot_be_merged":
|
||||
return "conflicting";
|
||||
default:
|
||||
// `unchecked` and `checking` mean GitLab has not finished the merge check yet.
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function toLabels(raw: ReadonlyArray<string> | null | undefined): ReadonlyArray<PullRequestLabel> {
|
||||
// GitLab returns label names only, so there is no colour to carry.
|
||||
return (raw ?? []).flatMap((label) => {
|
||||
const name = trimmed(label);
|
||||
return name === null ? [] : [{ name, color: null }];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* "3" for a counted change set, "1000+" once GitLab gives up counting. The leading number is
|
||||
* the floor either way, which reads better than dropping an uncounted change set to nothing.
|
||||
*/
|
||||
function toChangedFiles(value: string | null | undefined): number {
|
||||
const parsed = Number.parseInt(value?.trim() ?? "", 10);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
|
||||
}
|
||||
|
||||
function toPipelineStatus(value: string | null | undefined): PullRequestCheckStatus {
|
||||
switch (value?.trim().toLowerCase()) {
|
||||
case "success":
|
||||
return "success";
|
||||
case "failed":
|
||||
return "failure";
|
||||
case "canceled":
|
||||
case "cancelling":
|
||||
return "cancelled";
|
||||
case "skipped":
|
||||
return "skipped";
|
||||
// A pipeline waiting on a person is not progress, and it is not a failure either.
|
||||
case "manual":
|
||||
case "scheduled":
|
||||
return "neutral";
|
||||
default:
|
||||
return "pending";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GitLab has no per-job check list on a merge request, so its pipeline is reported as the one
|
||||
* check. The jobs behind it stay one click away through the pipeline URL.
|
||||
*/
|
||||
function toChecks(
|
||||
raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
|
||||
): ReadonlyArray<PullRequestCheck> {
|
||||
const pipeline = raw.head_pipeline;
|
||||
if (!pipeline) return [];
|
||||
return [
|
||||
{
|
||||
name: "Pipeline",
|
||||
status: toPipelineStatus(pipeline.status),
|
||||
description: trimmed(pipeline.source),
|
||||
url: trimmed(pipeline.web_url),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function toListItem(
|
||||
raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
|
||||
): GitLabMergeRequestListItem {
|
||||
return {
|
||||
number: raw.iid,
|
||||
title: raw.title,
|
||||
url: raw.web_url,
|
||||
author: toActor(raw.author),
|
||||
headBranch: raw.source_branch,
|
||||
baseBranch: raw.target_branch,
|
||||
state: toState(raw),
|
||||
isDraft: raw.draft ?? raw.work_in_progress ?? false,
|
||||
mergeability: toMergeability(raw),
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
createdAt: raw.created_at,
|
||||
updatedAt: raw.updated_at,
|
||||
reviewRequestLogins: (raw.reviewers ?? []).flatMap((reviewer) => {
|
||||
const login = trimmed(reviewer.username);
|
||||
return login === null ? [] : [login];
|
||||
}),
|
||||
labels: toLabels(raw.labels),
|
||||
};
|
||||
}
|
||||
|
||||
function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail {
|
||||
const listItem = toListItem(raw);
|
||||
return {
|
||||
...listItem,
|
||||
body: raw.description ?? "",
|
||||
changedFiles: toChangedFiles(raw.changes_count),
|
||||
mergedAt: trimmed(raw.merged_at),
|
||||
closedAt: trimmed(raw.closed_at),
|
||||
// Built from the reviewers themselves rather than from their logins, so the avatars survive.
|
||||
reviewers: (raw.reviewers ?? []).flatMap((reviewer) => {
|
||||
const actor = toActor(reviewer);
|
||||
return actor === null ? [] : [actor];
|
||||
}),
|
||||
checks: toChecks(raw),
|
||||
viewerCanMerge: raw.user?.can_merge !== false,
|
||||
reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) =>
|
||||
reviewer.id === undefined ? [] : [reviewer.id],
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
|
||||
const decodeMergeRequestEntry = Schema.decodeUnknownExit(RawMergeRequestSchema);
|
||||
const decodeMergeRequest = decodeJsonResult(RawMergeRequestSchema);
|
||||
const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
|
||||
const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
|
||||
const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
|
||||
const decodeCommit = decodeJsonResult(RawCommitSchema);
|
||||
const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema);
|
||||
const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema);
|
||||
const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema);
|
||||
const decodeViewer = decodeJsonResult(RawViewerSchema);
|
||||
const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema);
|
||||
|
||||
type DecodeFailure = Cause.Cause<Schema.SchemaError>;
|
||||
|
||||
export interface GitLabProjectUsers {
|
||||
readonly candidates: ReadonlyArray<PullRequestReviewerCandidate>;
|
||||
/** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
|
||||
readonly rawCount: number;
|
||||
}
|
||||
|
||||
export interface GitLabMergeRequestListBatch {
|
||||
readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
|
||||
/** Zero-based positions of the decoded items in GitLab's raw page. */
|
||||
readonly rawIndexes: ReadonlyArray<number>;
|
||||
/** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
|
||||
readonly rawCount: number;
|
||||
}
|
||||
|
||||
/** Malformed entries are skipped rather than failing the batch: one unexpected merge request
|
||||
* must not blank the whole list. */
|
||||
export function decodeMergeRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<GitLabMergeRequestListBatch, DecodeFailure> {
|
||||
const decoded = decodeUnknownList(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const items: GitLabMergeRequestListItem[] = [];
|
||||
const rawIndexes: number[] = [];
|
||||
for (const [rawIndex, entry] of decoded.success.entries()) {
|
||||
const item = decodeMergeRequestEntry(entry);
|
||||
if (Exit.isSuccess(item)) {
|
||||
items.push(toListItem(item.value));
|
||||
rawIndexes.push(rawIndex);
|
||||
}
|
||||
}
|
||||
return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
|
||||
}
|
||||
|
||||
export function decodeMergeRequestDetailJson(
|
||||
raw: string,
|
||||
): Result.Result<GitLabMergeRequestDetail, DecodeFailure> {
|
||||
const decoded = decodeMergeRequest(raw);
|
||||
return Result.isSuccess(decoded)
|
||||
? Result.succeed(toDetail(decoded.success))
|
||||
: Result.fail(decoded.failure);
|
||||
}
|
||||
|
||||
export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
|
||||
const decoded = decodeViewer(raw);
|
||||
return Result.isSuccess(decoded)
|
||||
? Result.succeed(trimmed(decoded.success.username))
|
||||
: Result.fail(decoded.failure);
|
||||
}
|
||||
|
||||
/**
|
||||
* The people with access to the project, which `GET /projects/:id/users` answers with — the same
|
||||
* list GitLab's own reviewer field is filled from, including the members a group above the project
|
||||
* lends it. A malformed row is skipped rather than failing the menu it belongs to.
|
||||
*
|
||||
* Nobody is marked requested here: who has been asked lives on the merge request, and only the
|
||||
* caller holds both.
|
||||
*/
|
||||
export function decodeProjectUsersJson(
|
||||
raw: string,
|
||||
): Result.Result<GitLabProjectUsers, DecodeFailure> {
|
||||
const decoded = decodeUnknownList(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const candidates: PullRequestReviewerCandidate[] = [];
|
||||
for (const entry of decoded.success) {
|
||||
const user = decodeUserEntry(entry);
|
||||
if (Exit.isFailure(user) || user.value.id === undefined) continue;
|
||||
const actor = toActor(user.value);
|
||||
if (actor === null) continue;
|
||||
candidates.push({
|
||||
...actor,
|
||||
id: String(user.value.id),
|
||||
kind: "user",
|
||||
isRequested: false,
|
||||
});
|
||||
}
|
||||
return Result.succeed({ candidates, rawCount: decoded.success.length });
|
||||
}
|
||||
|
||||
/**
|
||||
* GitLab settles the strategy per project rather than offering all three per merge request:
|
||||
* `merge_method` picks one of merge commit, semi-linear or fast-forward, and squashing is a
|
||||
* separate switch. An unrecognized setting offers nothing rather than offering a strategy the
|
||||
* project forbids.
|
||||
*/
|
||||
export function decodeProjectMergeCapabilitiesJson(
|
||||
raw: string,
|
||||
): Result.Result<PullRequestMergeCapabilities, DecodeFailure> {
|
||||
const decoded = decodeProjectMergeSettings(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const mergeMethod = decoded.success.merge_method?.trim().toLowerCase();
|
||||
const squashOption = decoded.success.squash_option?.trim().toLowerCase();
|
||||
return Result.succeed({
|
||||
merge: mergeMethod === "merge",
|
||||
// Both semi-linear and fast-forward histories are reached by rebasing onto the target.
|
||||
rebase: mergeMethod === "rebase_merge" || mergeMethod === "ff",
|
||||
// Only GitLab's own enabling values. An absent or unrecognized setting offers nothing,
|
||||
// rather than offering a squash the project may forbid.
|
||||
squash:
|
||||
squashOption === "always" || squashOption === "default_on" || squashOption === "default_off",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Comments only. System notes are GitLab's own activity feed entries, and a `DiffNote` is the
|
||||
* root of a line-level discussion, which is what the review-comment kind means.
|
||||
*
|
||||
* The raw note count comes back alongside, because dropping notes hides whether the page was
|
||||
* full: a caller cannot tell "no more notes" from "a page of activity entries" without it.
|
||||
*/
|
||||
/** The three revisions a positioned comment is written against. */
|
||||
export interface GitLabDiffRefs {
|
||||
readonly baseSha: string;
|
||||
readonly headSha: string;
|
||||
readonly startSha: string;
|
||||
}
|
||||
|
||||
export interface GitLabDiscussions {
|
||||
readonly threads: ReadonlyArray<PullRequestReviewThread>;
|
||||
/** Discussions GitLab returned, counted before decoding, so a skipped one still counts. */
|
||||
readonly rawCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Positioned discussions only. GitLab returns the merge request's whole conversation here,
|
||||
* including the plain notes the timeline already shows, and only a positioned one belongs
|
||||
* against a line of the diff.
|
||||
*/
|
||||
export function decodeDiscussionsJson(
|
||||
raw: string,
|
||||
): Result.Result<GitLabDiscussions, DecodeFailure> {
|
||||
const decoded = decodeUnknownList(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const threads: PullRequestReviewThread[] = [];
|
||||
for (const entry of decoded.success) {
|
||||
const discussion = decodeDiscussionEntry(entry);
|
||||
if (!Exit.isSuccess(discussion)) continue;
|
||||
const notes = (discussion.value.notes ?? []).filter((note) => note.system !== true);
|
||||
const root = notes[0];
|
||||
const position = root?.position;
|
||||
if (root === undefined || !position || position.position_type !== "text") continue;
|
||||
// A comment on an added or context line carries `new_line`; one on a removed line carries
|
||||
// only `old_line`, and belongs against the file as it was.
|
||||
const side = position.new_line === null || position.new_line === undefined ? "left" : "right";
|
||||
const path = trimmed(side === "left" ? position.old_path : position.new_path);
|
||||
const line = side === "left" ? position.old_line : position.new_line;
|
||||
if (path === null) continue;
|
||||
threads.push({
|
||||
id: discussion.value.id,
|
||||
path,
|
||||
line: typeof line === "number" && line > 0 ? line : null,
|
||||
side,
|
||||
isResolved: root.resolved === true,
|
||||
// GitLab reports no equivalent of "written against a line that has since moved", so a
|
||||
// thread the diff cannot place is worked out from the diff itself rather than claimed
|
||||
// here.
|
||||
isOutdated: false,
|
||||
comments: notes.map((note) => ({
|
||||
id: String(note.id),
|
||||
author: toActor(note.author),
|
||||
body: note.body ?? "",
|
||||
createdAt: note.created_at,
|
||||
url: null,
|
||||
})),
|
||||
});
|
||||
}
|
||||
return Result.succeed({ threads, rawCount: decoded.success.length });
|
||||
}
|
||||
|
||||
export function decodeDiffRefsJson(
|
||||
raw: string,
|
||||
): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
|
||||
const decoded = decodeDiffRefs(raw);
|
||||
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
|
||||
const refs = decoded.success.diff_refs;
|
||||
return Result.succeed(
|
||||
refs ? { baseSha: refs.base_sha, headSha: refs.head_sha, startSha: refs.start_sha } : null,
|
||||
);
|
||||
}
|
||||
|
||||
export function decodeNotesJson(
|
||||
raw: string,
|
||||
): Result.Result<
|
||||
{ readonly comments: ReadonlyArray<PullRequestComment>; readonly rawCount: number },
|
||||
DecodeFailure
|
||||
> {
|
||||
const decoded = decodeUnknownList(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const comments: PullRequestComment[] = [];
|
||||
for (const entry of decoded.success) {
|
||||
const note = decodeNoteEntry(entry);
|
||||
if (Exit.isFailure(note)) continue;
|
||||
const value = note.value;
|
||||
if (value.system === true) continue;
|
||||
const body = value.body ?? "";
|
||||
if (body.trim().length === 0) continue;
|
||||
const isDiffNote = value.type?.trim() === "DiffNote";
|
||||
comments.push({
|
||||
id: String(value.id),
|
||||
kind: isDiffNote ? "review-comment" : "issue-comment",
|
||||
author: toActor(value.author),
|
||||
body,
|
||||
createdAt: value.created_at,
|
||||
url: null,
|
||||
path: trimmed(value.position?.new_path) ?? trimmed(value.position?.old_path),
|
||||
reviewState: null,
|
||||
});
|
||||
}
|
||||
return Result.succeed({ comments, rawCount: decoded.success.length });
|
||||
}
|
||||
|
||||
export function decodeCommitsJson(
|
||||
raw: string,
|
||||
): Result.Result<ReadonlyArray<PullRequestCommit>, DecodeFailure> {
|
||||
const decoded = decodeUnknownList(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const commits: PullRequestCommit[] = [];
|
||||
for (const entry of decoded.success) {
|
||||
const commit = decodeCommitEntry(entry);
|
||||
if (Exit.isFailure(commit)) continue;
|
||||
const committedDate = trimmed(commit.value.committed_date) ?? trimmed(commit.value.created_at);
|
||||
if (committedDate === null) continue;
|
||||
commits.push({
|
||||
oid: commit.value.id,
|
||||
messageHeadline: commit.value.title ?? "",
|
||||
committedDate,
|
||||
...(commit.value.stats === null || commit.value.stats === undefined
|
||||
? {}
|
||||
: {
|
||||
additions: Math.max(0, commit.value.stats.additions ?? 0),
|
||||
deletions: Math.max(0, commit.value.stats.deletions ?? 0),
|
||||
}),
|
||||
authors: (() => {
|
||||
const login = trimmed(commit.value.author_name) ?? trimmed(commit.value.author_email);
|
||||
return login === null
|
||||
? []
|
||||
: [{ login, name: trimmed(commit.value.author_name), avatarUrl: null }];
|
||||
})(),
|
||||
});
|
||||
}
|
||||
// GitLab lists a merge request's commits newest first; the timeline reads oldest first.
|
||||
return Result.succeed(commits.toReversed());
|
||||
}
|
||||
|
||||
/** The exact comparison GitLab uses for a commit-scoped diff. */
|
||||
export function decodeCommitDiffRefsJson(
|
||||
raw: string,
|
||||
): Result.Result<GitLabDiffRefs | null, DecodeFailure> {
|
||||
const decoded = decodeCommit(raw);
|
||||
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
|
||||
const baseSha = trimmed(decoded.success.parent_ids?.[0]);
|
||||
const headSha = trimmed(decoded.success.id);
|
||||
return Result.succeed(
|
||||
baseSha === null || headSha === null ? null : { baseSha, headSha, startSha: baseSha },
|
||||
);
|
||||
}
|
||||
|
||||
function diffHeaderPaths(raw: Schema.Schema.Type<typeof RawDiffSchema>): {
|
||||
readonly from: string;
|
||||
readonly to: string;
|
||||
} {
|
||||
return {
|
||||
from: raw.new_file === true ? "/dev/null" : `a/${raw.old_path}`,
|
||||
to: raw.deleted_file === true ? "/dev/null" : `b/${raw.new_path}`,
|
||||
};
|
||||
}
|
||||
|
||||
export interface GitLabMergeRequestPatch {
|
||||
readonly patch: string;
|
||||
/** At least one file's hunks were withheld by GitLab as too large to inline. */
|
||||
readonly truncated: boolean;
|
||||
/** Files GitLab returned, counted before decoding, so the caller can page. */
|
||||
readonly rawCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitLab returns hunks per file with no `diff --git` header, so the unified patch every diff
|
||||
* viewer expects is assembled here. This decodes one page; walking pages is the caller's job,
|
||||
* which is why the raw file count comes back with the patch.
|
||||
*/
|
||||
export function decodeMergeRequestDiffsJson(
|
||||
raw: string,
|
||||
): Result.Result<GitLabMergeRequestPatch, DecodeFailure> {
|
||||
const decoded = decodeUnknownList(raw);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Result.fail(decoded.failure);
|
||||
}
|
||||
const sections: string[] = [];
|
||||
let truncated = false;
|
||||
for (const entry of decoded.success) {
|
||||
const file = decodeDiffEntry(entry);
|
||||
if (Exit.isFailure(file)) continue;
|
||||
const value = file.value;
|
||||
const hunks = value.diff ?? "";
|
||||
if (hunks.length === 0) {
|
||||
// A file GitLab declined to inline still belongs in the file list, header only.
|
||||
truncated = truncated || value.too_large === true || value.collapsed === true;
|
||||
}
|
||||
const { from, to } = diffHeaderPaths(value);
|
||||
const header = [
|
||||
`diff --git a/${value.old_path} b/${value.new_path}`,
|
||||
...(value.new_file === true ? [`new file mode ${value.b_mode ?? "100644"}`] : []),
|
||||
...(value.deleted_file === true ? [`deleted file mode ${value.a_mode ?? "100644"}`] : []),
|
||||
...(value.renamed_file === true
|
||||
? [`rename from ${value.old_path}`, `rename to ${value.new_path}`]
|
||||
: []),
|
||||
`--- ${from}`,
|
||||
`+++ ${to}`,
|
||||
].join("\n");
|
||||
sections.push(hunks.length === 0 ? header : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
|
||||
}
|
||||
return Result.succeed({
|
||||
patch: sections.join("\n"),
|
||||
truncated,
|
||||
rawCount: decoded.success.length,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { AuthOrchestrationReadScope, EnvironmentHttpApi } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
|
||||
import { annotateEnvironmentRequest, requireEnvironmentScope } from "../auth/http.ts";
|
||||
import * as PullRequestService from "./PullRequestService.ts";
|
||||
|
||||
/** The patch is often the largest PR payload and benefits from HTTP compression and flow control. */
|
||||
export const pullRequestHttpApiLayer = HttpApiBuilder.group(
|
||||
EnvironmentHttpApi,
|
||||
"pullRequests",
|
||||
Effect.fnUntraced(function* (handlers) {
|
||||
const pullRequests = yield* PullRequestService.PullRequestService;
|
||||
return handlers.handle(
|
||||
"diff",
|
||||
Effect.fn("environment.pullRequests.diff")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
|
||||
return yield* pullRequests.diff(args.payload);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
HostProcessEnvironment,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { afterEach, assert, describe, expect, it, vi } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
|
||||
@@ -12,6 +12,36 @@ import { ServerConfig } from "../config.ts";
|
||||
import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts";
|
||||
|
||||
describe("ResourceMonitorBinary", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it.effect("skips Linux libc detection on Windows", () =>
|
||||
Effect.gen(function* () {
|
||||
const getReport = vi.spyOn(process.report, "getReport").mockImplementation(() => {
|
||||
throw new Error("Linux libc detection must not run on Windows");
|
||||
});
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-resource-monitor-binary-",
|
||||
});
|
||||
const binaryPath = `${baseDir}/t3-resource-monitor.exe`;
|
||||
yield* fileSystem.writeFileString(binaryPath, "binary");
|
||||
|
||||
const service = yield* ResourceMonitorBinary.make().pipe(
|
||||
Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Effect.provideService(HostProcessPlatform, "win32"),
|
||||
Effect.provideService(HostProcessArchitecture, "arm64"),
|
||||
Effect.provideService(HostProcessEnvironment, {
|
||||
T3CODE_RESOURCE_MONITOR_PATH: binaryPath,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* service.resolve, binaryPath);
|
||||
expect(getReport).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolves an executable override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -106,7 +106,7 @@ export function resourceMonitorPlatformKey(
|
||||
export function resourceMonitorRustTarget(
|
||||
platform: NodeJS.Platform,
|
||||
architecture: NodeJS.Architecture,
|
||||
linuxLibc: ResourceMonitorLinuxLibc,
|
||||
linuxLibc?: ResourceMonitorLinuxLibc,
|
||||
): string | undefined {
|
||||
if (platform === "darwin") {
|
||||
return architecture === "arm64"
|
||||
@@ -142,7 +142,7 @@ export const make = Effect.fn("resourceTelemetry.resourceMonitorBinary.make")(fu
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const architecture = yield* HostProcessArchitecture;
|
||||
const environment = yield* HostProcessEnvironment;
|
||||
const linuxLibc = yield* ResourceMonitorHostLinuxLibc;
|
||||
const linuxLibc = platform === "linux" ? yield* ResourceMonitorHostLinuxLibc : undefined;
|
||||
const executableName = binaryName(platform);
|
||||
const platformKey = resourceMonitorPlatformKey(platform, architecture);
|
||||
const rustTarget = resourceMonitorRustTarget(platform, architecture, linuxLibc);
|
||||
|
||||
@@ -5233,6 +5233,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
},
|
||||
branch: "feature/demo",
|
||||
worktreePath: null,
|
||||
isOnPullRequestHead: true,
|
||||
}),
|
||||
},
|
||||
gitVcsDriver: {
|
||||
|
||||
@@ -21,6 +21,9 @@ import {
|
||||
import { fixPath } from "./os-jank.ts";
|
||||
import { websocketRpcRouteLayer } from "./ws.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import { pullRequestHttpApiLayer } from "./pullRequest/http.ts";
|
||||
import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts";
|
||||
import * as PullRequestService from "./pullRequest/PullRequestService.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
|
||||
@@ -429,12 +432,20 @@ const commandReadinessLayer = HttpRouter.middleware(
|
||||
{ global: true },
|
||||
);
|
||||
|
||||
const PullRequestServiceLive = PullRequestService.layer.pipe(
|
||||
// One registry entry per supported host; the service only knows the registry.
|
||||
Layer.provide(PullRequestProviderRegistry.layer),
|
||||
Layer.provide(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provide(VcsProcess.layer),
|
||||
);
|
||||
|
||||
export const makeRoutesLayer = Layer.mergeAll(
|
||||
Layer.mergeAll(
|
||||
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
|
||||
Layer.provide(authHttpApiLayer),
|
||||
Layer.provide(connectHttpApiLayer),
|
||||
Layer.provide(orchestrationHttpApiLayer),
|
||||
Layer.provide(pullRequestHttpApiLayer),
|
||||
Layer.provide(serverEnvironmentHttpApiLayer),
|
||||
Layer.provide(environmentAuthenticatedAuthLayer),
|
||||
),
|
||||
@@ -445,6 +456,9 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
),
|
||||
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
|
||||
).pipe(
|
||||
// Both transports consume the same service instance, so caches single-flight across clients
|
||||
// and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
|
||||
Layer.provide(PullRequestServiceLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
Layer.provide(ServerSelfUpdate.layer),
|
||||
Layer.provide(commandReadinessLayer),
|
||||
|
||||
@@ -756,3 +756,113 @@ it.effect("checks out fork pull requests through an ensured fork remote", () =>
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("refuses a url that points away from the configured Bitbucket", () => {
|
||||
// A whole url reaches `request` from inside a response — a pagination cursor, say — so
|
||||
// following one off-host would hand the account's credentials to whoever wrote it.
|
||||
const { layer, execute } = makeLayer({ response: () => new Response("{}", { status: 200 }) });
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
bitbucket.request({ method: "GET", url: "https://attacker.example/2.0/repositories" }),
|
||||
);
|
||||
|
||||
assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
|
||||
// Nothing was sent at all, so no header travelled anywhere.
|
||||
assert.strictEqual(execute.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("keeps only the host of a url it refuses, never its query", () =>
|
||||
Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
bitbucket.request({
|
||||
method: "GET",
|
||||
// A signed link, whose query is the credential.
|
||||
url: "https://attacker.example/asset?signature=secret-token",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
|
||||
assert.strictEqual(
|
||||
error._tag === "BitbucketUntrustedUrlError" ? error.host : "",
|
||||
"https://attacker.example",
|
||||
);
|
||||
assert.notInclude(error.message, "secret-token");
|
||||
}).pipe(Effect.provide(makeLayer({ response: () => new Response("{}", { status: 200 }) }).layer)),
|
||||
);
|
||||
|
||||
it.effect("does not follow a redirect off the configured Bitbucket", () =>
|
||||
Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
bitbucket.request({ method: "GET", url: "/repositories/acme/web/pullrequests/1/diff" }),
|
||||
);
|
||||
|
||||
// The client would carry every header to the new host, so the hop is checked here instead.
|
||||
assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
response: () =>
|
||||
new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: "https://attacker.example/stolen" },
|
||||
}),
|
||||
}).layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("follows a redirect that stays on the configured Bitbucket", () =>
|
||||
Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
|
||||
const result = yield* bitbucket.request({
|
||||
method: "GET",
|
||||
url: "/repositories/acme/web/pullrequests/1/diff",
|
||||
});
|
||||
|
||||
// Bitbucket serves a diff as a redirect to a commit range, so the hop has to be followed.
|
||||
assert.strictEqual(result.body, "diff --git a/a.ts b/a.ts");
|
||||
assert.isFalse(result.truncated);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
response: (request) =>
|
||||
request.url.endsWith("/pullrequests/1/diff")
|
||||
? new Response(null, {
|
||||
status: 302,
|
||||
// The same host the harness configures, which is not bitbucket.org: a
|
||||
// self-hosted base url has to be trusted on its own terms.
|
||||
headers: { location: "https://api.test.local/2.0/repositories/acme/web/diff/abc" },
|
||||
})
|
||||
: new Response("diff --git a/a.ts b/a.ts", { status: 200 }),
|
||||
}).layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("cuts a response short rather than reading an unbounded diff into memory", () =>
|
||||
Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
|
||||
const result = yield* bitbucket.request({
|
||||
method: "GET",
|
||||
url: "/repositories/acme/web/pullrequests/1/diff",
|
||||
maxBytes: 8,
|
||||
});
|
||||
|
||||
assert.strictEqual(result.body, "12345678");
|
||||
assert.isTrue(result.truncated);
|
||||
// Bounded as the body arrives, so an oversized diff is never held whole.
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({ response: () => new Response("1234567890", { status: 200 }) }).layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -22,11 +22,16 @@ import {
|
||||
normalizeBitbucketPullRequestRecord,
|
||||
type NormalizedBitbucketPullRequestRecord,
|
||||
} from "./bitbucketPullRequests.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
|
||||
/** A response body past this is cut short, so one huge diff cannot exhaust the server. */
|
||||
const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
||||
/** Bitbucket redirects a diff once; this leaves room without following a chain forever. */
|
||||
const MAX_REDIRECTS = 3;
|
||||
|
||||
const BitbucketApiEnvConfig = Config.all({
|
||||
baseUrl: Config.string("T3CODE_BITBUCKET_API_BASE_URL").pipe(
|
||||
@@ -47,6 +52,9 @@ const BitbucketApiOperation = Schema.Literals([
|
||||
"createPullRequest",
|
||||
"probeAuth",
|
||||
"checkoutPullRequest",
|
||||
// The raw escape hatch. Callers name their own operation in their own error, the way the
|
||||
// pull request wrappers do on top of `gh` and `glab`.
|
||||
"request",
|
||||
]);
|
||||
type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
|
||||
|
||||
@@ -56,8 +64,12 @@ export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<Bit
|
||||
repository: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Bitbucket repositories must be specified as workspace/repository.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
|
||||
return `Bitbucket API failed in createRepository: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,8 +80,12 @@ export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequ
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Failed to send the Bitbucket request.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,8 +97,12 @@ export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketRes
|
||||
responseBodyLength: NonNegativeInt,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Bitbucket returned HTTP ${this.status}.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,8 +114,12 @@ export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<Bitb
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Bitbucket returned HTTP ${this.status}.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,8 +131,12 @@ export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<Bitbuc
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Bitbucket returned invalid JSON for the requested resource.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,8 +147,12 @@ export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Failed to resolve VCS repository for ${this.cwd}.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;
|
||||
return `Bitbucket API failed in resolveRepository: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,8 +163,12 @@ export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Failed to list remotes for ${this.cwd}.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;
|
||||
return `Bitbucket API failed in resolveRepository: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,8 +178,12 @@ export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorCl
|
||||
cwd: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `No Bitbucket repository remote was detected for ${this.cwd}.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;
|
||||
return `Bitbucket API failed in resolveRepository: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,8 +195,12 @@ export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<B
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Failed to read pull request body file ${this.bodyFile}.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;
|
||||
return `Bitbucket API failed in createPullRequest: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,12 +212,38 @@ export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketChe
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Failed to check out the Bitbucket pull request.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.";
|
||||
return `Bitbucket API failed in checkoutPullRequest: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A url that does not belong to the configured Bitbucket. Refused rather than followed, because
|
||||
* the request carries the account's credentials and a url that came back in a response — a
|
||||
* pagination cursor, or the target of a redirect — is not this server's to trust.
|
||||
*/
|
||||
export class BitbucketUntrustedUrlError extends Schema.TaggedErrorClass<BitbucketUntrustedUrlError>()(
|
||||
"BitbucketUntrustedUrlError",
|
||||
{
|
||||
/** The host only. A rejected hop is often a signed url, whose query carries a credential. */
|
||||
host: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `The response pointed at ${this.host}, outside the configured Bitbucket.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in request: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BitbucketApiError = Schema.Union([
|
||||
BitbucketUntrustedUrlError,
|
||||
BitbucketRepositoryLocatorError,
|
||||
BitbucketRequestError,
|
||||
BitbucketResponseError,
|
||||
@@ -246,6 +316,24 @@ export class BitbucketApi extends Context.Service<
|
||||
BitbucketApi,
|
||||
{
|
||||
readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
|
||||
|
||||
/**
|
||||
* One authenticated request, returning the body verbatim. Bitbucket answers most endpoints
|
||||
* with JSON and a few — a pull request diff, for one — with plain text, so the body is
|
||||
* handed back undecoded for the caller to read as it sees fit.
|
||||
*/
|
||||
readonly request: (input: {
|
||||
readonly method: "GET" | "POST" | "PUT" | "DELETE";
|
||||
/**
|
||||
* A path below the API base, or a whole URL as a paged response reports its next page.
|
||||
* A whole URL is refused unless it belongs to the configured Bitbucket.
|
||||
*/
|
||||
readonly url: string;
|
||||
/** A JSON document, for the endpoints that take one. */
|
||||
readonly body?: string;
|
||||
/** Response bytes to keep; past this the body comes back cut short and marked. */
|
||||
readonly maxBytes?: number;
|
||||
}) => Effect.Effect<{ readonly body: string; readonly truncated: boolean }, BitbucketApiError>;
|
||||
readonly listPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
@@ -473,11 +561,25 @@ function authFromConfig(
|
||||
};
|
||||
}
|
||||
|
||||
/** Null for anything that is not a url at all, which is never the configured Bitbucket. */
|
||||
function originOf(value: string): string | null {
|
||||
try {
|
||||
return new URL(value).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function responseError(
|
||||
operation: BitbucketApiOperation,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<never, BitbucketApiError> {
|
||||
return response.text.pipe(
|
||||
// Bounded like any other body: an error response is no smaller than a successful one, and
|
||||
// only its length is reported anyway.
|
||||
return collectUint8StreamText({
|
||||
stream: response.stream,
|
||||
maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketResponseBodyReadError({
|
||||
@@ -486,12 +588,12 @@ function responseError(
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((body) =>
|
||||
Effect.flatMap((collected) =>
|
||||
Effect.fail(
|
||||
new BitbucketResponseError({
|
||||
operation,
|
||||
status: response.status,
|
||||
responseBodyLength: body.length,
|
||||
responseBodyLength: collected.text.length,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -689,7 +791,107 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
// A pull request's diff, diffstat and conflicts are served as redirects to a commit-range
|
||||
// URL, and the client does not follow redirects unless asked. The hop stays on the same host,
|
||||
// so the credentials travel with it.
|
||||
/**
|
||||
* The one host these credentials may be sent to. A url that came back inside a response — a
|
||||
* pagination cursor, or the target of a redirect — is data, not instruction, so it is checked
|
||||
* against this before the account's token travels with it.
|
||||
*/
|
||||
const apiOrigin = originOf(config.baseUrl);
|
||||
|
||||
const trustedUrl = (value: string): string | null => {
|
||||
if (!/^https?:\/\//u.test(value)) return apiUrl(value);
|
||||
const origin = originOf(value);
|
||||
return origin !== null && origin === apiOrigin ? value : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Redirects are followed here rather than by the client, which forwards every header to
|
||||
* whatever host it is sent to. A pull request diff, diffstat and conflicts are all served as
|
||||
* redirects, so they have to be followed — but only back to the same Bitbucket.
|
||||
*/
|
||||
const send = (input: {
|
||||
readonly method: "GET" | "POST" | "PUT" | "DELETE";
|
||||
readonly url: string;
|
||||
readonly body?: string;
|
||||
readonly redirects: number;
|
||||
}): Effect.Effect<HttpClientResponse.HttpClientResponse, BitbucketApiError> => {
|
||||
const url = trustedUrl(input.url);
|
||||
if (url === null) {
|
||||
return Effect.fail(
|
||||
new BitbucketUntrustedUrlError({ host: originOf(input.url) ?? "an unreadable url" }),
|
||||
);
|
||||
}
|
||||
const base =
|
||||
input.method === "GET"
|
||||
? HttpClientRequest.get(url)
|
||||
: input.method === "POST"
|
||||
? HttpClientRequest.post(url)
|
||||
: input.method === "DELETE"
|
||||
? HttpClientRequest.make("DELETE")(url)
|
||||
: HttpClientRequest.put(url);
|
||||
// No `Accept: application/json`: the diff endpoints answer with a patch, not JSON.
|
||||
const withBody =
|
||||
input.body === undefined
|
||||
? base
|
||||
: base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
|
||||
return httpClient.execute(withAuth(withBody)).pipe(
|
||||
Effect.mapError(
|
||||
(cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),
|
||||
),
|
||||
Effect.flatMap((response) => {
|
||||
const location = response.headers.location;
|
||||
if (
|
||||
response.status >= 300 &&
|
||||
response.status < 400 &&
|
||||
location !== undefined &&
|
||||
input.redirects < MAX_REDIRECTS
|
||||
) {
|
||||
return send({
|
||||
...input,
|
||||
url: new URL(location, url).toString(),
|
||||
redirects: input.redirects + 1,
|
||||
});
|
||||
}
|
||||
return Effect.succeed(response);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const request: BitbucketApi["Service"]["request"] = (input) =>
|
||||
send({ ...input, redirects: 0 }).pipe(
|
||||
Effect.flatMap((response) =>
|
||||
HttpClientResponse.matchStatus({
|
||||
// Read through the body stream rather than `text`, so an oversized diff is stopped
|
||||
// as it arrives instead of being materialized whole and then cut. The same collector
|
||||
// the process runner bounds command output with.
|
||||
"2xx": (success) =>
|
||||
collectUint8StreamText({
|
||||
stream: success.stream,
|
||||
maxBytes: input.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketResponseBodyReadError({
|
||||
operation: "request",
|
||||
status: success.status,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map((collected) => ({
|
||||
body: collected.text,
|
||||
truncated: collected.truncated,
|
||||
})),
|
||||
),
|
||||
orElse: (failed) => responseError("request", failed),
|
||||
})(response),
|
||||
),
|
||||
);
|
||||
|
||||
return BitbucketApi.of({
|
||||
request,
|
||||
probeAuth: executeJson(
|
||||
"probeAuth",
|
||||
HttpClientRequest.get(apiUrl("/user")),
|
||||
|
||||
Loaded 100 of 280 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user