Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex eff1bf76aa fix(mobile): preserve startup network path changes
Co-authored-by: codex <[email protected]>
2026-08-10 13:10:11 +02:00
Julius Marmingeandcodex 68b85b9050 test(connection): make reconnect hardening deterministic
Co-authored-by: codex <[email protected]>
2026-08-10 12:58:27 +02:00
b603bacfd0 fix(mobile): probe on network path changes, report leases on reconnect
Rebuilt on main after #5561 and #5404 landed overlapping reconnect
work. What main already covers is dropped from this branch: the backoff
ladder rework replaces our jitter, wakeProbeFailed replaces our
probe-failure fast path, and the authoritative-session guard replaces
our shell warm-cache short-circuit.

What remains is the mobile-specific delta:

- New advisory `network-path-changed` wakeup: WiFi<->cellular keeps
  isConnected true while invalidating the socket's path, so the mobile
  adapter emits a wakeup on interface-type changes while active and the
  supervisor probes the session (3s bound) instead of waiting for the
  ping timeout. A failed probe rides main's wakeProbeFailed fast path;
  flapping interfaces cannot cut backoff delays short.
- Client activity is re-reported on every newly connected session
  generation; the AppState-triggered report races the reconnect and is
  dropped, leaving provider/VCS work paused server-side for up to 25s
  after a resume. Generation dedup is per-supervisor since replacements
  restart the counter.
- The RPC onPingTimeout hook is wired to logging so zombie-socket
  disconnects are distinguishable from ordinary closes.
- Server websocket idleTimeout drops to 30s from Bun's 120s default
  (clients ping every 5s, so live connections never idle), releasing a
  suspended phone's half-dead socket and buffers four times sooner.

Co-Authored-By: Claude Fable 5 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-10 12:58:27 +02:00
174 changed files with 838 additions and 35021 deletions

No files matched your search

