@devries-cameron20 / t3code-1 / commits / 3c3a8f5917
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(bitbucket): skip Cloud API reads for unsupported Server remotes (#22029)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: GPT-6.1 Sol <noreply@openai.com> Co-authored-by: maria-rcks <maria@kuuro.net>

Victor Vogel committed Oct 30, 2026 at 15:30 UTC 3c3a8f5917ed9fd8e3d10208ea66ca23c32147df
7 files changed +177 -3
apps/server/src/pullRequest/PullRequestService.test.ts
+46
@@ -482,6 +482,52 @@ it.effect("reads nothing from a host with no implementation, but reports it", ()
482 }),
483 );
484
485 +it.effect("reads nothing from a host its provider does not serve, but reports it", () =>
486 + Effect.gen(function* () {
487 + const reached = new Set<string>();
488 + const bitbucket = (id: string, host: string) =>
489 + project({
490 + id,
491 + title: host,
492 + workspaceRoot: `/${id}`,
493 + repository: "proj/repo",
494 + provider: SourceControlProviderKind.make("bitbucket"),
495 + host,
496 + });
497 + const service = yield* makeService({
498 + projects: [bitbucket("p1", "bitbucket.org"), bitbucket("p2", "bitbucket.example.com")],
499 + providers: [
500 + fakePullRequestProvider(SourceControlProviderKind.make("bitbucket"), {
501 + servesHost: (host) => host === "bitbucket.org",
502 + getViewer: ({ host }) => {
503 + reached.add(host ?? "");
504 + return Effect.succeed("bilal");
505 + },
506 + listChangeRequests: ({ host }) => {
507 + reached.add(host);
508 + return Effect.succeed({ items: [], truncated: false, continues: false });
509 + },
510 + }),
511 + ],
512 + });
513 +
514 + const result = yield* service.list({ state: "open" });
515 +
516 + assert.deepStrictEqual([...reached], ["bitbucket.org"]);
517 + assert.deepStrictEqual(
518 + result.providers.map(({ host, configured, detail }) => ({ host, configured, detail })),
519 + [
520 + { host: "bitbucket.org", configured: true, detail: null },
521 + {
522 + host: "bitbucket.example.com",
523 + configured: false,
524 + detail: "This host cannot be browsed here yet.",
525 + },
526 + ],
527 + );
528 + }),
529 +);
530 +
531 it.effect("says where each repository carries on, and from nothing it has run out of", () =>
532 Effect.gen(function* () {
533 const service = yield* makeService({
apps/server/src/pullRequest/PullRequestService.ts
+3 -1
@@ -515,6 +515,7 @@ function withRateLimitBackoff(
515 ? {}
516 : { unavailableRequirement: api.unavailableRequirement }),
517 ...(api.repositoryKey === undefined ? {} : { repositoryKey: api.repositoryKey }),
518 + ...(api.servesHost === undefined ? {} : { servesHost: api.servesHost }),
519 ...(api.readsPublicHostWithoutCheckout === undefined
520 ? {}
521 : { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }),
@@ -925,7 +926,8 @@ export const make = Effect.gen(function* () {
926 if (filter.host !== undefined && host !== filter.host.toLowerCase()) {
927 continue;
928 }
928 - const api = registry.get(kind);
929 + const registered = registry.get(kind);
930 + const api = registered?.servesHost?.(host) === false ? null : registered;
931 if (api !== null) {
932 const roots = viewerRoots.get(host);
933 if (roots === undefined) viewerRoots.set(host, [project.workspaceRoot]);
packages/source-control-bitbucket/src/server/BitbucketApi.test.ts
+75 -1
@@ -10,6 +10,7 @@ import * as FileSystem from "effect/FileSystem";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Queue from "effect/Queue";
13 +import * as Result from "effect/Result";
14 import * as Schema from "effect/Schema";
15 import * as TestClock from "effect/testing/TestClock";
16 import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
@@ -72,6 +73,7 @@ function makeLayer(input: {
73 readonly stall?: boolean;
74 readonly git?: Partial<HostGit>;
75 readonly env?: Record<string, string>;
76 + readonly remoteUrl?: string;
77 }) {
78 const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
79 input.stall
@@ -108,7 +110,7 @@ function makeLayer(input: {
110 remotes: [
111 {
112 name: "origin",
111 - url: "git@bitbucket.org:pingdotgg/t3code.git",
113 + url: input.remoteUrl ?? "git@bitbucket.org:pingdotgg/t3code.git",
114 pushUrl: Option.none(),
115 isPrimary: true,
116 },
@@ -337,6 +339,78 @@ it.effect("prefers an explicit repository and uses context when the repository i
339 }).pipe(Effect.provide(layer));
340 });
341
342 +it.effect("sends a self-hosted Bitbucket remote nowhere unless an API base url is configured", () =>
343 + Effect.gen(function* () {
344 + const remoteUrl = "https://bitbucket.example.com/scm/proj/repo.git";
345 + const context = {
346 + provider: {
347 + kind: SourceControlProviderKind.make("bitbucket"),
348 + name: "Bitbucket Self-Hosted",
349 + baseUrl: "https://bitbucket.example.com",
350 + },
351 + remoteName: "origin",
352 + remoteUrl,
353 + };
354 + const cloudEnv = {
355 + T3CODE_BITBUCKET_EMAIL: "user@example.com",
356 + T3CODE_BITBUCKET_API_TOKEN: "t",
357 + };
358 + const response = (request: HttpClientRequest.HttpClientRequest) =>
359 + Response.json(request.url.endsWith("/branching-model") ? {} : repositoryJson);
360 + const defaultBranch = (setup: ReturnType<typeof makeLayer>, withContext: boolean) =>
361 + BitbucketApi.BitbucketApi.pipe(
362 + Effect.flatMap((bitbucket) =>
363 + bitbucket.getDefaultBranch({ cwd: "/repo", ...(withContext ? { context } : {}) }),
364 + ),
365 + Effect.provide(setup.layer),
366 + );
367 + const requestedUrls = (setup: ReturnType<typeof makeLayer>) =>
368 + setup.execute.mock.calls.map(([request]) => request.url).toSorted();
369 +
370 + // A self-hosted remote in the checkout, then a self-hosted context beside a Cloud remote.
371 + for (const [setup, withContext] of [
372 + [makeLayer({ response, env: cloudEnv, remoteUrl }), false],
373 + [makeLayer({ response, env: cloudEnv }), true],
374 + ] as const) {
375 + const result = yield* defaultBranch(setup, withContext).pipe(Effect.result);
376 + assert.deepStrictEqual(requestedUrls(setup), []);
377 + assert.strictEqual(
378 + Result.isFailure(result) && result.failure._tag,
379 + "BitbucketRepositoryRemoteNotFoundError",
380 + );
381 + }
382 +
383 + // An explicit repository does not let a self-hosted context reach the Cloud API.
384 + const explicit = makeLayer({ response, env: cloudEnv });
385 + const cloneUrls = yield* BitbucketApi.BitbucketApi.pipe(
386 + Effect.flatMap((bitbucket) =>
387 + bitbucket.getRepositoryCloneUrls({ cwd: "/repo", context, repository: "proj/repo" }),
388 + ),
389 + Effect.provide(explicit.layer),
390 + Effect.result,
391 + );
392 + assert.deepStrictEqual(requestedUrls(explicit), []);
393 + assert.strictEqual(
394 + Result.isFailure(cloneUrls) && cloneUrls.failure._tag,
395 + "BitbucketRepositoryRemoteNotFoundError",
396 + );
397 +
398 + const cloud = makeLayer({ response, env: cloudEnv });
399 + yield* defaultBranch(cloud, false);
400 + assert.deepStrictEqual(requestedUrls(cloud), [
401 + "https://api.bitbucket.org/2.0/repositories/pingdotgg/t3code",
402 + "https://api.bitbucket.org/2.0/repositories/pingdotgg/t3code/branching-model",
403 + ]);
404 +
405 + const configured = makeLayer({ response, remoteUrl });
406 + yield* defaultBranch(configured, true);
407 + assert.deepStrictEqual(requestedUrls(configured), [
408 + "https://api.test.local/2.0/repositories/proj/repo",
409 + "https://api.test.local/2.0/repositories/proj/repo/branching-model",
410 + ]);
411 + }),
412 +);
413 +
414 it.effect(
415 "prefers the Bitbucket branching model development branch as the default PR target",
416 () => {
packages/source-control-bitbucket/src/server/BitbucketApi.ts
+20 -1
@@ -12,6 +12,7 @@ import {
12 SourceControlProviderKind,
13 TrimmedNonEmptyString,
14 type SourceControlProviderAuth,
15 + type SourceControlProviderInfo,
16 type SourceControlRepositoryCloneUrls,
17 type SourceControlRepositoryVisibility,
18 } from "@t3tools/contracts";
@@ -51,6 +52,15 @@ const BitbucketApiEnvConfig = Config.all({
52 apiToken: Config.String("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
53 });
54
55 +// Server and Data Center use a different API; a custom Cloud endpoint must be explicit.
56 +export const BitbucketServesHost = Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
57 + Config.option,
58 + Config.map(
59 + (baseUrl) => (host: string) =>
60 + Option.isSome(baseUrl) || host === "bitbucket.org" || host.endsWith(".bitbucket.org"),
61 + ),
62 +);
63 +
64 const BitbucketApiOperation = Schema.Literals([
65 "resolveRepository",
66 "getRepository",
@@ -646,6 +656,11 @@ export const make = Effect.gen(function* () {
656 host: "bitbucket.org",
657 };
658
659 + const servesHost = yield* BitbucketServesHost;
660 +
661 + const servesProvider = (provider: SourceControlProviderInfo | null) =>
662 + provider?.kind === "bitbucket" && servesHost(URL.parse(provider.baseUrl)?.hostname ?? "");
663 +
664 const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
665
666 const currentCredential = host.settings.get.pipe(
@@ -757,6 +772,10 @@ export const make = Effect.gen(function* () {
772 readonly context?: SourceControlProvider.SourceControlProviderContext;
773 readonly repository?: string;
774 }) {
775 + if (input.context?.provider.kind === "bitbucket" && !servesProvider(input.context.provider)) {
776 + // Falling back to another remote could act on a different repository.
777 + return yield* new BitbucketRepositoryRemoteNotFoundError({ cwd: input.cwd });
778 + }
779 if (input.repository !== undefined) {
780 return yield* requireRepositoryLocator(input.repository);
781 }
@@ -787,7 +806,7 @@ export const make = Effect.gen(function* () {
806 );
807
808 for (const remote of remotes.remotes) {
790 - if (recognizeRemoteWith(definition, remote.url) === null) continue;
809 + if (!servesProvider(recognizeRemoteWith(definition, remote.url))) continue;
810 const parsed = parseBitbucketRemoteUrl(remote.url);
811 if (parsed) return parsed;
812 }
packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.test.ts
+25
@@ -1,5 +1,6 @@
1 import { SourceControlProviderKind } from "@t3tools/contracts";
2 import { describe, expect, it } from "@effect/vitest";
3 +import * as ConfigProvider from "effect/ConfigProvider";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Result from "effect/Result";
@@ -178,6 +179,30 @@ it.effect("reads checks and PR state without diff, mergeability, or permission r
179 }),
180 );
181
182 +it.effect("serves only Bitbucket Cloud hosts unless an API base url is configured", () =>
183 + Effect.gen(function* () {
184 + const servedHosts = (env: Record<string, string>) =>
185 + make.pipe(
186 + Effect.map(({ servesHost }) =>
187 + ["bitbucket.org", "altssh.bitbucket.org", "bitbucket.example.com"].filter(
188 + (host) => servesHost?.(host) === true,
189 + ),
190 + ),
191 + Effect.provide(
192 + Layer.merge(
193 + Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
194 + ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
195 + ),
196 + ),
197 + );
198 +
199 + expect(yield* servedHosts({})).toEqual(["bitbucket.org", "altssh.bitbucket.org"]);
200 + expect(
201 + yield* servedHosts({ T3CODE_BITBUCKET_API_BASE_URL: "https://bitbucket.example.com/api" }),
202 + ).toEqual(["bitbucket.org", "altssh.bitbucket.org", "bitbucket.example.com"]);
203 + }),
204 +);
205 +
206 describe("bitbucketProviderFailure", () => {
207 it("treats only an HTTP 401 as unusable credentials", () => {
208 const responseError = (status: number) =>
packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
+3
@@ -2,6 +2,7 @@ import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3to
2 import * as Effect from "effect/Effect";
3 import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
4
5 +import * as BitbucketApi from "./BitbucketApi.ts";
6 import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
7 import {
8 PullRequestProviderError,
@@ -109,6 +110,7 @@ function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeReque
110
111 export const make = Effect.gen(function* () {
112 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
113 + const servesHost = yield* BitbucketApi.BitbucketServesHost.pipe(Effect.orDie);
114
115 const fail =
116 (operation: string) => (error: BitbucketPullRequestApi.BitbucketPullRequestApiError) =>
@@ -148,6 +150,7 @@ export const make = Effect.gen(function* () {
150 const provider: PullRequestProviderApi = {
151 kind: SourceControlProviderKind.make("bitbucket"),
152 capabilities: CAPABILITIES,
153 + servesHost,
154 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
155 readsPublicHostWithoutCheckout: true,
156
packages/source-control-core/src/server/PullRequestProvider.ts
+5
@@ -308,6 +308,11 @@ export interface PullRequestProviderApi {
308 * definition's `publicHost` can be read from a project with no checkout of its repository.
309 */
310 readonly readsPublicHostWithoutCheckout?: boolean;
311 + /**
312 + * Absent means every host detected as this kind is read. A host it refuses is listed as one that
313 + * cannot be browsed here, and nothing is sent for it.
314 + */
315 + readonly servesHost?: (host: string) => boolean;
316
317 readonly getViewer: (input: {
318 readonly cwd: string;