+1 -3
View File
@@ -195,9 +195,7 @@ jobs:
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)')"
hash="$(eas fingerprint:generate --platform "$platform" --environment production --json --non-interactive | jq -r '.hash')"
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 \
+1 -1
View File
@@ -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: 30
timeout-minutes: 10
permissions:
contents: write
steps:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.33",
"version": "0.0.32",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -379,18 +379,10 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
// 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 noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
loadProfile: true,
});
const mergedPath = mergePaths("win32", [
trimNonEmpty(profile.PATH),
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
-1
View File
@@ -338,7 +338,6 @@ const config: ExpoConfig = {
"./plugins/withAndroidModernPopupMenu.cjs",
"./plugins/withAndroidModernAlertDialog.cjs",
"./plugins/withAndroidPredictiveBackCompat.cjs",
"./plugins/withAndroidTabletOrientation.cjs",
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
],
extra: {
@@ -1,80 +0,0 @@
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;
});
};
@@ -1,4 +1,4 @@
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
import { EnvironmentRegistry, EnvironmentSupervisor } from "@t3tools/client-runtime/connection";
import { EnvironmentRpcSubscriptionObserver, request } from "@t3tools/client-runtime/rpc";
import {
type BackgroundScope,
@@ -103,6 +103,40 @@ export const mobileBackgroundActivityReporterLayer = Layer.effectDiscard(
Stream.runForEach(() => Effect.sync(requestReport)),
Effect.forkScoped,
);
// Re-report on every newly connected session generation. The AppState
// report races the reconnect (the RPC fails while the socket is down and
// is ignored), so without this the server's lease can lag a resume by up
// to REPORT_INTERVAL_MS, keeping provider/VCS work paused. The generation
// dedup lives inside the per-supervisor stream because a replacement
// supervisor restarts generations; switchMap (default concurrency)
// interrupts the previous subscription set on environment changes.
const connectedGenerations = (environmentId: EnvironmentId) =>
registry.followStream(
environmentId,
Stream.unwrap(
Effect.map(EnvironmentSupervisor, (supervisor) =>
SubscriptionRef.changes(supervisor.state).pipe(
Stream.filter((state) => state.phase === "connected"),
Stream.map((state) => state.generation),
Stream.changes,
),
),
),
);
yield* Stream.concat(
Stream.fromEffect(SubscriptionRef.get(registry.entries)),
SubscriptionRef.changes(registry.entries),
).pipe(
Stream.map((entries) => [...entries.keys()].sort()),
Stream.changesWith((a, b) => a.length === b.length && a.every((id, i) => id === b[i])),
Stream.switchMap((environmentIds) =>
Stream.mergeAll(environmentIds.map(connectedGenerations), {
concurrency: "unbounded",
}),
),
Stream.runForEach(() => Effect.sync(requestReport)),
Effect.forkScoped,
);
yield* Stream.fromQueue(reportRequests).pipe(
Stream.debounce("250 millis"),
Stream.runForEach(() => report),
@@ -0,0 +1,42 @@
import { describe, expect, it } from "@effect/vitest";
import {
observeNetworkPath,
seedNetworkPathBaseline,
UNKNOWN_NETWORK_PATH,
} from "./network-path-change";
describe("network path change detection", () => {
it("does not probe when the listener matches the seeded interface", () => {
const seeded = seedNetworkPathBaseline(UNKNOWN_NETWORK_PATH, "WIFI");
expect(observeNetworkPath(seeded, "WIFI")).toEqual({
baseline: { known: true, type: "WIFI" },
shouldProbe: false,
});
});
it("probes when a known interface changes", () => {
const seeded = seedNetworkPathBaseline(UNKNOWN_NETWORK_PATH, "WIFI");
expect(observeNetworkPath(seeded, "CELLULAR").shouldProbe).toBe(true);
});
it("probes when the listener wins the race with the async seed", () => {
const observed = observeNetworkPath(UNKNOWN_NETWORK_PATH, "CELLULAR");
expect(observed.shouldProbe).toBe(true);
expect(seedNetworkPathBaseline(observed.baseline, "WIFI")).toEqual({
known: true,
type: "CELLULAR",
});
});
it("probes on the first known interface after an unknown observation", () => {
const seeded = seedNetworkPathBaseline(UNKNOWN_NETWORK_PATH, "WIFI");
const unknown = observeNetworkPath(seeded, null);
expect(unknown.shouldProbe).toBe(false);
expect(observeNetworkPath(unknown.baseline, "CELLULAR").shouldProbe).toBe(true);
});
});
@@ -0,0 +1,41 @@
export interface NetworkPathBaseline {
readonly known: boolean;
readonly type: string | null;
}
export const UNKNOWN_NETWORK_PATH: NetworkPathBaseline = {
known: false,
type: null,
};
export function seedNetworkPathBaseline(
baseline: NetworkPathBaseline,
type: string | null,
): NetworkPathBaseline {
if (baseline.known || type === null) {
return baseline;
}
return { known: true, type };
}
export function observeNetworkPath(
baseline: NetworkPathBaseline,
type: string | null,
): {
readonly baseline: NetworkPathBaseline;
readonly shouldProbe: boolean;
} {
if (type === null) {
return {
baseline: UNKNOWN_NETWORK_PATH,
shouldProbe: false,
};
}
return {
baseline: { known: true, type },
// If the initial async seed has not landed, the first listener event may
// itself be the WiFi/cellular transition. A cheap advisory probe is safer
// than losing that transition and waiting for the socket ping timeout.
shouldProbe: !baseline.known || baseline.type !== type,
};
}
+39 -2
View File
@@ -31,6 +31,11 @@ import { appAtomRegistry } from "../state/atom-registry";
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
import {
observeNetworkPath,
seedNetworkPathBaseline,
UNKNOWN_NETWORK_PATH,
} from "./network-path-change";
import { connectionStorageLayer } from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
@@ -87,11 +92,13 @@ const connectivityLayer = Connectivity.layer({
const wakeupsLayer = Wakeups.layer({
changes: Stream.merge(
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
Stream.callback<
"application-active-probe" | "application-active-reconnect" | "network-path-changed"
>((queue) =>
Effect.acquireRelease(
Effect.sync(() => {
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
return AppState.addEventListener("change", (state) => {
const appStateSubscription = AppState.addEventListener("change", (state) => {
if (state === "background") {
backgroundedAtMs = Date.now();
return;
@@ -101,6 +108,36 @@ const wakeupsLayer = Wakeups.layer({
backgroundedAtMs = null;
}
});
// WiFi <-> cellular keeps isConnected true while invalidating the
// socket's path, so the coarse online/offline signal never fires.
// Emit an advisory wakeup on interface-type changes while active;
// the supervisor probes the session rather than blindly replacing
// it, which keeps flapping paths cheap. Seed the current type so
// the first flip after startup is detected; the listener only
// reports changes.
let networkPath = UNKNOWN_NETWORK_PATH;
void Network.getNetworkStateAsync()
.then((current) => {
networkPath = seedNetworkPathBaseline(networkPath, current.type ?? null);
})
.catch(() => undefined);
const networkSubscription = Network.addNetworkStateListener((state) => {
const observation = observeNetworkPath(networkPath, state.type ?? null);
networkPath = observation.baseline;
if (
observation.shouldProbe &&
state.isConnected === true &&
AppState.currentState === "active"
) {
Queue.offerUnsafe(queue, "network-path-changed");
}
});
return {
remove: () => {
appStateSubscription.remove();
networkSubscription.remove();
},
};
}),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.33",
"version": "0.0.32",
"license": "MIT",
"repository": {
"type": "git",
@@ -37,17 +37,6 @@ 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(
-17
View File
@@ -52,23 +52,6 @@ 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,8 +81,6 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
});
@@ -31,8 +31,6 @@ const successfulRunner = (fs: FileSystem.FileSystem, path: Path.Path) =>
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
});
-4
View File
@@ -45,8 +45,6 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}
order.push("preflight");
@@ -66,8 +64,6 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
});
@@ -69,7 +69,6 @@ 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,8 +143,6 @@ export const make = Effect.gen(function* () {
capabilities: {
repositoryIdentity: true,
connectionProbe: true,
pullRequests: true,
pullRequestQuickFilters: true,
threadSettlement: true,
threadSnooze: true,
threadPinning: true,
@@ -81,8 +81,6 @@ describe("resolveServerEnvironmentLabel", () => {
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
}),
);
@@ -122,8 +120,6 @@ describe("resolveServerEnvironmentLabel", () => {
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
}),
);
@@ -227,8 +223,6 @@ describe("resolveServerEnvironmentLabel", () => {
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
}),
);
@@ -270,8 +264,6 @@ describe("resolveServerEnvironmentLabel", () => {
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
}),
);
+1 -542
View File
@@ -3341,7 +3341,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("launches setup when creating a new PR worktree", () =>
it.effect("launches setup only when creating a new PR worktree", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -3614,547 +3614,6 @@ 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);
}),
);
+12 -106
View File
@@ -1849,7 +1849,6 @@ export const make = Effect.gen(function* () {
pullRequest,
branch: details.branch ?? pullRequest.headBranch,
worktreePath: null,
isOnPullRequestHead: true,
};
}
@@ -1874,102 +1873,6 @@ 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(
@@ -2004,10 +1907,12 @@ export const make = Effect.gen(function* () {
existingBranchBeforeFetch?.worktreePath &&
existingBranchBeforeFetchPath !== rootWorktreePath
) {
return yield* reuseExistingWorktree(
existingBranchBeforeFetch.worktreePath,
existingBranchBeforeFetch.name,
);
yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath);
return {
pullRequest,
branch: localPullRequestBranch,
worktreePath: existingBranchBeforeFetch.worktreePath,
};
}
if (existingBranchBeforeFetchPath === rootWorktreePath) {
return yield* new GitManagerError({
@@ -2032,10 +1937,12 @@ export const make = Effect.gen(function* () {
existingBranchAfterFetch?.worktreePath &&
existingBranchAfterFetchPath !== rootWorktreePath
) {
return yield* reuseExistingWorktree(
existingBranchAfterFetch.worktreePath,
existingBranchAfterFetch.name,
);
yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath);
return {
pullRequest,
branch: localPullRequestBranch,
worktreePath: existingBranchAfterFetch.worktreePath,
};
}
if (existingBranchAfterFetchPath === rootWorktreePath) {
return yield* new GitManagerError({
@@ -2058,7 +1965,6 @@ export const make = Effect.gen(function* () {
pullRequest,
branch: worktree.worktree.refName,
worktreePath: worktree.worktree.path,
isOnPullRequestHead: true,
};
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
});
+13
View File
@@ -0,0 +1,13 @@
import { expect, it } from "@effect/vitest";
import { bunWebSocketOptions } from "./httpServerOptions.ts";
it("reaps Bun websocket connections after six missed client ping windows", () => {
expect(bunWebSocketOptions).toEqual({
perMessageDeflate: {
compress: "dedicated",
decompress: "shared",
},
idleTimeout: 30,
});
});
+16
View File
@@ -0,0 +1,16 @@
export const bunWebSocketOptions = {
// Negotiate permessage-deflate with clients that offer it; clients that
// don't still get uncompressed frames on their connection. A dedicated
// compressor keeps a per-connection sliding window (context takeover) so the
// compression dictionary is shared across server-to-client frames.
// Decompression uses the shared decompressor: uWebSockets' dedicated
// decompressor path can abort connections (close 1006) on valid DEFLATE
// input — see https://github.com/uNetworking/uWebSockets.js/issues/633.
perMessageDeflate: {
compress: "dedicated",
decompress: "shared",
},
// RPC clients ping every 5s. Reaping a connection after six missed ping
// windows releases suspended-mobile sockets well before Bun's 120s default.
idleTimeout: 30,
} as const;
+1 -8
View File
@@ -13,7 +13,6 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import {
collectUint8StreamText,
decodeUtf8,
type CollectedUint8StreamText,
} from "./stream/collectUint8StreamText.ts";
@@ -42,8 +41,6 @@ export interface ProcessRunOutput {
readonly timedOut: boolean;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
readonly stdoutInvalidUtf8: boolean;
readonly stderrInvalidUtf8: boolean;
}
const ProcessInvocationFields = {
@@ -241,7 +238,7 @@ const collectText = Effect.fn("processRunner.collectText")(function* (input: {
),
Effect.map(
(state): CollectedUint8StreamText => ({
...decodeUtf8(Buffer.concat(state.chunks, state.bytes)),
text: Buffer.concat(state.chunks, state.bytes).toString("utf8"),
bytes: state.bytes,
truncated: false,
}),
@@ -271,8 +268,6 @@ function finalizeRunProcess<R>(
timedOut: true,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
} satisfies ProcessRunOutput);
}
return Effect.fail(
@@ -399,8 +394,6 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
timedOut: false,
stdoutTruncated: stdout.truncated,
stderrTruncated: stderr.truncated,
stdoutInvalidUtf8: stdout.invalidUtf8,
stderrInvalidUtf8: stderr.invalidUtf8,
} satisfies ProcessRunOutput;
});
@@ -1,507 +0,0 @@
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);
}),
);
});
@@ -1,487 +0,0 @@
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);
@@ -1,21 +0,0 @@
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,
});
});
});
@@ -1,246 +0,0 @@
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;
});
@@ -1,874 +0,0 @@
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}" }] });
}),
);
});
@@ -1,785 +0,0 @@
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);
@@ -1,52 +0,0 @@
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"]);
});
});
@@ -1,290 +0,0 @@
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
@@ -1,224 +0,0 @@
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,
reviewStatus: "none",
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,
reviewStatus: "none",
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();
}
});
});
@@ -1,358 +0,0 @@
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,
reviewStatus: input.reviewStatus,
label: input.label,
maxSize: input.maxSize,
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,
reviewStatus: input.reviewStatus,
label: input.label,
maxSize: input.maxSize,
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
@@ -1,40 +0,0 @@
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",
]);
});
});
@@ -1,219 +0,0 @@
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;
});
@@ -1,396 +0,0 @@
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,
PullRequestReviewStatus,
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>;
/** Overall review decision when the provider exposes one. */
readonly reviewStatus?: PullRequestReviewStatus | null;
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;
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | 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 reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | 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>;
}
@@ -1,59 +0,0 @@
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
@@ -1,300 +0,0 @@
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([]);
});
});
@@ -1,333 +0,0 @@
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)),
);
}
@@ -1,360 +0,0 @@
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);
});
});
@@ -1,614 +0,0 @@
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);
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,455 +0,0 @@
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);
});
});
@@ -1,698 +0,0 @@
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,
});
}
-23
View File
@@ -1,23 +0,0 @@
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);
}),
);
}),
);
-1
View File
@@ -5233,7 +5233,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
branch: "feature/demo",
worktreePath: null,
isOnPullRequestHead: true,
}),
},
gitVcsDriver: {
+2 -27
View File
@@ -10,6 +10,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
import * as ServerConfig from "./config.ts";
import { bunWebSocketOptions } from "./httpServerOptions.ts";
import {
otlpTracesProxyRouteLayer,
assetRouteLayer,
@@ -21,9 +22,6 @@ 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";
@@ -188,20 +186,7 @@ const HttpServerLive = Layer.unwrap(
port: config.port,
hostname: config.host ?? "127.0.0.1",
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
websocket: {
// Negotiate permessage-deflate with clients that offer it; clients
// that don't still get uncompressed frames on their connection. A
// dedicated compressor keeps a per-connection sliding window
// (context takeover) so the compression dictionary is shared across
// server-to-client frames. Decompression uses the shared
// decompressor: uWebSockets' dedicated decompressor path can abort
// connections (close 1006) on valid DEFLATE input — see
// https://github.com/uNetworking/uWebSockets.js/issues/633.
perMessageDeflate: {
compress: "dedicated",
decompress: "shared",
},
},
websocket: bunWebSocketOptions,
});
} else {
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
@@ -432,19 +417,12 @@ 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(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),
),
@@ -455,9 +433,6 @@ 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,113 +756,3 @@ 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,
),
),
);
+13 -215
View File
@@ -22,16 +22,11 @@ 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(
@@ -52,9 +47,6 @@ 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;
@@ -64,12 +56,8 @@ 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: ${this.detail}`;
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
}
}
@@ -80,12 +68,8 @@ 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}: ${this.detail}`;
return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;
}
}
@@ -97,12 +81,8 @@ 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}: ${this.detail}`;
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
@@ -114,12 +94,8 @@ 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}: ${this.detail}`;
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
@@ -131,12 +107,8 @@ 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}: ${this.detail}`;
return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;
}
}
@@ -147,12 +119,8 @@ 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: ${this.detail}`;
return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;
}
}
@@ -163,12 +131,8 @@ 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: ${this.detail}`;
return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;
}
}
@@ -178,12 +142,8 @@ 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: ${this.detail}`;
return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;
}
}
@@ -195,12 +155,8 @@ 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: ${this.detail}`;
return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;
}
}
@@ -212,38 +168,12 @@ 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: ${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}`;
return "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.";
}
}
export const BitbucketApiError = Schema.Union([
BitbucketUntrustedUrlError,
BitbucketRepositoryLocatorError,
BitbucketRequestError,
BitbucketResponseError,
@@ -316,24 +246,6 @@ 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;
@@ -561,25 +473,11 @@ 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> {
// 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(
return response.text.pipe(
Effect.mapError(
(cause) =>
new BitbucketResponseBodyReadError({
@@ -588,12 +486,12 @@ function responseError(
cause,
}),
),
Effect.flatMap((collected) =>
Effect.flatMap((body) =>
Effect.fail(
new BitbucketResponseError({
operation,
status: response.status,
responseBodyLength: collected.text.length,
responseBodyLength: body.length,
}),
),
),
@@ -791,107 +689,7 @@ 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")),
@@ -203,9 +203,6 @@ export class GitHubCli extends Context.Service<
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
/** Piped to the child's stdin, for payloads that must never appear in argv. */
readonly stdin?: string;
readonly maxOutputBytes?: number;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
readonly listOpenPullRequests: (input: {
@@ -317,8 +314,6 @@ export const make = Effect.gen(function* () {
args: input.args,
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
})
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
@@ -249,9 +249,6 @@ export class GitLabCli extends Context.Service<
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
/** Piped to the child's stdin, for payloads that must never appear in argv. */
readonly stdin?: string;
readonly maxOutputBytes?: number;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitLabCliError>;
readonly listMergeRequests: (input: {
@@ -404,8 +401,6 @@ export const make = Effect.gen(function* () {
args: input.args,
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
...(input.stdin === undefined ? {} : { stdin: input.stdin }),
...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
})
.pipe(Effect.mapError(mapError));
@@ -72,12 +72,7 @@ function encodeAzureDevOpsPathSegment(segment: string): string {
return encodeURIComponent(segment);
}
/**
* The organization root a REST url belongs to, which is where a browser url and any further
* REST call have to be hung. Exported because the pull requests page derives its own urls from
* whatever Azure returned rather than from the local remote, whose shape varies.
*/
export function azureDevOpsOrganizationBaseFromRestApiUrl(
function azureDevOpsOrganizationBaseFromRestApiUrl(
value: string | null | undefined,
): string | null {
const rawUrl = trimOptionalString(value);
@@ -109,53 +104,29 @@ export function azureDevOpsOrganizationBaseFromRestApiUrl(
}
}
/**
* Where a pull request lives in a browser. Azure answers with a web link when asked for one and
* otherwise leaves it to be assembled, so all three routes are tried in the order they can be
* trusted. Takes plain fields so both the source control provider and the pull requests page
* can share it.
*/
export function azureDevOpsPullRequestWebUrl(input: {
readonly pullRequestId: number;
readonly webLink?: string | null | undefined;
readonly repositoryWebUrl?: string | null | undefined;
readonly restApiUrl?: string | null | undefined;
readonly projectName?: string | null | undefined;
readonly repositoryName?: string | null | undefined;
}): string {
const webLink = trimOptionalString(input.webLink);
function normalizeAzureDevOpsPullRequestUrl(
raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
): string {
const webLink = trimOptionalString(raw._links?.web?.href);
if (webLink) {
return webLink;
}
const repositoryWebUrl = trimOptionalString(input.repositoryWebUrl);
const repositoryWebUrl = trimOptionalString(raw.repository?.webUrl);
if (repositoryWebUrl) {
return `${repositoryWebUrl.replace(/\/+$/, "")}/pullrequest/${input.pullRequestId}`;
return `${repositoryWebUrl.replace(/\/+$/, "")}/pullrequest/${raw.pullRequestId}`;
}
const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(input.restApiUrl);
const projectName = trimOptionalString(input.projectName);
const repositoryName = trimOptionalString(input.repositoryName);
const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(raw.url);
const projectName = trimOptionalString(raw.repository?.project?.name);
const repositoryName = trimOptionalString(raw.repository?.name);
if (organizationBase && projectName && repositoryName) {
const encodedProjectName = encodeAzureDevOpsPathSegment(projectName);
const encodedRepositoryName = encodeAzureDevOpsPathSegment(repositoryName);
return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${input.pullRequestId}`;
return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${raw.pullRequestId}`;
}
return trimOptionalString(input.restApiUrl) ?? "";
}
function normalizeAzureDevOpsPullRequestUrl(
raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
): string {
return 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,
});
return trimOptionalString(raw.url) ?? "";
}
function normalizeAzureDevOpsPullRequestRecord(
@@ -17,7 +17,6 @@ describe("collectUint8StreamText", () => {
text: "hello world",
bytes: 11,
truncated: false,
invalidUtf8: false,
});
}),
);
@@ -34,24 +33,7 @@ describe("collectUint8StreamText", () => {
text: "abcde[truncated]",
bytes: 5,
truncated: true,
invalidUtf8: false,
});
}),
);
it.effect("reports invalid UTF-8 separately from a literal replacement character", () =>
Effect.gen(function* () {
const invalid = yield* collectUint8StreamText({
stream: Stream.make(new Uint8Array([0x66, 0x80, 0x6f])),
});
const literal = yield* collectUint8StreamText({
stream: Stream.make(encoder.encode("before\uFFFDafter")),
});
assert.strictEqual(invalid.invalidUtf8, true);
assert.strictEqual(invalid.text, "f\uFFFDo");
assert.strictEqual(literal.invalidUtf8, false);
assert.strictEqual(literal.text, "before\uFFFDafter");
}),
);
});
@@ -1,21 +1,12 @@
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import * as NodeBuffer from "node:buffer";
export interface CollectedUint8StreamText {
readonly text: string;
readonly truncated: boolean;
readonly bytes: number;
readonly invalidUtf8: boolean;
}
export const decodeUtf8 = (
bytes: Uint8Array,
): Pick<CollectedUint8StreamText, "text" | "invalidUtf8"> => ({
text: Buffer.from(bytes).toString("utf8"),
invalidUtf8: !NodeBuffer.isUtf8(bytes),
});
interface CollectState {
chunks: Uint8Array[];
readonly bytes: number;
@@ -68,15 +59,11 @@ export const collectUint8StreamText = <E>(input: {
},
),
Effect.map((state): CollectedUint8StreamText => {
const decoded = decodeUtf8(Buffer.concat(state.chunks, state.bytes));
const text = Buffer.concat(state.chunks, state.bytes).toString("utf8");
return {
text:
state.truncated && truncatedMarker.length > 0
? `${decoded.text}${truncatedMarker}`
: decoded.text,
text: state.truncated && truncatedMarker.length > 0 ? `${text}${truncatedMarker}` : text,
bytes: state.bytes,
truncated: state.truncated,
invalidUtf8: decoded.invalidUtf8,
};
}),
);
-41
View File
@@ -144,36 +144,6 @@ export interface GitFetchPullRequestBranchInput {
branch: string;
}
export interface GitFetchPullRequestHeadCommitInput {
cwd: string;
prNumber: number;
}
export interface GitResolveCommitInput {
cwd: string;
revision: string;
}
export interface GitResolveCommitResult {
commitSha: string;
}
export interface GitRefreshCheckedOutBranchInput {
cwd: string;
targetCommit: string;
/**
* Commit the checkout is allowed to be hard-reset away from: the upstream commit read before
* the fetch. HEAD sitting there means the checkout holds no work of its own.
*/
resetWhenHeadCommit?: string | null | undefined;
}
export interface GitRefreshCheckedOutBranchResult {
headCommit: string;
moved: boolean;
onTarget: boolean;
}
export interface GitEnsureRemoteInput {
cwd: string;
preferredName: string;
@@ -275,17 +245,6 @@ export class GitVcsDriver extends Context.Service<
readonly fetchPullRequestBranch: (
input: GitFetchPullRequestBranchInput,
) => Effect.Effect<void, GitCommandError>;
/** Fetches `refs/pull/<n>/head` without writing a branch, for heads that exist nowhere else. */
readonly fetchPullRequestHeadCommit: (
input: GitFetchPullRequestHeadCommitInput,
) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
readonly resolveCommit: (
input: GitResolveCommitInput,
) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
/** Moves the branch checked out in `cwd` onto `targetCommit`, from inside that worktree. */
readonly refreshCheckedOutBranch: (
input: GitRefreshCheckedOutBranchInput,
) => Effect.Effect<GitRefreshCheckedOutBranchResult, GitCommandError>;
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
-93
View File
@@ -2794,95 +2794,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
);
});
const resolveCommit: GitVcsDriver.GitVcsDriver["Service"]["resolveCommit"] = Effect.fn(
"resolveCommit",
)(function* (input) {
const commitSha = yield* runGitStdout("GitVcsDriver.resolveCommit", input.cwd, [
"rev-parse",
"--verify",
`${input.revision}^{commit}`,
]).pipe(Effect.map((stdout) => stdout.trim()));
return { commitSha };
});
const fetchPullRequestHeadCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchPullRequestHeadCommit"] =
Effect.fn("fetchPullRequestHeadCommit")(function* (input) {
const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
// No refspec destination: the pull head lands in FETCH_HEAD (per worktree) instead of a
// branch, which is the only way to read it while that branch is checked out somewhere.
yield* executeGit(
"GitVcsDriver.fetchPullRequestHeadCommit",
input.cwd,
["fetch", "--quiet", "--no-tags", remoteName, `refs/pull/${input.prNumber}/head`],
{
fallbackErrorDetail: "git fetch pull request head failed",
},
);
return yield* resolveCommit({ cwd: input.cwd, revision: "FETCH_HEAD" });
});
const refreshCheckedOutBranch: GitVcsDriver.GitVcsDriver["Service"]["refreshCheckedOutBranch"] =
Effect.fn("refreshCheckedOutBranch")(function* (input) {
const { commitSha: headCommit } = yield* resolveCommit({ cwd: input.cwd, revision: "HEAD" });
if (headCommit === input.targetCommit) {
return { headCommit, moved: false, onTarget: true };
}
const worktreeChanges = yield* runGitStdout(
"GitVcsDriver.refreshCheckedOutBranch.status",
input.cwd,
["status", "--porcelain"],
);
if (worktreeChanges.trim().length > 0) {
return { headCommit, moved: false, onTarget: false };
}
const isAncestor = yield* executeGit(
"GitVcsDriver.refreshCheckedOutBranch.isAncestor",
input.cwd,
["merge-base", "--is-ancestor", headCommit, input.targetCommit],
{ allowNonZeroExit: true },
).pipe(Effect.map((result) => result.exitCode === 0));
// A rewritten head (rebase, squash, amend) does not descend from the checkout, so it can
// only be taken by resetting. That is lossless exactly when the tree is clean and HEAD
// never left the commit the upstream held before the fetch.
if (!isAncestor && headCommit !== input.resetWhenHeadCommit) {
return { headCommit, moved: false, onTarget: false };
}
if (!isAncestor) {
// The commit being reset away is about to be reachable from nothing. It is only ever a
// commit the remote already held, but "the remote held it" stops being a way back once
// the head it belonged to has been rewritten, so a ref keeps it findable.
yield* executeGit(
"GitVcsDriver.refreshCheckedOutBranch.keepPrevious",
input.cwd,
["update-ref", "refs/t3code/pre-refresh", headCommit],
{ fallbackErrorDetail: "git failed to record the previous checkout commit" },
);
}
yield* executeGit(
"GitVcsDriver.refreshCheckedOutBranch.move",
input.cwd,
// `--merge` rather than `--hard`: the cleanliness check above is a snapshot, and another
// thread may edit a tracked file between it and this move. Git itself refuses a `--merge`
// reset that would overwrite such an edit — the same guarantee `--ff-only` gives the
// other branch — so a race loses nothing; the refresh fails and is reported instead.
isAncestor
? ["merge", "--ff-only", input.targetCommit]
: ["reset", "--merge", input.targetCommit],
{
timeoutMs: 30_000,
fallbackErrorDetail: "git failed to move the checkout onto the pull request head",
},
);
return { headCommit: input.targetCommit, moved: true, onTarget: true };
});
const fetchRemote: GitVcsDriver.GitVcsDriver["Service"]["fetchRemote"] = Effect.fn("fetchRemote")(
function* (input) {
yield* executeGit(
@@ -3160,10 +3071,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
createWorktree: (input) => withListRefsInvalidation(input.cwd, createWorktree(input)),
fetchPullRequestBranch: (input) =>
withListRefsInvalidation(input.cwd, fetchPullRequestBranch(input)),
fetchPullRequestHeadCommit,
resolveCommit,
refreshCheckedOutBranch: (input) =>
withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input)),
ensureRemote: (input) => withListRefsInvalidation(input.cwd, ensureRemote(input)),
resolvePrimaryRemoteName,
fetchRemote: (input) => withListRefsInvalidation(input.cwd, fetchRemote(input)),
-2
View File
@@ -192,8 +192,6 @@ describe("VcsProcess.run", () => {
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
}),
);
-5
View File
@@ -37,9 +37,6 @@ export interface VcsProcessOutput {
readonly stderr: string;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
/** Present on real process output; optional so narrow test doubles remain lightweight. */
readonly stdoutInvalidUtf8?: boolean;
readonly stderrInvalidUtf8?: boolean;
}
export class VcsProcess extends Context.Service<
@@ -166,8 +163,6 @@ export const make = Effect.gen(function* () {
stderr: result.stderr,
stdoutTruncated: result.stdoutTruncated,
stderrTruncated: result.stderrTruncated,
stdoutInvalidUtf8: result.stdoutInvalidUtf8 ?? false,
stderrInvalidUtf8: result.stderrInvalidUtf8 ?? false,
} satisfies VcsProcessOutput;
});
-68
View File
@@ -107,7 +107,6 @@ import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
import * as PullRequestService from "./pullRequest/PullRequestService.ts";
import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
@@ -409,7 +408,6 @@ const makeWsRpcLayer = (
);
const sourceControlRepositories =
yield* SourceControlRepositoryService.SourceControlRepositoryService;
const pullRequests = yield* PullRequestService.PullRequestService;
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
const sessions = yield* SessionStore.SessionStore;
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
@@ -1636,68 +1634,6 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "cloud" },
),
[WS_METHODS.pullRequestsList]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsList, pullRequests.list(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsListStats]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsListStats, pullRequests.listStats(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsDetail]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsDetail, pullRequests.detail(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsActivity]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsActivity, pullRequests.activity(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsDiffFileContents]: (input) =>
observeRpcEffect(
WS_METHODS.pullRequestsDiffFileContents,
pullRequests.diffFileContents(input),
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.pullRequestsRunAction]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsRunAction, pullRequests.runAction(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsComment]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsComment, pullRequests.comment(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsSubmitReview]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsSubmitReview, pullRequests.submitReview(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsReplyToThread]: (input) =>
observeRpcEffect(
WS_METHODS.pullRequestsReplyToThread,
pullRequests.replyToThread(input),
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.pullRequestsSetThreadResolution]: (input) =>
observeRpcEffect(
WS_METHODS.pullRequestsSetThreadResolution,
pullRequests.setThreadResolution(input),
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.pullRequestsInvalidate]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsInvalidate, pullRequests.invalidate(input), {
"rpc.aggregate": "pull-requests",
}),
[WS_METHODS.pullRequestsReviewerCandidates]: (input) =>
observeRpcEffect(
WS_METHODS.pullRequestsReviewerCandidates,
pullRequests.reviewerCandidates(input),
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.pullRequestsRequestReviewers]: (input) =>
observeRpcEffect(
WS_METHODS.pullRequestsRequestReviewers,
pullRequests.requestReviewers(input),
{ "rpc.aggregate": "pull-requests" },
),
[WS_METHODS.sourceControlLookupRepository]: (input) =>
observeRpcEffect(
WS_METHODS.sourceControlLookupRepository,
@@ -2263,7 +2199,6 @@ export const websocketRpcRouteLayer = Layer.unwrap(
Effect.gen(function* () {
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
const pullRequests = yield* PullRequestService.PullRequestService;
return HttpRouter.add(
"GET",
"/ws",
@@ -2287,9 +2222,6 @@ export const websocketRpcRouteLayer = Layer.unwrap(
Layer.provideMerge(RpcSerialization.layerJson),
Layer.provide(ProviderMaintenanceRunner.layer),
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
// One server-lifetime service means clients share the same PR caches, and a WS
// mutation invalidates the HTTP diff cache that every client reads from.
Layer.provide(Layer.succeed(PullRequestService.PullRequestService, pullRequests)),
Layer.provide(
SourceControlDiscovery.layer.pipe(
Layer.provide(
+2 -2
View File
@@ -37,7 +37,7 @@
light: {
background: "#fdf7fd",
foreground: "#501854",
accent: "#db2777",
accent: "#e33f86",
chrome: "#fdf7fd",
},
dark: {
@@ -54,7 +54,7 @@
light: {
background: "#fdf7fd",
foreground: "#501854",
accent: "#db2777",
accent: "#e33f86",
chrome: "#fdf7fd",
},
dark: {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.33",
"version": "0.0.32",
"private": true,
"type": "module",
"scripts": {
@@ -613,9 +613,9 @@ export function BranchToolbarBranchSelector({
// Action-oriented tooltip (the pill opens the PR), distinct from the sidebar's
// state-description tooltip.
const branchPrTooltip = branchPr
? `Open ${sourceControlPresentation.terminology.singular} #${branchPr.number} (${branchPr.state})`
? `Open ${sourceControlPresentation.terminology.singular} #${branchPr.number} (${branchPr.state}) in browser`
: "";
const openPrLink = useOpenPrLink(threadRef);
const openPrLink = useOpenPrLink();
function renderPickerItem(itemValue: string, index: number) {
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
+1 -94
View File
@@ -4,13 +4,8 @@ import {
ChevronRightIcon,
CopyIcon,
GlobeIcon,
InfoIcon,
LightbulbIcon,
Maximize2Icon,
MessageSquareWarningIcon,
Minimize2Icon,
OctagonAlertIcon,
TriangleAlertIcon,
WrapTextIcon,
} from "lucide-react";
import type { ScopedThreadRef, ServerProviderSkill } from "@t3tools/contracts";
@@ -43,7 +38,6 @@ import rehypeRaw from "rehype-raw";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import remarkBreaks from "remark-breaks";
import remarkGfm from "remark-gfm";
import { remarkGithubAlerts } from "../markdown-github-alerts";
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
@@ -90,7 +84,6 @@ import { usePreparedConnection } from "../state/session";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import {
@@ -152,7 +145,6 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
...defaultSchema.attributes,
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
},
protocols: {
...defaultSchema.protocols,
@@ -162,7 +154,6 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
const CHAT_MARKDOWN_REMARK_PLUGINS = [
remarkGfm,
remarkGithubAlerts,
remarkNormalizeListItemIndentation,
remarkPreserveCodeMeta,
remarkTagInlineCode,
@@ -170,7 +161,6 @@ const CHAT_MARKDOWN_REMARK_PLUGINS = [
const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
remarkGfm,
remarkGithubAlerts,
remarkNormalizeListItemIndentation,
remarkBreaks,
remarkPreserveCodeMeta,
@@ -182,43 +172,6 @@ const CHAT_MARKDOWN_REHYPE_PLUGINS = [
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
/** GitHub's own five alert kinds, in its colors: the glyph names the urgency, the title says it. */
const GITHUB_ALERT_PRESENTATIONS: Record<
string,
{ label: string; Icon: typeof InfoIcon; borderClassName: string; titleClassName: string }
> = {
note: {
label: "Note",
Icon: InfoIcon,
borderClassName: "border-blue-500/70",
titleClassName: "text-blue-600 dark:text-blue-400",
},
tip: {
label: "Tip",
Icon: LightbulbIcon,
borderClassName: "border-emerald-500/70",
titleClassName: "text-emerald-600 dark:text-emerald-400",
},
important: {
label: "Important",
Icon: MessageSquareWarningIcon,
borderClassName: "border-purple-500/70",
titleClassName: "text-purple-600 dark:text-purple-400",
},
warning: {
label: "Warning",
Icon: TriangleAlertIcon,
borderClassName: "border-amber-500/70",
titleClassName: "text-amber-600 dark:text-amber-500",
},
caution: {
label: "Caution",
Icon: OctagonAlertIcon,
borderClassName: "border-red-500/70",
titleClassName: "text-red-600 dark:text-red-400",
},
};
function extractFenceLanguage(className: string | undefined): string {
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
const raw = match?.[1] ?? "text";
@@ -952,25 +905,6 @@ function plainHastText(node: unknown): string | null {
return parts.every((part) => part !== null) ? parts.join("") : null;
}
/**
* Whether the link carries any words of its own. An anchor that is only an image — a badge, a
* "Fix in Cursor" button — already shows its identity, and a favicon bolted on in front of it
* is a stray logo rather than a hint.
*/
function hastHasText(node: unknown): boolean {
if (!node || typeof node !== "object") return false;
if (
"type" in node &&
node.type === "text" &&
"value" in node &&
typeof node.value === "string" &&
node.value.trim().length > 0
) {
return true;
}
return "children" in node && Array.isArray(node.children) && node.children.some(hastHasText);
}
const SANITIZED_FRAGMENT_PREFIX = "user-content-";
function decodeMarkdownFragmentId(href: string): string {
@@ -1390,7 +1324,6 @@ function ChatMarkdown({
event.clipboardData.setData("text/plain", payload.text);
event.clipboardData.setData("text/html", payload.html);
}, []);
const openChangeRequestLink = useOpenChangeRequestLink(threadRef);
const openExternalLinkInPreview = useCallback(
(url: string) => {
if (!threadRef) {
@@ -1483,26 +1416,6 @@ function ChatMarkdown({
p({ node: _node, children, ...props }) {
return <p {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</p>;
},
blockquote({ node: _node, children, ...props }) {
const alert =
GITHUB_ALERT_PRESENTATIONS[
String((props as Record<string, unknown>)["data-alert"] ?? "")
];
if (!alert) {
return <blockquote {...props}>{children}</blockquote>;
}
// Not a <blockquote>: the stylesheet mutes those, and an alert's body is ordinary
// text under a colored title — which is how the host renders it.
return (
<div role="note" className={cn("my-1 border-l-2 pl-3", alert.borderClassName)}>
<p className={cn("flex items-center gap-1.5 font-medium", alert.titleClassName)}>
<alert.Icon aria-hidden className="size-3.5 shrink-0" />
{alert.label}
</p>
{children}
</div>
);
},
li({ node, children, ...props }) {
const listItemStart = node?.position?.start.offset;
const markerOffset =
@@ -1560,13 +1473,7 @@ function ChatMarkdown({
onClick?.(event);
if (isSameDocumentLink && href) {
handleMarkdownFragmentClick(event, href);
return;
}
// A link to a change request in a workspace project opens beside the
// conversation instead of in a browser: it is the thing being talked about, and
// the panel it opens offers the browser as one of its actions. Anything else is
// an ordinary link and keeps the `_blank` the shell already handles.
if (href) openChangeRequestLink(event, href);
}}
onContextMenu={(event) => {
if (!canOpenInPreview || !href || !faviconHost) return;
@@ -1595,7 +1502,7 @@ function ChatMarkdown({
});
}}
>
{faviconHost && hastHasText(node) ? (
{faviconHost ? (
<MarkdownExternalLinkContent host={faviconHost} plainText={plainHastText(node)}>
{children}
</MarkdownExternalLinkContent>
+1 -1
View File
@@ -43,7 +43,7 @@ export function hasEnvironmentReconnectWarningGraceElapsed(
export function startNewThreadForProject(
projectRef: ScopedProjectRef | null,
handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
handleNewThread: (projectRef: ScopedProjectRef) => Promise<void>,
): boolean {
if (projectRef === null) return false;
void handleNewThread(projectRef);
+1 -89
View File
@@ -123,7 +123,6 @@ import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
import {
pullRequestSurfaceId,
selectActiveRightPanel,
selectActiveRightPanelSurface,
selectThreadRightPanelState,
@@ -144,10 +143,7 @@ import {
selectThreadPreviewMiniPlayer,
usePreviewMiniPlayerStore,
} from "../previewMiniPlayerStore";
import { PullRequestDetailPanel } from "./pullRequest/PullRequestDetailPanel";
import { PullRequestDetailGhost } from "./pullRequest/PullRequestGhosts";
import { PullRequestsUnavailableState } from "./pullRequest/PullRequestsUnavailableState";
import { RightPanelTabs, type PullRequestTabStatus } from "./RightPanelTabs";
import { RightPanelTabs } from "./RightPanelTabs";
import { AgentsPanel } from "./AgentsPanel";
import {
deriveAgentPanelModel,
@@ -1565,17 +1561,6 @@ function ChatViewContent(props: ChatViewProps) {
const activeRightPanelSurface = useRightPanelStore((state) =>
selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef),
);
const [pullRequestTabStatuses, setPullRequestTabStatuses] = useState<
Record<string, PullRequestTabStatus>
>({});
const handlePullRequestTabStatusChange = useCallback((status: PullRequestTabStatus) => {
const id = pullRequestSurfaceId(status);
setPullRequestTabStatuses((current) =>
current[id]?.state === status.state && current[id]?.isDraft === status.isDraft
? current
: { ...current, [id]: status },
);
}, []);
const activeFileSurface =
activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null;
const activePreviewState = useThreadPreviewState(activeThreadRef);
@@ -1958,8 +1943,6 @@ function ChatViewContent(props: ChatViewProps) {
const serverConfig = activeThread
? (activeEnvironment?.serverConfig ?? null)
: (primaryEnvironment?.serverConfig ?? null);
const pullRequestsCapabilityKnown = serverConfig !== null;
const supportsPullRequests = serverConfig?.environment.capabilities.pullRequests === true;
const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);
const versionMismatchDismissKey =
versionMismatch && activeThread
@@ -3243,27 +3226,6 @@ function ChatViewContent(props: ChatViewProps) {
},
[activeProject, activeThreadRef],
);
// The thread's own change request, placed against the project it belongs to. Without a
// project there is nothing to resolve it against, so the caller falls back to the browser.
const threadRepository = activeProject?.repositoryIdentity?.displayName ?? null;
const openThreadPullRequest = useCallback(
(number: number) => {
if (
!supportsPullRequests ||
!activeThreadRef ||
!activeProject ||
threadRepository === null
) {
return;
}
useRightPanelStore.getState().openPullRequest(activeThreadRef, {
projectId: activeProject.id,
repository: threadRepository,
number,
});
},
[activeProject, activeThreadRef, supportsPullRequests, threadRepository],
);
const togglePreviewPanel = useCallback(() => {
if (!activeThreadRef || !isPreviewSupportedInRuntime()) return;
if (previewPanelOpen) {
@@ -4068,14 +4030,6 @@ function ChatViewContent(props: ChatViewProps) {
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
});
// The right panel offers the thread's own change request, so it can only offer it once the
// branch has one; until then the picker says so rather than opening an empty panel.
const addPullRequestSurface = useCallback(() => {
if (activeThreadPr === null) return;
openThreadPullRequest(activeThreadPr.number);
}, [activeThreadPr, openThreadPullRequest]);
const pullRequestSurfaceAvailable =
supportsPullRequests && activeThreadPr !== null && threadRepository !== null;
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const nowMinute = useNowMinute();
@@ -6028,35 +5982,6 @@ function ChatViewContent(props: ChatViewProps) {
initialGitScope={initialDiffPanelGitScope}
/>
</Suspense>
) : activeRightPanelSurface?.kind === "pull-request" && !pullRequestsCapabilityKnown ? (
<PullRequestDetailGhost />
) : activeRightPanelSurface?.kind === "pull-request" && !supportsPullRequests ? (
<PullRequestsUnavailableState
title="Pull requests unavailable"
error="Update this environment's T3 Code server to browse pull requests."
/>
) : activeRightPanelSurface?.kind === "pull-request" ? (
// No onClose: the surface tab's own X owns closing here, and a second X in the header
// would be the same action twice. The thread context also drops the checkout button, so it
// is only right for the thread's own pull request, whose branch is already under the
// reader's feet. A link the agent wrote can open any other one here, and that one has to be
// checkable out like it is anywhere else.
<PullRequestDetailPanel
key={`${activeRightPanelSurface.repository}#${activeRightPanelSurface.number}`}
environmentId={activeThread.environmentId}
reference={{
projectId: activeRightPanelSurface.projectId as ProjectId,
repository: activeRightPanelSurface.repository,
number: activeRightPanelSurface.number,
}}
context={
activeThreadPr?.number === activeRightPanelSurface.number &&
threadRepository === activeRightPanelSurface.repository
? "thread"
: "page"
}
onStateChange={handlePullRequestTabStatusChange}
/>
) : activeRightPanelSurface?.kind === "agents" ? (
<AgentsPanel
model={agentPanelModel}
@@ -6116,9 +6041,6 @@ function ChatViewContent(props: ChatViewProps) {
>
{!rightPanelOpen ? panelLayoutControls : null}
<ChatHeader
{...(!supportsPullRequests || threadRepository === null
? {}
: { onOpenPullRequest: openThreadPullRequest })}
activeThreadEnvironmentId={activeThread.environmentId}
activeThreadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
@@ -6500,15 +6422,10 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddPullRequest={addPullRequestSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
terminalAvailable={activeProject !== null}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
pullRequestAvailable={pullRequestSurfaceAvailable}
agentsAvailable
pullRequestStatuses={pullRequestTabStatuses}
liveAgentCount={agentPanelModel.liveCount}
>
{rightPanelContent}
@@ -6534,15 +6451,10 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddPullRequest={addPullRequestSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
terminalAvailable={activeProject !== null}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
pullRequestAvailable={pullRequestSurfaceAvailable}
agentsAvailable
pullRequestStatuses={pullRequestTabStatuses}
liveAgentCount={agentPanelModel.liveCount}
>
{rightPanelContent}
+259 -33
View File
@@ -36,6 +36,7 @@ import {
getRenderablePatch,
resolveDiffThemeName,
resolveFileDiffPath,
DIFF_SURFACE_THEME_UNSAFE_CSS,
} from "../lib/diffRendering";
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
@@ -74,7 +75,6 @@ import { serverEnvironment } from "../state/server";
import { reviewEnvironment } from "../state/review";
import { vcsEnvironment } from "../state/vcs";
import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices";
import { createGitDiffFileContentsLoader } from "../lib/diffFileContents";
type DiffThemeType = "light" | "dark";
const AUTOMATIC_BASE_REF = "__automatic_base_ref__";
@@ -86,6 +86,215 @@ interface CollapsedDiffFilesState {
const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = new Set();
const DIFF_PANEL_UNSAFE_CSS = `${DIFF_SURFACE_THEME_UNSAFE_CSS}
:is(
[data-line],
[data-line-annotation],
[data-merge-conflict],
[data-merge-conflict-actions],
[data-no-newline]
)[data-selected-line] {
--diffs-line-bg: light-dark(
color-mix(
in lab,
var(--code-background) 88%,
color-mix(in srgb, var(--code-background) 50%, var(--diffs-modified-base))
),
color-mix(
in lab,
var(--code-background) 80%,
color-mix(in srgb, var(--code-background) 70%, var(--diffs-modified-base))
)
) !important;
}
:is([data-gutter-buffer], [data-column-number])[data-selected-line] {
--diffs-line-bg: light-dark(
color-mix(
in lab,
var(--code-background) 91%,
color-mix(in srgb, var(--code-background) 35%, var(--diffs-modified-base))
),
color-mix(
in lab,
var(--code-background) 85%,
color-mix(in srgb, var(--code-background) 60%, var(--diffs-modified-base))
)
) !important;
}
[data-indicators="bars"]
:is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line] {
position: relative;
}
[data-indicators="bars"]
:is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line]::before {
position: absolute !important;
inset-block: 0 !important;
inset-inline-start: 0 !important;
display: block !important;
width: 4px !important;
min-width: 4px !important;
max-width: 4px !important;
height: auto !important;
padding: 0 !important;
content: "" !important;
background-color: var(--diffs-modified-base) !important;
background-image: none !important;
}
[data-file-info] {
background-color: var(--code-background) !important;
border-block-color: transparent !important;
color: var(--code-foreground) !important;
}
[data-diffs-header] {
position: sticky !important;
top: 0;
z-index: 4;
background-color: var(--code-background) !important;
border-bottom-color: transparent !important;
align-items: center !important;
font-family: var(--font-sans) !important;
font-size: 12px !important;
line-height: 1 !important;
min-height: 32px !important;
padding-block: 6px !important;
padding-inline: 8px 12px !important;
}
[data-diffs-header]:hover {
background-color: color-mix(in srgb, var(--code-background) 97%, var(--code-foreground)) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]) {
height: 24px !important;
margin-block: 0 !important;
background-color: var(--code-background) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-separator-wrapper] {
padding-inline: 8px 12px !important;
background-color: transparent !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-separator-content] {
gap: 8px;
padding-inline: 0 !important;
background-color: transparent !important;
color: color-mix(in srgb, var(--code-foreground) 52%, var(--code-background)) !important;
font-family: var(--font-sans) !important;
font-size: 11px !important;
text-decoration: none !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-unmodified-lines] {
display: flex !important;
min-width: 0;
flex: 1 1 auto;
align-items: center;
gap: 8px;
cursor: pointer;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-unmodified-lines]::before,
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-unmodified-lines]::after {
width: auto;
height: 1px;
flex: 1 1 auto;
content: "";
background-color: color-mix(in srgb, var(--code-background) 92%, var(--code-foreground));
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
[data-separator-wrapper] {
grid-template-columns: 0 minmax(0, 1fr) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
[data-separator-content] {
grid-column: 2 !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-expand-button] {
display: none !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
)
[data-separator-content] {
cursor: pointer;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
):hover
[data-separator-content] {
color: color-mix(in srgb, var(--code-foreground) 76%, var(--code-background)) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
):hover
[data-unmodified-lines]::before,
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
):hover
[data-unmodified-lines]::after {
background-color: color-mix(in srgb, var(--code-background) 84%, var(--code-foreground));
}
[data-diffs-header] [data-header-content] {
align-items: center !important;
line-height: 1 !important;
}
[data-diffs-header] [data-metadata] {
align-items: center !important;
line-height: 1 !important;
font-variant-numeric: tabular-nums;
}
[data-diffs-header] [data-additions-count],
[data-diffs-header] [data-deletions-count] {
font-family: var(--font-mono) !important;
font-size: 11px !important;
font-variant-numeric: tabular-nums;
line-height: 1 !important;
}
[data-diffs-header] [data-change-icon],
[data-diffs-header] [data-rename-icon] {
display: block;
flex-shrink: 0;
}
[data-title] {
cursor: pointer;
transition:
color 120ms ease,
text-decoration-color 120ms ease;
text-decoration: underline;
text-decoration-color: transparent;
text-underline-offset: 2px;
font-family: var(--font-sans) !important;
}
[data-title]:hover {
color: color-mix(in srgb, var(--code-foreground) 84%, var(--primary)) !important;
text-decoration-color: currentColor;
}
`;
interface DiffPanelProps {
mode?: DiffPanelMode;
composerDraftTarget: ScopedThreadRef | DraftId;
@@ -314,14 +523,45 @@ export default function DiffPanel({
return undefined;
}
return createGitDiffFileContentsLoader(getDiffFileContents, {
environmentId: activeThread.environmentId,
cwd: preview.cwd,
sourceKind: selectedGitSource.kind,
baseRef: selectedGitSource.baseRef,
headRef: selectedGitSource.headRef,
cacheKey: selectedGitSource.diffHash,
});
const source = selectedGitSource;
return async (fileDiff) => {
const newPath = resolveFileDiffPath(fileDiff);
const oldPath = fileDiff.prevName
? resolveFileDiffPath({ ...fileDiff, name: fileDiff.prevName })
: newPath;
const result = await getDiffFileContents({
environmentId: activeThread.environmentId,
input: {
cwd: preview.cwd,
sourceKind: source.kind,
changeType: fileDiff.type,
baseRef: source.baseRef,
headRef: source.headRef,
oldPath,
newPath,
},
});
if (result._tag !== "Success") {
throw squashAtomCommandFailure(result);
}
const newFile = {
name: newPath,
contents: result.value.newContents,
cacheKey: `${source.diffHash}:new:${newPath}`,
};
if (fileDiff.type === "rename-pure") {
return { oldFile: null, newFile };
}
return {
oldFile: {
name: oldPath,
contents: result.value.oldContents,
cacheKey: `${source.diffHash}:old:${oldPath}`,
},
newFile,
};
};
}, [
activeThread,
branchDiffPreview.data,
@@ -862,41 +1102,19 @@ export default function DiffPanel({
className="min-h-0 flex-1"
onClickCapture={(event) => {
const composedPath = event.nativeEvent.composedPath?.() ?? [];
for (const node of composedPath) {
if (!(node instanceof HTMLElement)) continue;
// Header controls keep their own actions. In particular, the chevron must
// not also trigger the row handler or the two toggles cancel each other.
if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
return;
}
}
const title = composedPath.find(
(node): node is HTMLElement =>
node instanceof HTMLElement && node.hasAttribute("data-title"),
);
const filePath = title?.textContent?.trim();
// The filename remains the explicit "open in editor" affordance.
if (filePath) {
openDiffFile(filePath);
return;
}
const header = composedPath.find(
(node): node is HTMLElement =>
node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),
);
const headerFilePath = header?.querySelector("[data-title]")?.textContent?.trim();
if (!headerFilePath) return;
const file = codeViewFiles.find(
(candidate) => candidate.filePath === headerFilePath,
);
if (file) toggleDiffFileCollapsed(file.fileKey);
if (filePath) openDiffFile(filePath);
}}
>
<AnnotatableCodeView
key={collapseScopeKey ?? reviewSectionId}
viewerRef={codeViewRef}
codeViewKey={codeViewMountKey}
className="h-full min-h-0 overflow-auto"
className="diff-render-surface h-full min-h-0 overflow-auto"
files={codeViewFiles}
sectionId={reviewSectionId}
sectionTitle={reviewSectionTitle}
@@ -940,8 +1158,16 @@ export default function DiffPanel({
overflow: wordWrap ? "wrap" : "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme as DiffThemeType,
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
stickyHeaders: true,
...(loadDiffFiles ? { loadDiffFiles } : {}),
itemMetrics: {
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
paddingTop: 0,
paddingBottom: 0,
},
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
}}
/>
</div>
+2 -15
View File
@@ -95,11 +95,6 @@ interface GitActionsControlProps {
gitCwd: string | null;
activeThreadRef: ScopedThreadRef | null;
draftId?: DraftId;
/**
* Opens the thread's own change request beside it. Absent when the thread has no project to
* place it against, in which case it still opens in the browser.
*/
onOpenPullRequest?: ((number: number) => void) | undefined;
}
interface PendingDefaultBranchAction {
@@ -976,7 +971,6 @@ export default function GitActionsControl({
gitCwd,
activeThreadRef,
draftId,
onOpenPullRequest,
}: GitActionsControlProps) {
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
@@ -1219,13 +1213,6 @@ export default function GitActionsControl({
}, [activeEnvironmentId, gitCwd, refreshVcsStatus]);
const openExistingPr = useCallback(async () => {
const openPr = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr : null;
// Beside the thread where it was made, the way the browser opens beside it. Checked before
// the shell, which opening in the app does not need.
if (openPr && onOpenPullRequest) {
onOpenPullRequest(openPr.number);
return;
}
const api = readLocalApi();
if (!api) {
toastManager.add({
@@ -1235,7 +1222,7 @@ export default function GitActionsControl({
});
return;
}
const prUrl = openPr?.url ?? null;
const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
if (!prUrl) {
toastManager.add({
type: "error",
@@ -1255,7 +1242,7 @@ export default function GitActionsControl({
}),
);
});
}, [gitStatusForActions, onOpenPullRequest, threadToastData]);
}, [gitStatusForActions, threadToastData]);
runGitActionWithToast = useEffectEvent(
async ({
+4 -32
View File
@@ -305,7 +305,6 @@ interface SidebarThreadRowProps {
projectCwd: string | null;
orderedProjectThreadKeys: readonly string[];
isActive: boolean;
openPullRequestsInRightPanel: boolean;
jumpLabel: string | null;
appSettingsConfirmThreadArchive: boolean;
renamingThreadKey: string | null;
@@ -336,18 +335,13 @@ interface SidebarThreadRowProps {
) => Promise<void>;
cancelRename: () => void;
attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise<void>;
openPrLink: (
event: React.MouseEvent<HTMLElement>,
prUrl: string,
threadRef?: ScopedThreadRef,
) => boolean;
openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void;
}
export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
const {
orderedProjectThreadKeys,
isActive,
openPullRequestsInRightPanel,
jumpLabel,
appSettingsConfirmThreadArchive,
renamingThreadKey,
@@ -569,16 +563,9 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
const handlePrClick = useCallback(
(event: React.MouseEvent<HTMLButtonElement>) => {
if (!prStatus) return;
const openedInRightPanel = openPrLink(
event,
prStatus.url,
openPullRequestsInRightPanel ? threadRef : undefined,
);
if (openedInRightPanel && openPullRequestsInRightPanel && !isActive) {
navigateToThread(threadRef);
}
openPrLink(event, prStatus.url);
},
[isActive, navigateToThread, openPrLink, openPullRequestsInRightPanel, prStatus, threadRef],
[openPrLink, prStatus],
);
const handleRenameInputRef = useCallback(
(element: HTMLInputElement | null) => {
@@ -898,7 +885,6 @@ interface SidebarProjectThreadListProps {
isThreadListExpanded: boolean;
projectCwd: string;
activeRouteThreadKey: string | null;
openPullRequestsInRightPanel: boolean;
threadJumpLabelByKey: ReadonlyMap<string, string>;
appSettingsConfirmThreadArchive: boolean;
renamingThreadKey: string | null;
@@ -930,11 +916,7 @@ interface SidebarProjectThreadListProps {
) => Promise<void>;
cancelRename: () => void;
attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise<void>;
openPrLink: (
event: React.MouseEvent<HTMLElement>,
prUrl: string,
threadRef?: ScopedThreadRef,
) => boolean;
openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void;
expandThreadListForProject: (projectKey: string) => void;
collapseThreadListForProject: (projectKey: string) => void;
}
@@ -954,7 +936,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
isThreadListExpanded,
projectCwd,
activeRouteThreadKey,
openPullRequestsInRightPanel,
threadJumpLabelByKey,
appSettingsConfirmThreadArchive,
renamingThreadKey,
@@ -1007,7 +988,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
projectCwd={projectCwd}
orderedProjectThreadKeys={orderedProjectThreadKeys}
isActive={activeRouteThreadKey === threadKey}
openPullRequestsInRightPanel={openPullRequestsInRightPanel}
jumpLabel={threadJumpLabelByKey.get(threadKey) ?? null}
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
renamingThreadKey={renamingThreadKey}
@@ -1073,7 +1053,6 @@ interface SidebarProjectItemProps {
project: SidebarProjectSnapshot;
isThreadListExpanded: boolean;
activeRouteThreadKey: string | null;
openPullRequestsInRightPanel: boolean;
newThreadShortcutLabel: string | null;
handleNewThread: ReturnType<typeof useNewThreadHandler>;
archiveThread: ReturnType<typeof useThreadActions>["archiveThread"];
@@ -1094,7 +1073,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
project,
isThreadListExpanded,
activeRouteThreadKey,
openPullRequestsInRightPanel,
newThreadShortcutLabel,
handleNewThread,
archiveThread,
@@ -2358,7 +2336,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
isThreadListExpanded={isThreadListExpanded}
projectCwd={project.workspaceRoot}
activeRouteThreadKey={activeRouteThreadKey}
openPullRequestsInRightPanel={openPullRequestsInRightPanel}
threadJumpLabelByKey={threadJumpLabelByKey}
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
renamingThreadKey={renamingThreadKey}
@@ -2776,7 +2753,6 @@ interface SidebarProjectsContentProps {
expandedThreadListsByProject: ReadonlySet<string>;
activeRouteProjectKey: string | null;
routeThreadKey: string | null;
openPullRequestsInRightPanel: boolean;
newThreadShortcutLabel: string | null;
commandPaletteShortcutLabel: string | null;
threadJumpLabelByKey: ReadonlyMap<string, string>;
@@ -2818,7 +2794,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
expandedThreadListsByProject,
activeRouteProjectKey,
routeThreadKey,
openPullRequestsInRightPanel,
newThreadShortcutLabel,
commandPaletteShortcutLabel,
threadJumpLabelByKey,
@@ -2959,7 +2934,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
activeRouteThreadKey={
activeRouteProjectKey === project.projectKey ? routeThreadKey : null
}
openPullRequestsInRightPanel={openPullRequestsInRightPanel}
newThreadShortcutLabel={newThreadShortcutLabel}
handleNewThread={handleNewThread}
archiveThread={archiveThread}
@@ -2992,7 +2966,6 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
activeRouteThreadKey={
activeRouteProjectKey === project.projectKey ? routeThreadKey : null
}
openPullRequestsInRightPanel={openPullRequestsInRightPanel}
newThreadShortcutLabel={newThreadShortcutLabel}
handleNewThread={handleNewThread}
archiveThread={archiveThread}
@@ -3678,7 +3651,6 @@ export default function LegacySidebar() {
expandedThreadListsByProject={expandedThreadListsByProject}
activeRouteProjectKey={activeRouteProjectKey}
routeThreadKey={routeThreadKey}
openPullRequestsInRightPanel={routeThreadRef !== null}
newThreadShortcutLabel={newThreadShortcutLabel}
commandPaletteShortcutLabel={commandPaletteShortcutLabel}
threadJumpLabelByKey={visibleThreadJumpLabelByKey}
+9 -92
View File
@@ -1,15 +1,6 @@
import type { ContextMenuItem, PreviewSessionSnapshot, PullRequestState } from "@t3tools/contracts";
import type { ContextMenuItem, PreviewSessionSnapshot } from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import {
Bot,
FileDiff,
Files,
GitPullRequest,
Globe2,
Plus,
TerminalSquare,
X,
} from "lucide-react";
import { Bot, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";
import {
type MouseEvent as ReactMouseEvent,
type ReactElement,
@@ -37,10 +28,6 @@ import { PierreEntryIcon } from "./chat/PierreEntryIcon";
interface RightPanelTabsProps {
mode: PreviewPanelMode;
maximized?: boolean;
/** Forwarded to PreviewPanelShell so this surface persists its own width. */
widthStorageKey?: string;
/** Forwarded to PreviewPanelShell as the initial width before a user resize. */
defaultWidth?: number;
layoutControls?: ReactNode;
surfaces: readonly RightPanelSurface[];
activeSurfaceId: string | null;
@@ -57,35 +44,19 @@ interface RightPanelTabsProps {
onAddTerminal: () => void;
onAddDiff: () => void;
onAddFiles: () => void;
onAddPullRequest: () => void;
onAddAgents: () => void;
browserAvailable: boolean;
terminalAvailable: boolean;
diffAvailable: boolean;
filesAvailable: boolean;
pullRequestAvailable: boolean;
agentsAvailable: boolean;
pullRequestStatuses?: Readonly<Record<string, PullRequestTabStatus>>;
/** Running + waiting subagents; badges the Agents card in the empty state. */
liveAgentCount: number;
children: ReactNode;
}
export interface PullRequestTabStatus {
projectId: string;
repository: string;
number: number;
state: PullRequestState;
isDraft: boolean;
}
const SURFACE_DISABLED_REASONS = {
browser: "Browser previews are only available in the T3 Code desktop app.",
terminal: "Terminal surfaces are only available from a project thread.",
files: "Files are only available when a project is open.",
diff: "Diff is only available for server threads in Git repositories.",
pullRequest: "This thread's branch has no pull request yet.",
agents: "Agents are only available from a thread.",
} as const;
type TabContextMenuAction = "copy-path" | "close" | "close-others" | "close-to-right" | "close-all";
@@ -123,14 +94,10 @@ function RightPanelEmptyState(props: {
onAddTerminal: () => void;
onAddDiff: () => void;
onAddFiles: () => void;
onAddPullRequest: () => void;
onAddAgents: () => void;
browserAvailable: boolean;
terminalAvailable: boolean;
diffAvailable: boolean;
filesAvailable: boolean;
pullRequestAvailable: boolean;
agentsAvailable: boolean;
liveAgentCount: number;
}) {
const actions = [
@@ -147,8 +114,8 @@ function RightPanelEmptyState(props: {
label: "Terminal",
description: "Start a shell in this workspace.",
icon: TerminalSquare,
available: props.terminalAvailable,
disabledReason: SURFACE_DISABLED_REASONS.terminal,
available: true,
disabledReason: null,
onClick: props.onAddTerminal,
badgeCount: 0,
},
@@ -170,21 +137,12 @@ function RightPanelEmptyState(props: {
onClick: props.onAddDiff,
badgeCount: 0,
},
{
label: "Pull request",
description: "Open the pull request for this thread's branch.",
icon: GitPullRequest,
available: props.pullRequestAvailable,
disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
onClick: props.onAddPullRequest,
badgeCount: 0,
},
{
label: "Agents",
description: "Watch subagents and workflows run.",
icon: Bot,
available: props.agentsAvailable,
disabledReason: SURFACE_DISABLED_REASONS.agents,
available: true,
disabledReason: null,
onClick: props.onAddAgents,
badgeCount: props.liveAgentCount,
},
@@ -273,8 +231,6 @@ function surfaceTitle(
terminalLabelsById.get(surface.activeTerminalId) ??
getTerminalLabel(surface.activeTerminalId)
);
case "pull-request":
return `#${surface.number}`;
case "agents":
return "Agents";
case "preview": {
@@ -310,12 +266,10 @@ function SurfaceIcon({
surface,
sessions,
theme,
pullRequestStatuses,
}: {
surface: RightPanelSurface;
sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
theme: "light" | "dark";
pullRequestStatuses: Readonly<Record<string, PullRequestTabStatus>> | undefined;
}) {
switch (surface.kind) {
case "preview": {
@@ -338,20 +292,6 @@ function SurfaceIcon({
);
case "terminal":
return <TerminalSquare className="size-3 shrink-0" />;
case "pull-request": {
const status = pullRequestStatuses?.[surface.id] ?? null;
const toneClassName =
status?.state === "merged"
? "text-violet-600 dark:text-violet-300/90"
: status?.state === "closed"
? "text-red-600 dark:text-red-300/90"
: status?.isDraft
? "text-zinc-500 dark:text-zinc-400/80"
: status?.state === "open"
? "text-emerald-600 dark:text-emerald-300/90"
: "text-muted-foreground";
return <GitPullRequest className={cn("size-3 shrink-0", toneClassName)} />;
}
case "agents":
return <Bot className="size-3 shrink-0" />;
}
@@ -442,14 +382,12 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<PreviewPanelShell
mode={props.mode}
{...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
{...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
{...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
>
<div
className={cn(
"workspace-topbar gap-1 pl-2",
props.mode !== "inline" && "[--workspace-topbar-height:--spacing(11)]",
props.mode === "inline" && !props.layoutControls ? "pr-28" : "pr-3",
props.mode === "inline" ? "pr-28" : "pr-3",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
@@ -492,7 +430,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
surface={surface}
sessions={props.previewSessions}
theme={resolvedTheme}
pullRequestStatuses={props.pullRequestStatuses}
/>
{pending ? (
<span
@@ -537,11 +474,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<Globe2 />
Browser
</SurfaceMenuItem>
<SurfaceMenuItem
available={props.terminalAvailable}
disabledReason={SURFACE_DISABLED_REASONS.terminal}
onClick={props.onAddTerminal}
>
<SurfaceMenuItem available onClick={props.onAddTerminal}>
<TerminalSquare />
Terminal
</SurfaceMenuItem>
@@ -561,19 +494,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<FileDiff />
Diff
</SurfaceMenuItem>
<SurfaceMenuItem
available={props.pullRequestAvailable}
disabledReason={SURFACE_DISABLED_REASONS.pullRequest}
onClick={props.onAddPullRequest}
>
<GitPullRequest />
Pull request
</SurfaceMenuItem>
<SurfaceMenuItem
available={props.agentsAvailable}
disabledReason={SURFACE_DISABLED_REASONS.agents}
onClick={props.onAddAgents}
>
<SurfaceMenuItem available onClick={props.onAddAgents}>
<Bot />
Agents
</SurfaceMenuItem>
@@ -591,14 +512,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
onAddTerminal={props.onAddTerminal}
onAddDiff={props.onAddDiff}
onAddFiles={props.onAddFiles}
onAddPullRequest={props.onAddPullRequest}
onAddAgents={props.onAddAgents}
browserAvailable={props.browserAvailable}
terminalAvailable={props.terminalAvailable}
diffAvailable={props.diffAvailable}
filesAvailable={props.filesAvailable}
pullRequestAvailable={props.pullRequestAvailable}
agentsAvailable={props.agentsAvailable}
liveAgentCount={props.liveAgentCount}
/>
) : (
@@ -8,18 +8,15 @@ function localDate(year: number, month: number, day: number, hour: number, minut
}
describe("resolveSnoozePresets", () => {
it("offers one hour, three hours, evening, tomorrow, and next week in the morning", () => {
it("offers hour, evening, tomorrow, next week in the morning", () => {
// Wednesday 2026-04-08 10:00 local.
const presets = resolveSnoozePresets(localDate(2026, 4, 8, 10), "locale");
expect(presets.map((preset) => preset.id)).toEqual([
"hour",
"three-hours",
"evening",
"tomorrow",
"next-week",
]);
const threeHours = presets.find((preset) => preset.id === "three-hours");
expect(new Date(threeHours!.snoozedUntil).getHours()).toBe(13);
const evening = presets.find((preset) => preset.id === "evening");
expect(new Date(evening!.snoozedUntil).getHours()).toBe(18);
const tomorrow = presets.find((preset) => preset.id === "tomorrow");
@@ -48,10 +45,10 @@ describe("resolveSnoozePresets", () => {
it("drops the evening preset once evening is near or past", () => {
expect(
resolveSnoozePresets(localDate(2026, 4, 8, 17, 30), "locale").map((preset) => preset.id),
).toEqual(["hour", "three-hours", "tomorrow", "next-week"]);
).toEqual(["hour", "tomorrow", "next-week"]);
expect(
resolveSnoozePresets(localDate(2026, 4, 8, 21), "locale").map((preset) => preset.id),
).toEqual(["hour", "three-hours", "tomorrow", "next-week"]);
).toEqual(["hour", "tomorrow", "next-week"]);
});
it("puts next week a full week out when today is Monday", () => {
+2 -13
View File
@@ -671,7 +671,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
// the user visits the thread.
wokeAt: string | null;
isActive: boolean;
openPullRequestsInRightPanel: boolean;
jumpLabel: string | null;
currentEnvironmentId: string | null;
environmentLabel: string | null;
@@ -713,7 +712,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
onUnsettle,
onUnsnooze,
onUnpin,
openPullRequestsInRightPanel,
renamingTitle,
thread,
variant,
@@ -1001,17 +999,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
}, [showSnoozeButton]);
const handlePrClick = useCallback(
(event: ReactMouseEvent<HTMLElement>) => {
if (!pr?.url) return;
const openedInRightPanel = openPrLink(
event,
pr.url,
openPullRequestsInRightPanel ? threadRef : undefined,
);
if (openedInRightPanel && openPullRequestsInRightPanel && !props.isActive) {
onThreadActivate(threadRef);
}
if (pr?.url) openPrLink(event, pr.url);
},
[onThreadActivate, openPrLink, openPullRequestsInRightPanel, pr, props.isActive, threadRef],
[openPrLink, pr],
);
// All sidebar rows share one surface model. Live threads used to look
@@ -3480,7 +3470,6 @@ export default function Sidebar() {
// rows resolve to null on their own.
wokeAt={threadWokeAt(thread, { now: snoozeNow })}
isActive={routeThreadKey === threadKey}
openPullRequestsInRightPanel={routeThreadRef !== null}
jumpLabel={showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null}
currentEnvironmentId={primaryEnvironmentId}
environmentLabel={environmentLabelById.get(thread.environmentId) ?? null}
@@ -62,7 +62,6 @@ interface ChatHeaderProps {
availableEditors: ReadonlyArray<EditorId>;
rightPanelOpen: boolean;
gitCwd: string | null;
readonly onOpenPullRequest?: ((number: number) => void) | undefined;
onNewThreadInProject: () => void;
onRunProjectScript: (script: ProjectScript) => void;
onAddProjectScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
@@ -116,7 +115,6 @@ export const ChatHeader = memo(function ChatHeader({
availableEditors,
rightPanelOpen,
gitCwd,
onOpenPullRequest,
onNewThreadInProject,
onRunProjectScript,
onAddProjectScript,
@@ -331,7 +329,6 @@ export const ChatHeader = memo(function ChatHeader({
<GitActionsControl
gitCwd={gitCwd}
activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
onOpenPullRequest={onOpenPullRequest}
{...(draftId ? { draftId } : {})}
/>
)}
@@ -29,7 +29,7 @@ const SELECTED_INDICATOR_CLASS =
"pointer-events-none absolute -right-1 top-1/2 z-10 h-5 w-0.75 -translate-y-1/2 rounded-l-full bg-primary";
const BADGE_BASE_CLASS =
"pointer-events-none absolute -right-0.5 top-0.5 z-10 flex size-3.5 items-center justify-center rounded-full bg-transparent shadow-sm ";
const NEW_BADGE_CLASS = `${BADGE_BASE_CLASS} text-update-foreground `;
const NEW_BADGE_CLASS = `${BADGE_BASE_CLASS} text-update `;
/** Opens toward the rail so the list stays readable (not over the model names). */
const PICKER_TOOLTIP_SIDE = "left" as const;
@@ -5,7 +5,6 @@ import { Toggle } from "../ui/toggle";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
interface PanelLayoutControlsProps {
showTerminalControl?: boolean;
terminalAvailable: boolean;
terminalOpen: boolean;
terminalShortcutLabel: string | null;
@@ -19,7 +18,6 @@ interface PanelLayoutControlsProps {
}
export const PanelLayoutControls = memo(function PanelLayoutControls({
showTerminalControl = true,
terminalAvailable,
terminalOpen,
terminalShortcutLabel,
@@ -35,30 +33,28 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
className="flex h-full shrink-0 items-center gap-1 [-webkit-app-region:no-drag]"
data-panel-layout-controls
>
{showTerminalControl ? (
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
pressed={terminalOpen}
onPressedChange={onToggleTerminal}
aria-label="Toggle terminal drawer"
variant="ghost"
size="sm"
disabled={!terminalAvailable}
>
<PanelBottomIcon className="size-3.5" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{terminalAvailable
? `Toggle terminal drawer${terminalShortcutLabel ? ` (${terminalShortcutLabel})` : ""}`
: "Terminal drawer is unavailable"}
</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
pressed={terminalOpen}
onPressedChange={onToggleTerminal}
aria-label="Toggle terminal drawer"
variant="ghost"
size="sm"
disabled={!terminalAvailable}
>
<PanelBottomIcon className="size-3.5" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{terminalAvailable
? `Toggle terminal drawer${terminalShortcutLabel ? ` (${terminalShortcutLabel})` : ""}`
: "Terminal drawer is unavailable"}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
@@ -21,8 +21,8 @@ vi.mock("~/composerDraftStore", () => ({
}),
}));
vi.mock("./DiffCommentAnnotation", () => ({
DiffCommentAnnotation: () => null,
vi.mock("../files/LocalCommentAnnotation", () => ({
LocalCommentAnnotation: () => null,
}));
vi.mock("../files/fileCommentAnnotations", () => ({
@@ -6,7 +6,7 @@ import type {
FileDiffMetadata,
SelectedLineRange,
} from "@pierre/diffs";
import type { CodeViewHandle } from "@pierre/diffs/react";
import { CodeView, type CodeViewHandle, type CodeViewProps } from "@pierre/diffs/react";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useMemo, useState, type ReactNode, type Ref } from "react";
@@ -18,9 +18,8 @@ import {
type ReviewCommentContext,
} from "~/reviewCommentContext";
import { LocalCommentAnnotation } from "../files/LocalCommentAnnotation";
import { nextFileCommentId } from "../files/fileCommentAnnotations";
import { DiffCommentAnnotation } from "./DiffCommentAnnotation";
import { StyledDiffCodeView, type StyledDiffCodeViewOptions } from "./StyledDiffCodeView";
interface DiffCommentAnnotationEntry {
id: string;
@@ -82,7 +81,7 @@ interface AnnotatableCodeViewProps {
sectionId: string;
sectionTitle: string;
composerDraftTarget: ScopedThreadRef | DraftId;
options: StyledDiffCodeViewOptions<DiffCommentAnnotationGroup>;
options: NonNullable<CodeViewProps<DiffCommentAnnotationGroup>["options"]>;
viewerRef?: Ref<AnnotatableCodeViewHandle>;
className?: string;
renderHeaderPrefix: (
@@ -238,9 +237,9 @@ export function AnnotatableCodeView({
const hasOpenComment = draft !== null;
return (
<StyledDiffCodeView<DiffCommentAnnotationGroup>
<CodeView<DiffCommentAnnotationGroup>
key={codeViewKey}
{...(viewerRef ? { viewerRef } : {})}
{...(viewerRef ? { ref: viewerRef } : {})}
{...(className ? { className } : {})}
items={items}
selectedLines={selectedLines}
@@ -263,7 +262,7 @@ export function AnnotatableCodeView({
className={hasDraft ? "py-1" : "divide-y divide-border/30 border-y border-border/30"}
>
{annotation.metadata.entries.map((entry) => (
<DiffCommentAnnotation
<LocalCommentAnnotation
key={entry.id}
kind={entry.kind}
rangeLabel={entry.rangeLabel}
@@ -1,58 +0,0 @@
import { renderToStaticMarkup } from "react-dom/server";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const testState = vi.hoisted(() => ({
codeViewClassName: null as string | null,
codeViewOptions: null as Record<string, unknown> | null,
}));
vi.mock("@pierre/diffs/react", () => ({
CodeView: (props: { className: string; options: Record<string, unknown> }) => {
testState.codeViewClassName = props.className;
testState.codeViewOptions = props.options;
return null;
},
}));
import { StyledDiffCodeView } from "./StyledDiffCodeView";
describe("StyledDiffCodeView", () => {
beforeEach(() => {
testState.codeViewClassName = null;
testState.codeViewOptions = null;
});
it("always pairs the shared diff styling with its virtualized geometry", () => {
const loadDiffFiles = vi.fn(async () => ({
oldFile: { name: "before.ts", contents: "before\n" },
newFile: { name: "after.ts", contents: "after\n" },
}));
renderToStaticMarkup(
<StyledDiffCodeView
className="min-h-0"
items={[]}
options={{ theme: "pierre-dark", stickyHeaders: true, loadDiffFiles }}
/>,
);
expect(testState.codeViewClassName).toBe("diff-render-surface outline-none min-h-0");
expect(testState.codeViewOptions).toMatchObject({
theme: "pierre-dark",
stickyHeaders: true,
loadDiffFiles,
itemMetrics: {
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
paddingTop: 0,
paddingBottom: 0,
},
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
});
expect(testState.codeViewOptions?.unsafeCSS).toEqual(
expect.stringContaining("[data-unmodified-lines]::before"),
);
expect(testState.codeViewOptions?.unsafeCSS).toEqual(
expect.stringContaining(")[data-expand-index]\n [data-unmodified-lines]"),
);
});
});
@@ -1,309 +0,0 @@
/* oxlint-disable eslint/no-restricted-imports -- This is the single styled adapter around Pierre's raw viewer. */
import {
CodeView,
type CodeViewHandle,
type CodeViewProps,
type ControlledCodeViewProps,
type UncontrolledCodeViewProps,
} from "@pierre/diffs/react";
/* oxlint-enable eslint/no-restricted-imports */
import type { Ref } from "react";
import { DIFF_SURFACE_THEME_UNSAFE_CSS } from "~/lib/diffRendering";
const DIFF_VIEW_UNSAFE_CSS = `${DIFF_SURFACE_THEME_UNSAFE_CSS}
:is(
[data-line],
[data-line-annotation],
[data-merge-conflict],
[data-merge-conflict-actions],
[data-no-newline]
)[data-selected-line] {
--diffs-line-bg: light-dark(
color-mix(
in lab,
var(--code-background) 88%,
color-mix(in srgb, var(--code-background) 50%, var(--diffs-modified-base))
),
color-mix(
in lab,
var(--code-background) 80%,
color-mix(in srgb, var(--code-background) 70%, var(--diffs-modified-base))
)
) !important;
}
:is([data-gutter-buffer], [data-column-number])[data-selected-line] {
--diffs-line-bg: light-dark(
color-mix(
in lab,
var(--code-background) 91%,
color-mix(in srgb, var(--code-background) 35%, var(--diffs-modified-base))
),
color-mix(
in lab,
var(--code-background) 85%,
color-mix(in srgb, var(--code-background) 60%, var(--diffs-modified-base))
)
) !important;
}
[data-indicators="bars"]
:is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line] {
position: relative;
}
[data-indicators="bars"]
:is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line]::before {
position: absolute !important;
inset-block: 0 !important;
inset-inline-start: 0 !important;
display: block !important;
width: 4px !important;
min-width: 4px !important;
max-width: 4px !important;
height: auto !important;
padding: 0 !important;
content: "" !important;
background-color: var(--diffs-modified-base) !important;
background-image: none !important;
}
[data-file-info] {
background-color: var(--code-background) !important;
border-block-color: transparent !important;
color: var(--code-foreground) !important;
}
[data-diffs-header] {
position: sticky !important;
top: 0;
z-index: 4;
background-color: var(--code-background) !important;
border-bottom-color: transparent !important;
align-items: center !important;
font-family: var(--font-sans) !important;
font-size: 12px !important;
line-height: 1 !important;
min-height: 32px !important;
padding-block: 6px !important;
padding-inline: 8px 12px !important;
}
[data-diffs-header]:hover {
/* A native scrollbar gutter cannot be painted by descendants. Use an inset edge cue instead
of a full-width band that would look accidentally clipped at the gutter. */
background-color: var(--code-background) !important;
box-shadow: inset 3px 0 color-mix(in srgb, var(--code-foreground) 24%, transparent);
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]) {
height: 24px !important;
margin-block: 0 !important;
background-color: var(--code-background) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-separator-wrapper] {
padding-inline: 8px 12px !important;
background-color: transparent !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-separator-content] {
gap: 8px;
padding-inline: 0 !important;
background-color: transparent !important;
color: color-mix(in srgb, var(--code-foreground) 52%, var(--code-background)) !important;
font-family: var(--font-sans) !important;
font-size: 11px !important;
text-decoration: none !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-unmodified-lines] {
display: flex !important;
min-width: 0;
flex: 1 1 auto;
align-items: center;
gap: 8px;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
[data-unmodified-lines] {
cursor: pointer;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-unmodified-lines]::before,
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-unmodified-lines]::after {
width: auto;
height: 1px;
flex: 1 1 auto;
content: "";
background-color: color-mix(in srgb, var(--code-background) 92%, var(--code-foreground));
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
[data-separator-wrapper] {
grid-template-columns: 0 minmax(0, 1fr) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
[data-separator-content] {
grid-column: 2 !important;
}
/* Visually hidden rather than display: none so the expand action stays keyboard-reachable. */
:is([data-separator="line-info"], [data-separator="line-info-basic"])
[data-expand-button] {
position: absolute !important;
width: 1px !important;
height: 1px !important;
margin: -1px !important;
padding: 0 !important;
overflow: hidden !important;
clip-path: inset(50%) !important;
border: 0 !important;
white-space: nowrap !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
)
[data-separator-content] {
cursor: pointer;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
):is(:hover, :focus-within)
[data-separator-content] {
color: color-mix(in srgb, var(--code-foreground) 76%, var(--code-background)) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
):is(:hover, :focus-within)
[data-unmodified-lines]::before,
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
[data-expand-button]
):is(:hover, :focus-within)
[data-unmodified-lines]::after {
background-color: color-mix(in srgb, var(--code-background) 84%, var(--code-foreground));
}
[data-diffs-header] [data-header-content] {
align-items: center !important;
line-height: 1 !important;
}
[data-diffs-header] [data-metadata] {
align-items: center !important;
line-height: 1 !important;
font-variant-numeric: tabular-nums;
}
[data-diffs-header] [data-additions-count],
[data-diffs-header] [data-deletions-count] {
font-family: var(--font-mono) !important;
font-size: 11px !important;
font-variant-numeric: tabular-nums;
line-height: 1 !important;
}
[data-diffs-header] [data-change-icon],
[data-diffs-header] [data-rename-icon] {
display: block;
flex-shrink: 0;
}
[data-title] {
cursor: pointer;
transition:
color 120ms ease,
text-decoration-color 120ms ease;
text-decoration: underline;
text-decoration-color: transparent;
text-underline-offset: 2px;
font-family: var(--font-sans) !important;
}
[data-title]:hover {
color: color-mix(in srgb, var(--code-foreground) 84%, var(--primary)) !important;
text-decoration-color: currentColor;
}
/* Expanding a file mounts its body all at once; easing it in matches the 200ms the app's
collapsibles take. Appearance only — the viewer owns geometry, so height cannot animate.
Departing content cuts, the same one-way rule the pull request chrome fold follows. */
[data-diff],
[data-file] {
transition: opacity 200ms ease-out;
}
@starting-style {
[data-diff],
[data-file] {
opacity: 0;
}
}
@media (prefers-reduced-motion: reduce) {
[data-diff],
[data-file] {
transition: none;
}
}
`;
export type StyledDiffCodeViewOptions<LAnnotation> = Omit<
NonNullable<CodeViewProps<LAnnotation>["options"]>,
"unsafeCSS" | "itemMetrics" | "layout"
>;
type StyledDiffCodeViewProps<LAnnotation> = (
| Omit<ControlledCodeViewProps<LAnnotation>, "options">
| Omit<UncontrolledCodeViewProps<LAnnotation>, "options">
) & {
readonly options?: StyledDiffCodeViewOptions<LAnnotation>;
readonly viewerRef?: Ref<CodeViewHandle<LAnnotation>>;
};
/** The shared web CodeView surface: app styling and virtualized geometry stay paired here. */
export function StyledDiffCodeView<LAnnotation = undefined>({
options,
viewerRef,
className,
...props
}: StyledDiffCodeViewProps<LAnnotation>) {
return (
<CodeView<LAnnotation>
{...props}
{...(viewerRef ? { ref: viewerRef } : {})}
// The custom element itself is focusable for keyboard scrolling. Its native outline sits
// outside the panel clipping boundary; actual controls inside retain their own indicators.
className={
className
? `diff-render-surface outline-none ${className}`
: "diff-render-surface outline-none"
}
options={{
...options,
unsafeCSS: DIFF_VIEW_UNSAFE_CSS,
itemMetrics: {
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
// Pierre uses its general file spacing as a fallback in expanded-file layout paths.
// Keep it zero alongside the explicit paddings or expanding the first file can
// reintroduce the library's default 8px gap above its header.
spacing: 0,
paddingTop: 0,
paddingBottom: 0,
},
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
}}
/>
);
}
@@ -1,26 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { isCommentSubmitShortcut } from "./commentSubmitShortcut";
describe("isCommentSubmitShortcut", () => {
it("accepts Command or Ctrl+Enter only while an eligible comment is idle", () => {
expect(
isCommentSubmitShortcut({ key: "Enter", metaKey: true, ctrlKey: false }, "Looks good", false),
).toBe(true);
expect(
isCommentSubmitShortcut({ key: "Enter", metaKey: false, ctrlKey: true }, "Looks good", false),
).toBe(true);
expect(
isCommentSubmitShortcut({ key: "Enter", metaKey: true, ctrlKey: false }, "Looks good", true),
).toBe(false);
});
it("rejects empty comments and unrelated key presses", () => {
expect(
isCommentSubmitShortcut({ key: "Enter", metaKey: true, ctrlKey: false }, " ", false),
).toBe(false);
expect(
isCommentSubmitShortcut({ key: "K", metaKey: true, ctrlKey: false }, "Looks good", false),
).toBe(false);
});
});
@@ -1,16 +0,0 @@
interface CommentSubmitShortcutEvent {
readonly key: string;
readonly metaKey: boolean;
readonly ctrlKey: boolean;
}
/** Shared guard for inline comment composers that submit on Command/Ctrl+Enter. */
export function isCommentSubmitShortcut(
event: CommentSubmitShortcutEvent,
value: string,
pending: boolean,
): boolean {
return (
!pending && (event.metaKey || event.ctrlKey) && event.key === "Enter" && value.trim().length > 0
);
}
@@ -52,7 +52,7 @@ import {
} from "./fileCommentAnnotations";
import { installFileEditorDismissal } from "./fileEditorDismissal";
import { resolveCenteredFileLineScrollTop } from "./fileLineReveal";
import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
import { LocalCommentAnnotation } from "./LocalCommentAnnotation";
import { projectFileCacheKey, projectFileEditorCacheKey } from "./fileContentRevision";
import { fileBreadcrumbs } from "./filePath";
import { isMarkdownPreviewFile, setMarkdownTaskChecked } from "./filePreviewMode";
@@ -678,7 +678,7 @@ function EditableFileSurface({
renderAnnotation={(annotation) => (
<div className="py-1">
{annotation.metadata.entries.map((entry) => (
<DiffCommentAnnotation
<LocalCommentAnnotation
key={entry.id}
kind={entry.kind}
rangeLabel={formatFileCommentRange(entry.startLine, entry.endLine)}
@@ -1,7 +1,7 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { DiffCommentAnnotation } from "./DiffCommentAnnotation";
import { LocalCommentAnnotation } from "./LocalCommentAnnotation";
const callbacks = {
onTextChange: vi.fn(),
@@ -10,10 +10,10 @@ const callbacks = {
onDelete: vi.fn(),
};
describe("DiffCommentAnnotation", () => {
it("renders the shared draft composer directly in the selected diff", () => {
describe("LocalCommentAnnotation", () => {
it("renders the draft composer directly in the selected diff", () => {
const markup = renderToStaticMarkup(
<DiffCommentAnnotation kind="draft" rangeLabel="+78" text="" {...callbacks} />,
<LocalCommentAnnotation kind="draft" rangeLabel="+78" text="" {...callbacks} />,
);
expect(markup).toContain("font-sans");
@@ -31,35 +31,9 @@ describe("DiffCommentAnnotation", () => {
expect(markup).toContain("cursor-text");
});
it("lets a pull-request diff configure actions without replacing the composer", () => {
const markup = renderToStaticMarkup(
<DiffCommentAnnotation
kind="draft"
rangeLabel="src/app.ts:4"
text=""
{...callbacks}
submitLabel="Add to review"
secondaryAction={{
label: "Ask",
icon: <span data-test-icon />,
allowEmpty: true,
onAction: vi.fn(),
}}
/>,
);
expect(markup).toContain("Add a comment…");
expect(markup).toContain(">Ask</button>");
expect(markup).toContain(">Add to review</button>");
expect(markup.match(/<button[^>]*disabled[^>]*>Add to review<\/button>/)).not.toBeNull();
const askButton = markup.match(/<button[^>]*>.*?Ask<\/button>/)?.[0];
expect(askButton).toBeDefined();
expect(askButton).not.toContain(' disabled=""');
});
it("renders a saved comment without a nested card or redundant range label", () => {
const markup = renderToStaticMarkup(
<DiffCommentAnnotation
<LocalCommentAnnotation
kind="comment"
rangeLabel="+78"
text="Please keep this branch explicit."
@@ -79,7 +53,7 @@ describe("DiffCommentAnnotation", () => {
it("renders draft text owned by the annotation wrapper", () => {
const markup = renderToStaticMarkup(
<DiffCommentAnnotation
<LocalCommentAnnotation
kind="draft"
rangeLabel="+78"
text="Keep this unsaved draft"
@@ -1,34 +1,20 @@
import { MessageCircle, Trash2 } from "lucide-react";
import { useState, type ReactNode } from "react";
import { useState } from "react";
import { Button } from "~/components/ui/button";
import { Textarea } from "~/components/ui/textarea";
import { isCommentSubmitShortcut } from "./commentSubmitShortcut";
interface DiffCommentSecondaryAction {
readonly label: string;
readonly icon?: ReactNode;
readonly allowEmpty?: boolean;
readonly onAction: (text: string) => void;
}
interface DiffCommentAnnotationProps {
interface LocalCommentAnnotationProps {
kind: "draft" | "comment";
rangeLabel: string;
text: string;
onTextChange?: (text: string) => void;
onCancel: () => void;
onComment: (text: string) => void;
onDelete?: () => void;
placeholder?: string;
submitLabel?: string;
pending?: boolean;
secondaryAction?: DiffCommentSecondaryAction;
onDelete: () => void;
}
/** The shared inline comment treatment for file previews, thread diffs, and pull-request diffs. */
export function DiffCommentAnnotation({
export function LocalCommentAnnotation({
kind,
rangeLabel,
text,
@@ -36,43 +22,36 @@ export function DiffCommentAnnotation({
onCancel,
onComment,
onDelete,
placeholder = "Add a comment…",
submitLabel = "Comment",
pending = false,
secondaryAction,
}: DiffCommentAnnotationProps) {
}: LocalCommentAnnotationProps) {
const [localDraftText, setLocalDraftText] = useState("");
const displayedText = kind === "draft" && !onTextChange ? localDraftText : text;
const trimmedText = displayedText.trim();
if (kind === "comment") {
return (
<div
data-diff-comment-annotation
data-file-comment-annotation
className="group/comment flex min-w-0 items-start gap-2.5 border-s-2 border-primary/55 bg-primary/[0.045] px-3 py-2.5 font-sans text-foreground"
contentEditable={false}
onPointerDown={(event) => event.stopPropagation()}
>
<MessageCircle className="mt-0.5 size-3.5 shrink-0 text-primary/70" aria-hidden="true" />
<p className="min-w-0 flex-1 whitespace-pre-wrap text-[13px] leading-5">{displayedText}</p>
{onDelete ? (
<Button
className="-my-1 -mr-1 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/comment:opacity-100 focus-visible:opacity-100 max-sm:opacity-100"
variant="ghost"
size="icon-xs"
aria-label="Delete comment"
onClick={onDelete}
>
<Trash2 className="size-3" />
</Button>
) : null}
<Button
className="-my-1 -mr-1 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/comment:opacity-100 focus-visible:opacity-100 max-sm:opacity-100"
variant="ghost"
size="icon-xs"
aria-label="Delete comment"
onClick={onDelete}
>
<Trash2 className="size-3" />
</Button>
</div>
);
}
return (
<div
data-diff-comment-annotation
data-file-comment-annotation
className="px-3 py-2 font-sans text-foreground"
contentEditable={false}
onPointerDown={(event) => event.stopPropagation()}
@@ -83,7 +62,7 @@ export function DiffCommentAnnotation({
className="relative inline-flex w-full rounded-md border border-border/50 bg-background/20 font-sans text-foreground transition-colors focus-within:border-border/70 [&_[data-slot=textarea]]:min-h-12 [&_[data-slot=textarea]]:cursor-text [&_[data-slot=textarea]]:px-2.5 [&_[data-slot=textarea]]:py-1.5 [&_[data-slot=textarea]]:font-sans [&_[data-slot=textarea]]:text-xs [&_[data-slot=textarea]]:leading-5 max-sm:[&_[data-slot=textarea]]:min-h-12"
size="sm"
value={displayedText}
placeholder={placeholder}
placeholder="Add a comment…"
aria-label={`Comment on lines ${rangeLabel}`}
onChange={(event) => (onTextChange ?? setLocalDraftText)(event.target.value)}
onFocus={(event) => {
@@ -95,9 +74,9 @@ export function DiffCommentAnnotation({
event.preventDefault();
onCancel();
}
if (isCommentSubmitShortcut(event, trimmedText, pending)) {
if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && displayedText.trim()) {
event.preventDefault();
onComment(trimmedText);
onComment(displayedText.trim());
}
}}
/>
@@ -111,19 +90,12 @@ export function DiffCommentAnnotation({
>
Cancel
</Button>
{secondaryAction ? (
<Button
size="xs"
variant="outline"
disabled={!secondaryAction.allowEmpty && !trimmedText}
onClick={() => secondaryAction.onAction(trimmedText)}
>
{secondaryAction.icon}
{secondaryAction.label}
</Button>
) : null}
<Button size="xs" disabled={pending || !trimmedText} onClick={() => onComment(trimmedText)}>
{submitLabel}
<Button
size="xs"
disabled={!displayedText.trim()}
onClick={() => onComment(displayedText.trim())}
>
Comment
</Button>
</div>
</div>
@@ -26,23 +26,14 @@ export function getPreviewPanelMaxWidth(viewportWidth: number): number {
export function PreviewPanelShell(props: {
mode: PreviewPanelMode;
maximized?: boolean;
/**
* Overrides the localStorage key used to persist the panel width. Callers
* embedding this shell for a different surface (e.g. the pull requests
* page) should pass their own key so resizing one panel doesn't clobber
* the other's remembered width.
*/
widthStorageKey?: string;
/** Overrides the initial width (px) before the user has resized the panel. */
defaultWidth?: number;
children: ReactNode;
}) {
const useDragRegion = isElectron && props.mode !== "sheet" && props.mode !== "embedded";
const isInline = props.mode === "inline";
const maxWidth = useViewportClampedMaxWidth();
const { width, handlers } = useResizableWidth({
storageKey: props.widthStorageKey ?? PREVIEW_PANEL_WIDTH_STORAGE_KEY,
defaultWidth: props.defaultWidth ?? PREVIEW_PANEL_DEFAULT_WIDTH,
storageKey: PREVIEW_PANEL_WIDTH_STORAGE_KEY,
defaultWidth: PREVIEW_PANEL_DEFAULT_WIDTH,
minWidth: PREVIEW_PANEL_MIN_WIDTH,
maxWidth,
edge: "left",
@@ -1,31 +0,0 @@
import { RefreshCwIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Button } from "../ui/button";
export function PullRequestActivityUnavailableState({
error,
onRetry,
compact = false,
}: {
error: string;
onRetry: () => void;
compact?: boolean;
}) {
return (
<div
className={cn(
"flex flex-col items-center justify-center gap-2 text-center",
compact ? "py-3" : "min-h-48 px-4 py-10",
)}
>
<p className="text-sm font-medium text-foreground">Could not load pull request activity</p>
<p className="max-w-md text-xs text-muted-foreground">{error}</p>
<Button size="sm" variant="outline" onClick={onRetry}>
<RefreshCwIcon aria-hidden className="size-3.5" />
Retry
</Button>
</div>
);
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,144 +0,0 @@
/**
* Loading states specific to the pull request surface — the first list, a search under way,
* and a detail panel opening — use bars in the geometry of the content they stand for, pulsing
* on one composited layer. Diff loading uses the shared diff-panel skeleton instead.
*
* Deliberately not the app's shimmer skeleton. The sweep is a `transform` animation per bar —
* compositor-safe, but a layer for every bar on screen — and its white highlight over the
* near-white `muted` base all but disappears in light mode. Here one `animate-ghost-pulse` on the
* container is a single opacity animation however many bars sit under it, and the bars take
* their tone from `muted-foreground` at low alpha, which reads on both themes.
*/
import { cn } from "~/lib/utils";
function GhostBar({ className }: { className?: string | undefined }) {
return <div aria-hidden className={cn("h-3 rounded bg-muted-foreground/15", className)} />;
}
/** Widths cycle rather than randomize, so the ghost renders the same on every pass. */
const TITLE_WIDTHS = ["w-3/5", "w-2/5", "w-1/2", "w-2/3", "w-2/5", "w-3/5", "w-1/2"];
const META_WIDTHS = ["w-2/5", "w-1/3", "w-2/5", "w-1/4", "w-1/3", "w-2/5", "w-1/3"];
/** Rows in the list's own grid — glyph, title over meta, time over diffstat. */
export function PullRequestListGhost({
rows = 7,
caption,
}: {
rows?: number;
/** Said where the group headers speak, for the states with something to say — a search. */
caption?: string;
}) {
return (
<div
role="status"
aria-label={caption ?? "Loading pull requests"}
className="animate-ghost-pulse space-y-0.5"
>
{caption ? (
<p className="px-3 pb-1 text-xs font-medium text-muted-foreground/70">{caption}</p>
) : null}
{Array.from({ length: rows }, (_, index) => (
<div
key={index}
className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-3 rounded-lg px-3 py-2"
>
<GhostBar className="size-4 rounded-full" />
<div className="min-w-0 space-y-1.5">
<GhostBar className={cn("h-3.5", TITLE_WIDTHS[index % TITLE_WIDTHS.length])} />
<GhostBar
className={cn("bg-muted-foreground/10", META_WIDTHS[index % META_WIDTHS.length])}
/>
</div>
<div className="flex flex-col items-end gap-1.5">
<GhostBar className="w-12" />
<GhostBar className="w-16 bg-muted-foreground/10" />
</div>
</div>
))}
</div>
);
}
/** The summary's own shape: a title, a byline, the facts rows, the description. */
export function PullRequestDetailGhost() {
return (
<div
role="status"
aria-label="Loading pull request"
className="animate-ghost-pulse space-y-6 px-4 py-5"
>
<div className="space-y-2">
<GhostBar className="h-5 w-4/5" />
<GhostBar className="w-2/5 bg-muted-foreground/10" />
</div>
<div className="space-y-3">
{Array.from({ length: 4 }, (_, index) => (
<div key={index} className="flex items-center gap-3">
<GhostBar className="size-3.5 rounded-full" />
<GhostBar className="w-20 bg-muted-foreground/10" />
<GhostBar className={TITLE_WIDTHS[(index + 1) % TITLE_WIDTHS.length]} />
</div>
))}
</div>
<div className="space-y-2 pt-1">
<GhostBar className="w-full bg-muted-foreground/10" />
<GhostBar className="w-11/12 bg-muted-foreground/10" />
<GhostBar className="w-4/5 bg-muted-foreground/10" />
<GhostBar className="w-2/3 bg-muted-foreground/10" />
</div>
</div>
);
}
/** People-shaped: an avatar and a name, in the reviewer picker's own row height. */
export function PullRequestPeopleGhost({ rows = 4 }: { rows?: number }) {
return (
<div role="status" aria-label="Loading people" className="animate-ghost-pulse space-y-1 p-1">
{Array.from({ length: rows }, (_, index) => (
<div key={index} className="flex h-7 items-center gap-2 rounded-md px-2">
<GhostBar className="size-4 rounded-full" />
<GhostBar className={META_WIDTHS[index % META_WIDTHS.length]} />
</div>
))}
</div>
);
}
/** The timeline's own shape: dots on the rail, a line and a date to each. */
export function PullRequestTimelineGhost({ rows = 6 }: { rows?: number }) {
return (
<div role="status" aria-label="Loading timeline" className="animate-ghost-pulse px-4 py-5">
<div className="relative ml-2 border-l border-border/70 pl-5">
{Array.from({ length: rows }, (_, index) => (
<div key={index} className="relative pb-5">
<GhostBar className="absolute -left-[1.55rem] top-1 size-2 rounded-full" />
<GhostBar className={cn("h-3.5", TITLE_WIDTHS[index % TITLE_WIDTHS.length])} />
<GhostBar className="mt-1.5 w-16 bg-muted-foreground/10" />
</div>
))}
</div>
</div>
);
}
/** A compact placeholder for the conversation while the core detail is already readable. */
export function PullRequestConversationGhost({ rows = 3 }: { rows?: number }) {
return (
<div
role="status"
aria-label="Loading pull request conversation"
className="animate-ghost-pulse space-y-4 py-2"
>
{Array.from({ length: rows }, (_, index) => (
<div key={index} className="flex items-start gap-2">
<GhostBar className="size-5 shrink-0 rounded-full" />
<div className="flex-1 space-y-1.5">
<GhostBar className={META_WIDTHS[index % META_WIDTHS.length]} />
<GhostBar className="w-full bg-muted-foreground/10" />
<GhostBar className="w-3/4 bg-muted-foreground/10" />
</div>
</div>
))}
</div>
);
}
@@ -1,54 +0,0 @@
/**
* Which of the four states wins, and which of them offer to ask the hosts again. The component is
* called as a plain function and its tree read for text: the elements are walked rather than
* invoked, so the button's own hooks never run outside a render.
*/
import { isValidElement, type ReactElement, type ReactNode } from "react";
import { describe, expect, it } from "vite-plus/test";
import { PullRequestListEmptyState } from "./PullRequestListEmptyState";
function textOf(node: ReactNode): string {
if (typeof node === "string" || typeof node === "number") return String(node);
if (Array.isArray(node)) return node.map(textOf).join(" ");
if (!isValidElement(node)) return "";
return textOf((node as ReactElement<{ children?: ReactNode }>).props.children);
}
const baseProps = {
query: "",
filtered: false,
searching: false,
hasProjects: true,
canLoadMore: false,
loadingMore: false,
refreshing: false,
onClearQuery: () => {},
onLoadMore: () => {},
onRefresh: () => {},
};
function render(props: Partial<typeof baseProps>): string {
return textOf(PullRequestListEmptyState({ ...baseProps, ...props }));
}
describe("PullRequestListEmptyState", () => {
it("asks for a project ahead of anything a search or a filter could say", () => {
const text = render({ hasProjects: false, searching: true, query: "fix", filtered: true });
expect(text).toContain("No projects in this workspace");
expect(text).toContain("Add project");
});
it("leaves the retry off the states where asking again could not change the answer", () => {
expect(render({ hasProjects: false })).not.toContain("Check again");
expect(render({ searching: true, query: "fix" })).not.toContain("Check again");
});
it("offers the retry once the hosts have answered", () => {
expect(render({})).toContain("Check again");
expect(render({ filtered: true })).toContain("Check again");
expect(render({ query: "fix" })).toContain("Check again");
expect(render({ canLoadMore: true })).toContain("Load more pull requests");
expect(render({ refreshing: true })).toContain("Checking...");
});
});
@@ -1,184 +0,0 @@
/**
* What the list shows when it has no rows to show.
*
* The drawing is the page's own subject rather than a stock empty box: two branch lines and the
* node where a change would land, in the stroke language the row icons already use. Nothing
* found leaves the branch unjoined — the gap is the whole picture, so it is drawn once and the
* variants only decide whether the seam closes.
*
* An empty page and an unread one look the same, so the states that are showing a host's answer
* offer to ask for it again. The two that are not — a search still in flight, and a workspace
* with no project to read from — leave the button out, since pressing it could only repeat what
* is already happening or ask nobody.
*/
import { PlusIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
import { openCommandPalette } from "../../commandPaletteBus";
import { Button } from "../ui/button";
import { PullRequestListGhost } from "./PullRequestGhosts";
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty";
/**
* Drawn at the weight of the icons beside it rather than as an illustration with its own
* palette, so an empty page reads as the same surface with nothing on it.
*/
function BranchMark({ joined }: { joined: boolean }) {
return (
<svg
aria-hidden
viewBox="0 0 120 72"
className="h-20 w-32 text-muted-foreground/60"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
>
{/* The base line the change would land on, always whole. */}
<path d="M10 58h100" className="text-muted-foreground/30" stroke="currentColor" />
<circle cx="10" cy="58" r="5" fill="currentColor" fillOpacity={0.25} />
<circle cx="110" cy="58" r="5" fill="currentColor" fillOpacity={0.25} />
{joined ? (
// A branch that leaves the base and comes back: the shape of a change that landed.
<path d="M30 58c0-18 8-26 24-26h12c16 0 24 8 24 26" />
) : (
<>
{/* The same branch, stopped short. What is missing is the join, so that is what the
drawing withholds. */}
<path d="M30 58c0-18 8-26 24-26h4" />
<path
d="M90 58c0-18-8-26-24-26h-4"
strokeDasharray="2 7"
className="text-muted-foreground/50"
/>
</>
)}
<circle
cx="60"
cy="32"
r={joined ? 5 : 4}
fill={joined ? "currentColor" : "none"}
fillOpacity={0.25}
className={joined ? undefined : "text-muted-foreground/45"}
/>
</svg>
);
}
export function PullRequestListEmptyState({
query,
filtered,
searching,
hasProjects,
canLoadMore,
loadingMore,
refreshing,
onClearQuery,
onLoadMore,
onRefresh,
}: {
/** The text being searched for, so the reader is told what was searched rather than guessing. */
query: string;
/** True when a state, involvement or project filter is narrowing the list. */
filtered: boolean;
/** A search is in flight; the rows on screen are the previous answer. */
searching: boolean;
/**
* Whether this environment holds a project at all. The list is assembled from the projects'
* remotes, so without one there is no host to ask and no filter or search that could help.
*/
hasProjects: boolean;
canLoadMore: boolean;
loadingMore: boolean;
/** A re-read of the hosts is already running, from here or from the header. */
refreshing: boolean;
onClearQuery: () => void;
onLoadMore: () => void;
onRefresh: () => void;
}) {
// Ahead of the search and the filters, because neither can produce a row until a project does.
if (!hasProjects) {
return (
<Empty className="py-16">
<BranchMark joined={false} />
<EmptyHeader>
<EmptyTitle>No projects in this workspace</EmptyTitle>
<EmptyDescription>
Add a project, and the pull requests from its repository appear here.
</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button size="sm" onClick={() => openCommandPalette({ open: "add-project" })}>
<PlusIcon className="size-3.5" />
Add project
</Button>
</EmptyContent>
</Empty>
);
}
if (searching) {
// The same ghost the first load wears, so a search on its way and a list on its way are
// one state to the eye — with the question named where the group headers usually speak.
return (
<PullRequestListGhost
rows={5}
caption={`Searching every host for “${query.length > 48 ? `${query.slice(0, 48)}…` : query}”`}
/>
);
}
if (query.length > 0) {
return (
<Empty className="py-16">
<BranchMark joined={false} />
<EmptyHeader>
{/* A pasted paragraph is still a search, but it is not a title. */}
<EmptyTitle>
Nothing matches “{query.length > 48 ? `${query.slice(0, 48)}…` : query}”
</EmptyTitle>
<EmptyDescription>
The hosts were searched for it. Try fewer words, or search by number, author or branch.
</EmptyDescription>
</EmptyHeader>
<EmptyContent className="flex-row flex-wrap justify-center gap-2">
<Button size="sm" variant="outline" onClick={onClearQuery}>
<SearchIcon className="size-3.5" />
Clear search
</Button>
{/* The hosts answered this query once; a pull request opened since then would answer
differently, and nothing on screen says which of the two the reader is looking at. */}
<Button size="sm" variant="outline" disabled={refreshing} onClick={onRefresh}>
<RefreshCwIcon className="size-3.5" />
{refreshing ? "Checking..." : "Check again"}
</Button>
</EmptyContent>
</Empty>
);
}
return (
<Empty className="py-16">
<BranchMark joined={false} />
<EmptyHeader>
<EmptyTitle>{filtered ? "Nothing under these filters" : "No pull requests"}</EmptyTitle>
<EmptyDescription>
{filtered
? "Widen the state, involvement or project filter to see more."
: "Pull requests from every project in this workspace appear here."}
</EmptyDescription>
</EmptyHeader>
<EmptyContent className="flex-row flex-wrap justify-center gap-2">
{canLoadMore ? (
<Button size="sm" variant="outline" disabled={loadingMore} onClick={onLoadMore}>
{loadingMore ? "Loading..." : "Load more pull requests"}
</Button>
) : null}
<Button size="sm" variant="outline" disabled={refreshing} onClick={onRefresh}>
<RefreshCwIcon className="size-3.5" />
{refreshing ? "Checking..." : "Check again"}
</Button>
</EmptyContent>
</Empty>
);
}
@@ -1,151 +0,0 @@
import type { ProjectId } from "@t3tools/contracts";
import { CircleIcon } from "lucide-react";
import { Children, isValidElement, type ReactElement, type ReactNode } from "react";
import { describe, expect, it, vi } from "vite-plus/test";
import { PullRequestFiltersMenu } from "./PullRequestListFilters";
function findValueChange(
node: ReactNode,
):
| ReactElement<{ readonly children?: ReactNode; readonly onValueChange: (value: string) => void }>
| undefined {
for (const child of Children.toArray(node)) {
if (!isValidElement(child)) continue;
const props = child.props as {
readonly children?: ReactNode;
readonly onValueChange?: (value: string) => void;
};
if (props.onValueChange) {
return child as ReactElement<{
readonly children?: ReactNode;
readonly onValueChange: (value: string) => void;
}>;
}
const nested = findValueChange(props.children);
if (nested) return nested;
}
return undefined;
}
/** The nested radio-group component element carrying this label, invoked so its group shows. */
function findLabeledGroup(node: ReactNode, label: string): ReactNode {
for (const child of Children.toArray(node)) {
if (!isValidElement(child)) continue;
const props = child.props as { readonly children?: ReactNode; readonly label?: string };
if (props.label === label && typeof child.type === "function") {
return (child.type as (properties: unknown) => ReactNode)(child.props);
}
const nested = findLabeledGroup(props.children, label);
if (nested !== undefined) return nested;
}
return undefined;
}
function menu(overrides: Partial<Parameters<typeof PullRequestFiltersMenu>[0]>) {
return PullRequestFiltersMenu({
state: "open",
stateOptions: [
{ value: "open", label: "Open", Icon: CircleIcon },
{ value: "closed", label: "Closed", Icon: CircleIcon },
],
onState: () => undefined,
involvement: "all",
involvementOptions: [{ value: "all", label: "All", Icon: CircleIcon }],
onInvolvement: () => undefined,
reviewStatus: undefined,
reviewStatusOptions: [{ value: "", label: "Any review status", Icon: CircleIcon }],
onReviewStatus: () => undefined,
maxSize: undefined,
sizeOptions: [{ value: "", label: "Any size", Icon: CircleIcon }],
onMaxSize: () => undefined,
label: undefined,
labelOptions: [{ value: "", label: "Any label", Icon: CircleIcon }],
onLabel: () => undefined,
host: undefined,
hostOptions: [],
onHost: () => undefined,
environmentId: null,
projects: [],
projectId: undefined,
unavailable: new Map(),
onProject: () => undefined,
...overrides,
quickFiltersSupported: overrides.quickFiltersSupported ?? true,
});
}
describe("pull request filters menu", () => {
it("does not emit a change when the selected state is chosen again", () => {
const onState = vi.fn();
const group = findValueChange(findLabeledGroup(menu({ onState }), "State"));
expect(group).toBeDefined();
group?.props.onValueChange("open");
expect(onState).not.toHaveBeenCalled();
group?.props.onValueChange("closed");
expect(onState).toHaveBeenCalledOnce();
expect(onState).toHaveBeenCalledWith("closed");
});
it("hides quick filters when the server does not advertise support", () => {
const view = menu({ quickFiltersSupported: false });
expect(findLabeledGroup(view, "Review")).toBeUndefined();
expect(findLabeledGroup(view, "Size")).toBeUndefined();
expect(findLabeledGroup(view, "Label")).toBeUndefined();
});
it("maps the review, size, and label any options back to no filter", () => {
const onReviewStatus = vi.fn();
const onMaxSize = vi.fn();
const onLabel = vi.fn();
const view = menu({
reviewStatus: "approved",
reviewStatusOptions: [
{ value: "", label: "Any review status", Icon: CircleIcon },
{ value: "approved", label: "Approved", Icon: CircleIcon },
],
maxSize: "m",
sizeOptions: [
{ value: "", label: "Any size", Icon: CircleIcon },
{ value: "m", label: "Size ≤ M", Icon: CircleIcon },
],
label: "bug",
labelOptions: [
{ value: "", label: "Any label", Icon: CircleIcon },
{ value: "bug", label: "bug", Icon: CircleIcon },
],
onReviewStatus,
onMaxSize,
onLabel,
});
findValueChange(findLabeledGroup(view, "Review"))?.props.onValueChange("");
findValueChange(findLabeledGroup(view, "Size"))?.props.onValueChange("");
findValueChange(findLabeledGroup(view, "Label"))?.props.onValueChange("");
expect(onReviewStatus).toHaveBeenCalledWith(undefined);
expect(onMaxSize).toHaveBeenCalledWith(undefined);
expect(onLabel).toHaveBeenCalledWith(undefined);
});
it("does not emit a change when the selected project is chosen again", () => {
const projectId = "project-1" as ProjectId;
const onProject = vi.fn();
const view = menu({
projects: [{ id: projectId, title: "T3 Code", workspaceRoot: "/work/t3code" }],
projectId,
onProject,
});
const radioGroup = findValueChange(view);
expect(radioGroup).toBeDefined();
radioGroup?.props.onValueChange(projectId);
expect(onProject).not.toHaveBeenCalled();
radioGroup?.props.onValueChange("all");
expect(onProject).toHaveBeenCalledWith(undefined);
});
});
@@ -1,341 +0,0 @@
import type {
EnvironmentId,
ProjectId,
PullRequestInvolvement,
PullRequestListState,
PullRequestReviewStatus,
SourceControlProviderKind,
} from "@t3tools/contracts";
import { FolderGit2Icon, LayersIcon, ListFilterIcon, LoaderIcon, SearchIcon } from "lucide-react";
import type { ElementType } from "react";
import { cn } from "~/lib/utils";
import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
import { ProjectFavicon } from "../ProjectFavicon";
import {
Menu,
MenuGroupLabel,
MenuPopup,
MenuRadioGroup,
MenuRadioItem,
MenuSeparator,
MenuTrigger,
} from "../ui/menu";
export interface PullRequestFilterOption<Value extends string> {
readonly value: Value;
readonly label: string;
/**
* Carries the option's own tone, so an icon reads the same here as it does on a row. Left
* uncoloured, which lets the item's selected state stay the thing the eye follows.
*/
readonly Icon: ElementType<{ className?: string }>;
/** Why it cannot be chosen, carried onto the item as its title. */
readonly unavailable?: string | undefined;
}
export interface PullRequestExpectedHost {
readonly host: string;
readonly kind: SourceControlProviderKind;
}
/**
* What to call a host in the row. The provider's own name reads best — "GitHub" over
* "github.com" — but it stops naming anything once a workspace has two hosts of one kind, so
* those wear the host itself instead. Only the ambiguous ones: a lone GitLab beside two GitHub
* installs is still "GitLab".
*/
export function pullRequestHostLabel(
entries: ReadonlyArray<{ readonly host: string; readonly kind: SourceControlProviderKind }>,
entry: { readonly host: string; readonly kind: SourceControlProviderKind },
): string {
const sharing = entries.filter((candidate) => candidate.kind === entry.kind);
return sharing.length > 1
? entry.host
: getSourceControlPresentationForKind(entry.kind).providerName;
}
export function PullRequestSearchInput({
value,
busy,
onChange,
}: {
value: string;
/** A search is on its way to the hosts, said where the typing is rather than over the list. */
busy?: boolean;
onChange: (value: string) => void;
}) {
return (
<div className="relative min-w-0 flex-1">
{busy ? (
<LoaderIcon
aria-hidden
className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 animate-spin text-muted-foreground"
/>
) : (
<SearchIcon
aria-hidden
className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"
/>
)}
<input
type="text"
value={value}
onChange={(event) => onChange(event.currentTarget.value)}
placeholder="Search pull requests"
aria-label="Search pull requests"
// Tracks the shared input's height at both widths, so it stays level with the icon
// button beside it rather than towering over it on wide screens.
className="h-9 w-full rounded-lg border border-input bg-background pr-3 pl-9 text-sm outline-none placeholder:text-muted-foreground/72 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24 sm:h-8"
/>
</div>
);
}
/**
* Every list filter lives behind the one filter icon so the control row stays two controls
* wide: the search and this. The trigger carries a dot whenever any filter is off its
* default, so a narrowed list is never a mystery. Same menu chrome as the detail panel's
* actions, which also owns its own spacing.
*/
const ALL_PROJECTS_VALUE = "all";
/** MenuRadioGroup wants a string, so "every host" wears the one value no host can be. */
const ALL_HOSTS_VALUE = "";
function PullRequestFilterRadioGroup<Value extends string>({
label,
value,
options,
onChange,
}: {
label: string;
value: Value;
options: ReadonlyArray<PullRequestFilterOption<Value>>;
onChange: (value: Value) => void;
}) {
return (
<MenuRadioGroup
value={value}
onValueChange={(next) => {
if (next !== value) onChange(next as Value);
}}
>
<MenuGroupLabel>{label}</MenuGroupLabel>
{options.map((option) => (
<MenuRadioItem
key={option.value}
value={option.value}
// A host the server has already said it cannot read is not a choice here: offering
// it would answer the press by replacing a working list with that failure.
disabled={option.unavailable !== undefined}
title={option.unavailable}
>
<span className="flex min-w-0 items-center gap-2">
<option.Icon aria-hidden className="size-3.5" />
{option.label}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
);
}
export function PullRequestFiltersMenu({
state,
stateOptions,
onState,
involvement,
involvementOptions,
onInvolvement,
quickFiltersSupported,
reviewStatus,
reviewStatusOptions,
onReviewStatus,
maxSize,
sizeOptions,
onMaxSize,
label,
labelOptions,
onLabel,
host,
hostOptions,
onHost,
environmentId,
projects,
projectId,
unavailable,
onProject,
}: {
state: PullRequestListState;
stateOptions: ReadonlyArray<PullRequestFilterOption<PullRequestListState>>;
onState: (state: PullRequestListState) => void;
involvement: PullRequestInvolvement;
involvementOptions: ReadonlyArray<PullRequestFilterOption<PullRequestInvolvement>>;
onInvolvement: (involvement: PullRequestInvolvement) => void;
quickFiltersSupported: boolean;
reviewStatus: PullRequestReviewStatus | undefined;
reviewStatusOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onReviewStatus: (status: PullRequestReviewStatus | undefined) => void;
maxSize: "m" | undefined;
sizeOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onMaxSize: (size: "m" | undefined) => void;
label: string | undefined;
labelOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onLabel: (label: string | undefined) => void;
host: string | undefined;
/**
* Includes the "all hosts" entry, whose value is the empty string. With fewer than two real
* hosts there is nothing to switch between, so the whole group stays out of the menu.
*/
hostOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onHost: (host: string | undefined) => void;
/** Where the projects' own favicons are read from; null before the environment is known. */
environmentId: EnvironmentId | null;
projects: ReadonlyArray<{
readonly id: ProjectId;
readonly title: string;
readonly workspaceRoot: string;
}>;
projectId: ProjectId | undefined;
/**
* Projects whose repository could not be read this time round. They are named here, where
* the reader is already choosing between projects, rather than as a count above the list
* that says something is missing without saying which.
*/
unavailable: ReadonlyMap<ProjectId, string>;
onProject: (projectId: ProjectId | undefined) => void;
}) {
const filtered =
state !== "open" ||
involvement !== "all" ||
(quickFiltersSupported &&
(reviewStatus !== undefined || maxSize !== undefined || label !== undefined)) ||
host !== undefined ||
projectId !== undefined;
return (
<Menu>
<MenuTrigger
className={cn(
// The icon-button size that pairs with a full-height input, so the two read as one strip.
"relative inline-flex size-9 shrink-0 items-center justify-center rounded-lg border border-input text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground sm:size-8",
filtered && "text-foreground",
)}
aria-label={filtered ? "Filter pull requests, filters active" : "Filter pull requests"}
>
<ListFilterIcon className="size-4" />
{filtered ? (
<span
aria-hidden
className="absolute top-0.5 right-0.5 size-1.5 rounded-full bg-primary"
/>
) : null}
</MenuTrigger>
<MenuPopup align="end" side="bottom" className="min-w-56">
<PullRequestFilterRadioGroup
label="State"
value={state}
options={stateOptions}
onChange={onState}
/>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Involvement"
value={involvement}
options={involvementOptions}
onChange={onInvolvement}
/>
{quickFiltersSupported ? (
<>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Review"
value={reviewStatus ?? ""}
options={reviewStatusOptions}
onChange={(next) =>
onReviewStatus(next === "" ? undefined : (next as PullRequestReviewStatus))
}
/>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Size"
value={maxSize ?? ""}
options={sizeOptions}
onChange={(next) => onMaxSize(next === "" ? undefined : "m")}
/>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Label"
value={label ?? ""}
options={labelOptions}
onChange={(next) => onLabel(next === "" ? undefined : next)}
/>
</>
) : null}
{hostOptions.length > 2 ? (
<>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Host"
value={host ?? ALL_HOSTS_VALUE}
options={hostOptions}
onChange={(next) => onHost(next === ALL_HOSTS_VALUE ? undefined : next)}
/>
</>
) : null}
<MenuSeparator />
<MenuRadioGroup
value={projectId ?? ALL_PROJECTS_VALUE}
onValueChange={(next) => {
const nextProjectId = next === ALL_PROJECTS_VALUE ? undefined : (next as ProjectId);
if (nextProjectId !== projectId) onProject(nextProjectId);
}}
>
<MenuGroupLabel>Project</MenuGroupLabel>
<MenuRadioItem value={ALL_PROJECTS_VALUE}>
<span className="flex min-w-0 items-center gap-2">
<LayersIcon aria-hidden className="size-3.5" />
All projects
</span>
</MenuRadioItem>
{/* The ones that can be chosen first: a list that opens with three disabled rows reads
as a broken menu rather than as a workspace with three unreadable repositories. */}
{projects
.toSorted(
(left, right) => Number(unavailable.has(left.id)) - Number(unavailable.has(right.id)),
)
.map((project) => {
const reason = unavailable.get(project.id);
return (
<MenuRadioItem
key={project.id}
value={project.id}
disabled={reason !== undefined}
title={reason}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
{environmentId === null ? (
<FolderGit2Icon aria-hidden className="size-3.5 shrink-0" />
) : (
<ProjectFavicon
environmentId={environmentId}
cwd={project.workspaceRoot}
fallbackIcon={FolderGit2Icon}
className="size-3.5 shrink-0"
/>
)}
<span className="min-w-0 flex-1 truncate">{project.title}</span>
{reason === undefined ? null : (
<span className="shrink-0 rounded-full border border-amber-500/40 bg-amber-500/10 px-1.5 py-px text-[10px] font-medium text-amber-600 dark:text-amber-400/90">
Unavailable
</span>
)}
</span>
</MenuRadioItem>
);
})}
</MenuRadioGroup>
</MenuPopup>
</Menu>
);
}
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more