Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] c853f98b90 fix(server): wait for restored checkout status on concurrent reads (#10304)
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-20 12:45:08 +00:00
Mohamed Boudra c3da87ee4c Support Gitea, Forgejo, and Codeberg change request watches (#10280)
* feat(server): add Gitea, Forgejo, and Codeberg support for change request watches

Implement the Gitea-family ChangeRequestSource using cwd-free tea login list and tea api --login -i requests, inspecting HTTP status codes directly on stdout/stderr rather than treating exit code 0 alone as success.

Reuse the shared per-host bounded poller for concurrency limits, 429 Retry-After pauses, and exponential backoff. Combine commit statuses and Actions tasks (including approval-held runs via need_approval and cross-repo waiting shadows) with mid-pagination headSha validation, and paginate comments, reviews, and inline review comments with bounded fan-out and quiet-poll caching.

* fix(server): address review findings on Gitea watch pagination, check sharing, and runs fetch

- Read /pulls/:index/reviews/:id/comments in a single request instead of a page loop because Gitea ignores page/limit on that endpoint and omits X-Total-Count/Link headers.
- Paginate /commits/:sha/status using the X-Total-Count response header instead of body total_count (which Gitea sets to the page length).
- Extract shared pure Gitea check schemas, shadow detection, rerun selection, and tea login matching into gitea-checks.ts imported by both gitea-service.ts and gitea-change-requests.ts.
- Remove the redundant /actions/runs fetch from the watch adapter because watch checks carry no action_required trait and approval-held tasks/pending shadows already map to pending.

* fix(server): preserve Gitea watch identity, checks, and backoff

* fix(server): route Gitea watches by base URL and retain complete updates

* fix(server): reconcile Gitea checks by job and refresh watch logins

* fix(server): validate Gitea and Forgejo Actions job responses

* fix(server): classify canceled native Actions statuses as neutral

* fix(server): drain failed Gitea polls before releasing host slots

* fix(server): let admitted Gitea polls finish with low quota

* fix(server): normalize Gitea watch URLs and refresh inline replies

* test(server): cover late Gitea rate limits across recovery windows
2026-11-20 18:41:41 +07:00
12 changed files with 2980 additions and 839 deletions
@@ -1,4 +1,4 @@
import { expect, type Page } from "@playwright/test";
import { expect, test, type Page } from "@playwright/test";
import { openChangesPanel } from "./branch-switcher";
export async function restoreArchivedWorkspace(page: Page): Promise<void> {
@@ -32,7 +32,11 @@ export async function expectCommittedFile(page: Page, filename: string): Promise
}
export async function expectCommittedFileAfterReload(page: Page, filename: string): Promise<void> {
await expectCommittedFile(page, filename);
await page.reload();
await expectCommittedFile(page, filename);
await test.step("See the committed file immediately after Restore", async () => {
await expectCommittedFile(page, filename);
});
await test.step("Reload and see the same committed file", async () => {
await page.reload();
await expectCommittedFile(page, filename);
});
}
@@ -2404,6 +2404,46 @@ describe("WorkspaceGitServiceImpl with workspace folders that no longer exist",
await service.dispose();
});
test("a snapshot read during restoration waits for fresh checkout facts", async () => {
const workspace = await createTemporaryFolder();
const git = createFolderBackedGit();
const started = createDeferred<void>();
const release = createDeferred<void>();
let holdRestoredRead = false;
const service = createService({
...git.deps,
getCheckoutSnapshotFacts: async (cwd: string) => {
if (holdRestoredRead) {
started.resolve();
await release.promise;
}
return git.deps.getCheckoutSnapshotFacts(cwd);
},
});
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
await waitForObservationToSettle(service, 1);
await rm(workspace, { recursive: true, force: true });
service.onWorkspaceStateMayHaveChanged(workspace);
await vi.advanceTimersByTimeAsync(1_000);
await waitForRefreshesToSettle(service);
expect((await service.getSnapshot(workspace)).git.isGit).toBe(false);
await advanceThroughDegradedPolls(service);
await waitForObservationToSettle(service, 0);
await mkdir(workspace);
holdRestoredRead = true;
const restoringRead = service.getSnapshot(workspace);
await started.promise;
const concurrentRead = service.getSnapshot(workspace);
release.resolve();
expect((await restoringRead).git.isGit).toBe(true);
expect((await concurrentRead).git.isGit).toBe(true);
subscription.unsubscribe();
await service.dispose();
});
test("a resumed workspace rebuilds observation from fresh facts, not the non-git facts cached while its folder was gone", async () => {
const workspace = await createTemporaryFolder();
const git = createFolderBackedGit();
@@ -838,9 +838,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
cwd = resolve(cwd);
const request = this.normalizeRefreshRequest(options, "getSnapshot");
const target = this.ensureWorkspaceTarget(cwd);
// The snapshot cached while the folder was gone can say "not git". Resume
// first, so a restored folder is read again instead of served from it.
if (target.folderMissing) {
// Restoration clears folderMissing before the fresh snapshot is ready.
if (target.folderRestorePromise) {
await target.folderRestorePromise;
} else if (target.folderMissing) {
await this.resumeWorkspaceIfFolderRestored(target);
}
if (!request.force && target.latestSnapshot) {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,936 @@
import pLimit from "p-limit";
import { z } from "zod";
import { normalizeHost } from "@getpaseo/protocol/git-remote";
import {
ChangeRequestRateLimitError,
createPerHostChangeRequestPoller,
type PerHostReadContext,
parseCliHttpResponse,
parseRetryAfterMs,
} from "./change-request-poller.js";
import type { ChangeRequestSnapshot, ChangeRequestSource } from "./change-request-source.js";
import {
findTeaLoginNameForBaseUrl,
getGiteaActionTaskName,
GITEA_ACTION_MAX_PAGES,
GITEA_ACTION_PAGE_LIMIT,
GiteaActionsListResponseSchema,
GiteaCombinedCommitStatusSchema,
latestGiteaActionTasksByWorkflow,
parseGiteaActionTasks,
type GiteaActionTask,
type GiteaCommitStatus,
} from "./gitea-checks.js";
const GITEA_CLOUD_HOSTS = new Set(["gitea.com", "codeberg.org"]);
const GITEA_PR_TABS = new Set(["commits", "files", "checks"]);
const GITEA_PAGE_SIZE = GITEA_ACTION_PAGE_LIMIT;
const GITEA_REVIEW_COMMENT_CONCURRENCY = 3;
const GITEA_REVIEW_COMMENTS_TTL_MS = 5 * 60_000;
const GITEA_ACTION_RUN_LOOKUP_LIMIT = 5;
const checkUrlSchema = z.url({ protocol: /^https?$/ });
const giteaWatchPrSchema = z
.object({
number: z.number(),
state: z.string(),
merged: z.boolean().optional(),
merged_at: z.string().nullable().optional(),
html_url: z.string().optional(),
head: z
.object({
sha: z.string(),
})
.passthrough(),
})
.passthrough();
const giteaIssueCommentSchema = z
.object({
id: z.number(),
html_url: z.string().optional(),
type: z.string().optional(),
})
.passthrough();
const giteaReviewSchema = z
.object({
id: z.number(),
state: z.string(),
comments_count: z.number().optional().default(0),
submitted_at: z.string().nullable().optional(),
updated_at: z.string().nullable().optional(),
html_url: z.string().optional(),
})
.passthrough();
const giteaReviewCommentSchema = z
.object({
id: z.number(),
html_url: z.string().optional(),
})
.passthrough();
const giteaActionJobSchema = z.object({
id: z.number(),
name: z.string(),
status: z.string(),
conclusion: z.string().nullable().optional(),
html_url: z.string().nullable().optional(),
});
const giteaActionJobsPageSchema = z.union([
z.object({
jobs: z
.array(giteaActionJobSchema)
.nullable()
.transform((jobs) => jobs ?? []),
total_count: z.number(),
}),
// Forgejo returns the complete job list as an array.
z.array(giteaActionJobSchema),
]);
type GiteaActionJob = z.infer<typeof giteaActionJobSchema>;
type GiteaWatchPr = z.infer<typeof giteaWatchPrSchema>;
type GiteaReview = z.infer<typeof giteaReviewSchema>;
interface GiteaPullRequestIdentity {
baseUrl: string;
displayBase: string | null;
owner: string;
repo: string;
number: number;
}
function invalidGiteaUrl(): never {
throw new Error("Enter a Gitea, Forgejo, or Codeberg pull request URL.");
}
function parseGiteaUrlOrigin(input: string): {
protocol: "http:" | "https:";
host: string;
port: string;
hostWithPort: string;
pathname: string;
} {
const trimmed = input.trim();
if (!trimmed || /\s/.test(trimmed)) invalidGiteaUrl();
let parsed: URL;
try {
parsed = new URL(trimmed);
} catch {
invalidGiteaUrl();
}
const protocol = parsed.protocol.toLowerCase();
if ((protocol !== "https:" && protocol !== "http:") || parsed.username || parsed.password) {
invalidGiteaUrl();
}
const host = normalizeHost(parsed.hostname);
if (!host || (GITEA_CLOUD_HOSTS.has(host) && protocol !== "https:")) {
invalidGiteaUrl();
}
return {
protocol: protocol as "http:" | "https:",
host,
port: parsed.port,
hostWithPort: parsed.port ? `${host}:${parsed.port}` : host,
pathname: parsed.pathname,
};
}
function decodeRepoSegment(raw: string): string {
let decoded: string;
try {
decoded = decodeURIComponent(raw);
} catch {
invalidGiteaUrl();
}
if (
!decoded ||
decoded === "." ||
decoded === ".." ||
decoded.includes("/") ||
decoded.includes("\\")
) {
invalidGiteaUrl();
}
return decoded;
}
function parseGiteaPullRequestUrl(input: string): GiteaPullRequestIdentity {
const origin = parseGiteaUrlOrigin(input);
const segments = origin.pathname.split("/").filter(Boolean);
if (
segments.length >= 5 &&
GITEA_PR_TABS.has(segments.at(-1)!.toLowerCase()) &&
/^\d+$/.test(segments.at(-2)!)
) {
segments.pop();
}
const rawNumber = segments.pop();
const number = Number(rawNumber);
const resource = segments.pop();
const repo = segments.pop();
const owner = segments.pop();
if (
resource?.toLowerCase() !== "pulls" ||
!owner ||
!repo ||
!rawNumber ||
!/^\d+$/.test(rawNumber) ||
!Number.isInteger(number) ||
number < 1 ||
number > 2_147_483_647
) {
invalidGiteaUrl();
}
const path = segments.length ? `/${segments.join("/")}` : "";
const displayBase =
!path && !origin.port && GITEA_CLOUD_HOSTS.has(origin.host)
? null
: `${origin.hostWithPort}${path}`;
return {
baseUrl: `${origin.protocol}//${origin.hostWithPort}${path}`,
displayBase,
owner: decodeRepoSegment(owner),
repo: decodeRepoSegment(repo),
number,
};
}
export function resolveGiteaChangeRequest(input: string): string {
const { baseUrl, owner, repo, number } = parseGiteaPullRequestUrl(input);
return `${baseUrl}/${owner.toLowerCase()}/${repo.toLowerCase()}/pulls/${number}`;
}
export function describeGiteaChangeRequest(url: string): string {
const { displayBase, owner, repo, number } = parseGiteaPullRequestUrl(url);
const project = displayBase ? `${displayBase}/${owner}/${repo}` : `${owner}/${repo}`;
return `${project} #${number}`;
}
function mapGiteaPrState(pr: GiteaWatchPr): ChangeRequestSnapshot["state"] {
if (pr.merged === true || pr.merged_at != null) return "merged";
const normalized = pr.state.toLowerCase();
if (normalized === "open") return "open";
if (normalized === "merged") return "merged";
return "closed";
}
function mapCommitStatusToWatchState(
status: string,
): ChangeRequestSnapshot["checks"][number]["state"] {
switch (status.toLowerCase()) {
case "success":
return "passed";
case "failure":
case "error":
case "warning":
return "failed";
case "pending":
case "running":
return "pending";
default:
return "neutral";
}
}
function isCanceledActionStatus(status: GiteaCommitStatus): boolean {
// Actions writes a generic failure state on cancellation, with a distinct
// description in the native job's commit status.
const description = status.description ?? "";
return description === "Has been cancelled" || description.startsWith("Canceled after ");
}
function mapActionTaskToWatchState(
status: string,
): ChangeRequestSnapshot["checks"][number]["state"] {
switch (status.toLowerCase()) {
case "success":
return "passed";
case "failure":
case "failed":
case "error":
return "failed";
case "cancelled":
case "canceled":
case "skipped":
return "neutral";
default:
return "pending";
}
}
function computeAggregateChecksState(
checks: ChangeRequestSnapshot["checks"],
): ChangeRequestSnapshot["checksState"] {
if (checks.length === 0) return "neutral";
if (checks.some((check) => check.state === "failed")) return "failed";
if (checks.some((check) => check.state === "pending")) return "pending";
if (checks.some((check) => check.state === "passed")) return "passed";
return "neutral";
}
function nativeActionUrl(value: string | null | undefined, origin: string) {
if (!value) return null;
try {
const url = new URL(value, origin);
if (url.origin !== origin) return null;
const match = /^(.*\/actions\/runs\/(\d+))(\/jobs\/\d+)?\/?$/.exec(url.pathname);
if (!match) return null;
const [, run, runId, job] = match;
return { run: run!, runId: runId!, jobUrl: job ? `${origin}${run}${job}` : null };
} catch {
return null;
}
}
function combineWatchChecks(
commitStatuses: GiteaCommitStatus[],
actionTasks: GiteaActionTask[],
jobsByRun: ReadonlyMap<string, GiteaActionJob[]>,
origin: string,
): ChangeRequestSnapshot["checks"] {
const checks: ChangeRequestSnapshot["checks"] = [];
const actionJobs = [...jobsByRun.values()].flat();
const coveredJobUrls = new Set(
actionJobs.map((job) => nativeActionUrl(job.html_url, origin)?.jobUrl),
);
for (const status of commitStatuses) {
const jobUrl = nativeActionUrl(status.target_url, origin)?.jobUrl;
if (jobUrl && coveredJobUrls.has(jobUrl)) continue;
const url = checkUrlSchema.safeParse(status.target_url).data;
checks.push({
id: `status:${status.id}`,
name: status.context || `status-${status.id}`,
state:
jobUrl && isCanceledActionStatus(status)
? "neutral"
: mapCommitStatusToWatchState(status.status),
...(url ? { url } : {}),
});
}
for (const job of actionJobs) {
const url = checkUrlSchema.safeParse(job.html_url).data;
checks.push({
id: `action-job:${job.id}`,
name: job.name,
state: mapActionTaskToWatchState(job.conclusion || job.status),
...(url ? { url } : {}),
});
}
const seenTaskIds = new Set<number>();
for (const task of actionTasks) {
if (seenTaskIds.has(task.id)) continue;
const address = nativeActionUrl(task.url, origin);
if (address && jobsByRun.has(address.run)) continue;
seenTaskIds.add(task.id);
const url = checkUrlSchema.safeParse(task.url).data;
checks.push({
id: `action:${task.id}`,
name: getGiteaActionTaskName(task),
state: mapActionTaskToWatchState(task.status),
...(url ? { url } : {}),
});
}
return checks;
}
function hasNextLinkHeader(headers: ReadonlyMap<string, string>): boolean {
const link = headers.get("link");
return link ? /rel=["']?next["']?/i.test(link) : false;
}
function parseTotalCountHeader(headers: ReadonlyMap<string, string>): number | null {
const raw = headers.get("x-total-count");
if (!raw) return null;
const parsed = Number(raw);
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
}
function isSubmittedGiteaReview(review: GiteaReview): boolean {
const state = review.state.trim().toUpperCase();
return state !== "PENDING" && state !== "REQUEST_REVIEW";
}
function parseTeaHttpStreams(
stdout: string,
stderr: string,
): {
status: number | null;
headers: Map<string, string>;
body: string;
} {
const fromStdout = parseCliHttpResponse(stdout);
if (fromStdout.status !== null) {
return fromStdout;
}
const fromStderr = parseCliHttpResponse(stderr);
if (fromStderr.status !== null) {
return { status: fromStderr.status, headers: fromStderr.headers, body: stdout.trim() };
}
return { status: null, headers: new Map(), body: stdout.trim() };
}
class TeaHttpStatusError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.name = "TeaHttpStatusError";
this.status = status;
}
}
function isOptionalEndpointStatus(error: unknown): boolean {
return (
error instanceof TeaHttpStatusError &&
(error.status === 403 || error.status === 404 || error.status === 501)
);
}
type TeaApiGet = <T>(
endpoint: string,
schema: z.ZodType<T>,
) => Promise<{ data: T; headers: ReadonlyMap<string, string> }>;
interface TeaPollApi {
get: TeaApiGet;
all<T extends readonly unknown[]>(
reads: T,
): Promise<{ -readonly [Key in keyof T]: Awaited<T[Key]> }>;
}
interface CachedReviewComments {
count: number;
fetchedAt: number;
items: ChangeRequestSnapshot["activity"];
}
export interface CreateGiteaChangeRequestSourceOptions {
runCommand(
args: string[],
options: { cwd: string; envOverlay?: Record<string, string> },
): Promise<{ stdout: string; stderr: string }>;
createAuthError(stderr: string): Error;
createCommandError(params: {
args: string[];
cwd: string;
exitCode: number | null;
stderr: string;
stdout?: string;
}): Error;
now?: () => number;
pollIntervalMs?: number;
initialDelayMs?: number;
}
export function createGiteaChangeRequestSource(
options: CreateGiteaChangeRequestSourceOptions,
): ChangeRequestSource & { dispose(): void } {
const now = options.now ?? Date.now;
const cachedReviewCommentsByUrl = new Map<string, Map<number, CachedReviewComments>>();
const reviewCommentLimit = pLimit(GITEA_REVIEW_COMMENT_CONCURRENCY);
async function resolveLogin(baseUrl: string): Promise<string> {
const result = await options.runCommand(["login", "list", "-o", "json"], {
cwd: process.cwd(),
});
const loginName = findTeaLoginNameForBaseUrl(result.stdout, baseUrl);
if (!loginName) {
throw options.createAuthError(`No tea login configured for ${baseUrl}`);
}
return loginName;
}
function parseJsonBody<T>(params: {
args: string[];
cwd: string;
body: string;
schema: z.ZodType<T>;
}): T {
let data: unknown;
try {
data = JSON.parse(params.body);
} catch {
throw options.createCommandError({
args: params.args,
cwd: params.cwd,
exitCode: null,
stderr: `tea did not return valid JSON (${params.body.length} bytes)`,
});
}
const parsed = params.schema.safeParse(data);
if (!parsed.success) {
throw options.createCommandError({
args: params.args,
cwd: params.cwd,
exitCode: null,
stderr: `tea JSON did not match the expected schema: ${parsed.error.message}`,
});
}
return parsed.data;
}
function bindTeaApi(context: PerHostReadContext, loginName: string): TeaPollApi {
let active = true;
const get: TeaApiGet = async (endpoint, schema) => {
if (!active || !context.isObserved()) throw new Error("Change request observation ended");
context.assertHostAvailable();
const args = ["api", "--login", loginName, "-i", endpoint];
const cwd = process.cwd();
const result = await options.runCommand(args, { cwd });
const parsed = parseTeaHttpStreams(result.stdout, result.stderr);
const nowMs = now();
// tea api can exit 0 on an HTTP failure, so always check the status line.
if (parsed.status === null) {
throw options.createCommandError({
args,
cwd,
exitCode: 0,
stderr: "tea api -i did not return an HTTP status line",
stdout: result.stdout,
});
}
if (parsed.status === 429) {
const resetAtMs = parseRetryAfterMs(parsed.headers, nowMs, {
forceOnMissing: true,
defaultPauseMs: 60_000,
})!;
context.pauseHost(resetAtMs);
throw new ChangeRequestRateLimitError({ host: context.host, resetAtMs });
}
if (parsed.status === 401) {
throw options.createAuthError(parsed.body || "401 Unauthorized");
}
if (parsed.status < 200 || parsed.status >= 300) {
throw new TeaHttpStatusError(
parsed.status,
`Gitea API returned HTTP ${parsed.status} for ${endpoint}: ${parsed.body}`.trim(),
);
}
const proactivePause = parseRetryAfterMs(parsed.headers, nowMs);
if (proactivePause !== null) context.deferPollsUntil(proactivePause);
const data = parseJsonBody({ args, cwd, body: parsed.body, schema });
return { data, headers: parsed.headers };
};
return {
get,
all(reads) {
return Promise.all(reads).catch(async (error: unknown) => {
// Stop admitting reads from this poll and hold its host slot until
// requests already sent (including late rate limits) settle.
active = false;
await Promise.allSettled(reads);
throw error;
});
},
};
}
async function teaApiGetAllPages<T>(params: {
get: TeaApiGet;
endpoint: string;
itemSchema: z.ZodType<T>;
}): Promise<T[]> {
const items: T[] = [];
const schema = z.array(params.itemSchema);
let minPageSize = 1;
for (let page = 1; ; page += 1) {
const sep = params.endpoint.includes("?") ? "&" : "?";
const { data, headers } = await params.get(
`${params.endpoint}${sep}page=${page}&limit=${GITEA_PAGE_SIZE}`,
schema,
);
items.push(...data);
if (headers.has("link")) {
if (hasNextLinkHeader(headers)) continue;
break;
}
const totalCount = parseTotalCountHeader(headers);
if (totalCount !== null) {
// Gitea can cap limit below the requested value and filter pending
// reviews after pagination. The largest page is a lower bound on
// the number of records advanced on every page.
minPageSize = Math.max(minPageSize, data.length);
if (page * minPageSize < totalCount) continue;
break;
}
if (data.length < GITEA_PAGE_SIZE) break;
}
return items;
}
async function readCommitStatuses(params: {
get: TeaApiGet;
repoPrefix: string;
headSha: string;
isObserved(): boolean;
}): Promise<{ statuses: GiteaCommitStatus[]; pagesRead: number }> {
const statuses: GiteaCommitStatus[] = [];
const seenIds = new Set<number>();
let page = 1;
let pagesRead = 0;
while (true) {
if (!params.isObserved()) return { statuses, pagesRead };
const response = await params.get(
`${params.repoPrefix}/commits/${encodeURIComponent(params.headSha)}/status?limit=${GITEA_PAGE_SIZE}&page=${page}`,
GiteaCombinedCommitStatusSchema,
);
pagesRead += 1;
const pageStatuses = response.data.statuses;
if (pageStatuses.length === 0) break;
for (const status of pageStatuses) {
if (seenIds.has(status.id)) {
throw new Error("Gitea commit status pages overlap. Retry the poll.");
}
seenIds.add(status.id);
statuses.push(status);
}
// Gitea sets body `total_count` to the current page length; the full total
// lives only in the `X-Total-Count` response header.
const headerTotal = parseTotalCountHeader(response.headers);
if (headerTotal !== null) {
if (statuses.length >= headerTotal) break;
page += 1;
continue;
}
if (hasNextLinkHeader(response.headers) || pageStatuses.length >= GITEA_PAGE_SIZE) {
page += 1;
continue;
}
break;
}
return { statuses, pagesRead };
}
async function readBoundedActionTasks(params: {
get: TeaApiGet;
repoPrefix: string;
isObserved(): boolean;
}): Promise<{ items: unknown[]; pagesRead: number }> {
const items: unknown[] = [];
let fetched = 0;
let pagesRead = 0;
for (let page = 1; page <= GITEA_ACTION_MAX_PAGES; page += 1) {
if (!params.isObserved()) return { items, pagesRead };
let response: { data: z.infer<typeof GiteaActionsListResponseSchema> };
try {
response = await params.get(
`${params.repoPrefix}/actions/tasks?limit=${GITEA_PAGE_SIZE}&page=${page}`,
GiteaActionsListResponseSchema,
);
} catch (error) {
if (page === 1 && isOptionalEndpointStatus(error)) {
return { items: [], pagesRead: 0 };
}
throw error;
}
pagesRead += 1;
const runs = response.data.workflow_runs;
if (runs.length === 0) break;
fetched += runs.length;
items.push(...runs);
if (response.data.total_count !== undefined && fetched >= response.data.total_count) break;
}
return { items, pagesRead };
}
async function readActionJobs(params: {
get: TeaApiGet;
origin: string;
repoPrefix: string;
tasks: GiteaActionTask[];
statuses: GiteaCommitStatus[];
}): Promise<Map<string, GiteaActionJob[]>> {
// Commit statuses identify a job URL. Tasks identify a run, so only a job
// list can establish coverage when both sources report the same run.
const statusRuns = new Set<string>();
for (const status of params.statuses) {
const address = nativeActionUrl(status.target_url, params.origin);
if (address?.jobUrl) statusRuns.add(address.run);
}
const runs = new Map<string, string>();
for (const task of params.tasks) {
const address = nativeActionUrl(task.url, params.origin);
if (address && statusRuns.has(address.run)) runs.set(address.run, address.runId);
}
const jobsByRun = new Map<string, GiteaActionJob[]>();
for (const [run, runId] of [...runs].slice(0, GITEA_ACTION_RUN_LOOKUP_LIMIT)) {
const endpoint = `${params.repoPrefix}/actions/runs/${runId}/jobs`;
const jobs = new Map<number, GiteaActionJob>();
for (let page = 1; page <= GITEA_ACTION_MAX_PAGES; page += 1) {
try {
const { data } = await params.get(
`${endpoint}?limit=${GITEA_PAGE_SIZE}&page=${page}`,
giteaActionJobsPageSchema,
);
const items = Array.isArray(data) ? data : data.jobs;
const totalCount = Array.isArray(data) ? data.length : data.total_count;
if (!items.length) break;
// The browser run number and API ID differ on some versions. Keep
// the original sources if any job belongs to another run.
if (items.some((job) => nativeActionUrl(job.html_url, params.origin)?.run !== run)) {
break;
}
for (const job of items) jobs.set(job.id, job);
if (jobs.size >= totalCount) {
jobsByRun.set(run, [...jobs.values()]);
break;
}
} catch (error) {
if (page === 1 && isOptionalEndpointStatus(error)) break;
throw error;
}
}
}
return jobsByRun;
}
async function readChecks(params: {
api: TeaPollApi;
origin: string;
repoPrefix: string;
prEndpoint: string;
headSha: string;
isObserved(): boolean;
}): Promise<ChangeRequestSnapshot["checks"]> {
const { get, all } = params.api;
const [statusResult, tasksResult] = await all([
readCommitStatuses({ ...params, get }),
readBoundedActionTasks({ ...params, get }),
]);
if (!params.isObserved()) {
throw new Error("Change request observation ended");
}
const matchingTasks = parseGiteaActionTasks(tasksResult.items).filter(
(task) => task.head_sha === params.headSha,
);
const latestTasks = latestGiteaActionTasksByWorkflow(matchingTasks);
const jobsByRun = await readActionJobs({
...params,
get,
tasks: latestTasks,
statuses: statusResult.statuses,
});
if (statusResult.pagesRead > 1 || tasksResult.pagesRead > 1 || jobsByRun.size > 0) {
const { data: recheck } = await get(params.prEndpoint, giteaWatchPrSchema);
if (recheck.head.sha !== params.headSha) {
throw new Error("The pull request head changed during pagination.");
}
}
return combineWatchChecks(statusResult.statuses, latestTasks, jobsByRun, params.origin);
}
async function readActivity(params: {
url: string;
api: TeaPollApi;
repoPrefix: string;
number: number;
prWebUrl: string;
terminal: boolean;
knownActivity(): ReadonlySet<string> | undefined;
isObserved(): boolean;
}): Promise<ChangeRequestSnapshot["activity"]> {
const { get, all } = params.api;
const [comments, reviews] = await all([
teaApiGetAllPages({
get,
endpoint: `${params.repoPrefix}/issues/${params.number}/comments`,
itemSchema: giteaIssueCommentSchema,
}),
teaApiGetAllPages({
get,
endpoint: `${params.repoPrefix}/pulls/${params.number}/reviews`,
itemSchema: giteaReviewSchema,
}),
]);
if (!params.isObserved()) {
throw new Error("Change request observation ended");
}
const activity: ChangeRequestSnapshot["activity"] = [];
for (const comment of comments) {
if (comment.type !== undefined && comment.type !== "comment") continue;
activity.push({
id: `comment:${comment.id}`,
kind: "comment",
url: comment.html_url || `${params.prWebUrl}#issuecomment-${comment.id}`,
});
}
const submittedReviews = reviews.filter(isSubmittedGiteaReview);
for (const review of submittedReviews) {
activity.push({
id: `review:${review.id}`,
kind: "review",
url: review.html_url || `${params.prWebUrl}#pullrequestreview-${review.id}`,
});
}
const known = params.knownActivity();
let reviewCache = cachedReviewCommentsByUrl.get(params.url);
if (!reviewCache) {
reviewCache = new Map<number, CachedReviewComments>();
cachedReviewCommentsByUrl.set(params.url, reviewCache);
}
const staleBefore = now() - GITEA_REVIEW_COMMENTS_TTL_MS;
const reviewsNeedingFetch = submittedReviews.filter((review) => {
if (review.comments_count <= 0) return false;
const cached = reviewCache.get(review.id);
if (
!params.terminal &&
cached &&
cached.fetchedAt > staleBefore &&
cached.count === review.comments_count &&
cached.items.every((item) => known?.has(item.id))
) {
return false;
}
return true;
});
// Gitea's review-comments endpoint returns all comments for a review in one
// response and ignores page/limit, so fetch it once without a pagination loop.
const fetchedGroups = await all(
reviewsNeedingFetch.map((review) =>
reviewCommentLimit(async () => {
if (!params.isObserved()) {
return { reviewId: review.id, count: review.comments_count, items: [] };
}
const { data: inlineComments } = await get(
`${params.repoPrefix}/pulls/${params.number}/reviews/${review.id}/comments`,
z.array(giteaReviewCommentSchema),
);
const items: ChangeRequestSnapshot["activity"] = inlineComments.map((comment) => ({
id: `inline:${comment.id}`,
kind: "inline comment",
url: comment.html_url || `${params.prWebUrl}#issuecomment-${comment.id}`,
}));
return { reviewId: review.id, count: review.comments_count, items };
}),
),
);
if (!params.isObserved()) {
throw new Error("Change request observation ended");
}
const fetchedAt = now();
for (const group of fetchedGroups) {
reviewCache.set(group.reviewId, { count: group.count, fetchedAt, items: group.items });
}
for (const review of submittedReviews) {
if (review.comments_count <= 0) continue;
const cached = reviewCache.get(review.id);
if (cached) {
activity.push(...cached.items);
}
}
return activity;
}
async function readPullRequest(context: PerHostReadContext): Promise<ChangeRequestSnapshot> {
const identity = parseGiteaPullRequestUrl(context.url);
const { baseUrl, owner, repo, number } = identity;
const loginName = await resolveLogin(baseUrl);
const api = bindTeaApi(context, loginName);
const repoPrefix = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
const prEndpoint = `${repoPrefix}/pulls/${number}`;
const { data: pr } = await api.get(prEndpoint, giteaWatchPrSchema);
if (!pr.head.sha) {
throw new Error(`Gitea pull request #${number} did not include a head commit SHA.`);
}
const prWebUrl = pr.html_url || context.url;
const address = parseGiteaPullRequestUrl(prWebUrl);
if (
address.baseUrl !== baseUrl ||
address.owner.toLowerCase() !== owner.toLowerCase() ||
address.repo.toLowerCase() !== repo.toLowerCase() ||
address.number !== number ||
pr.number !== number
) {
throw new Error("Tea returned a pull request that does not match the watch URL.");
}
const checks = await readChecks({
api,
origin: context.host,
repoPrefix,
prEndpoint,
headSha: pr.head.sha,
isObserved: context.isObserved,
});
const state = mapGiteaPrState(pr);
const activity = await readActivity({
url: context.url,
api,
repoPrefix,
number,
prWebUrl,
terminal: state !== "open",
knownActivity: context.knownActivity,
isObserved: context.isObserved,
});
return {
state,
headSha: pr.head.sha,
checksState: computeAggregateChecksState(checks),
checks,
reviewDecision: null,
activity,
};
}
const poller = createPerHostChangeRequestPoller({
hostOf: (url) => new URL(url).origin,
read: readPullRequest,
now,
pollIntervalMs: options.pollIntervalMs,
initialDelayMs: options.initialDelayMs,
});
return {
resolve: resolveGiteaChangeRequest,
describe: describeGiteaChangeRequest,
observe(url, callbacks) {
const release = poller.observe(url, callbacks);
return () => {
cachedReviewCommentsByUrl.delete(url);
release();
};
},
dispose() {
cachedReviewCommentsByUrl.clear();
poller.dispose();
},
};
}
@@ -0,0 +1,253 @@
import { z } from "zod";
import { normalizeHost } from "@getpaseo/protocol/git-remote";
// 50 is the page-size cap Gitea enforces on list endpoints; five pages bounds
// the sweep to the 250 most recent Actions tasks.
export const GITEA_ACTION_PAGE_LIMIT = 50;
export const GITEA_ACTION_MAX_PAGES = 5;
const GITEA_RELATIVE_URL_ORIGIN = "https://gitea.invalid";
export const GiteaLoginSchema = z
.object({
name: z.string().optional(),
url: z.string().optional(),
ssh_host: z.string().optional(),
})
.passthrough();
export const GiteaCommitStatusSchema = z
.object({
id: z.number(),
status: z.string(),
target_url: z.string().nullable().optional(),
description: z.string().nullable().optional(),
url: z.string().nullable().optional(),
context: z.string().optional().default(""),
creator: z.unknown().nullable().optional(),
})
.passthrough();
export const GiteaCombinedCommitStatusSchema = z
.object({
state: z.string().optional().default(""),
sha: z.string().optional(),
total_count: z.number().optional(),
statuses: z
.array(GiteaCommitStatusSchema)
.nullable()
.optional()
.transform((value) => value ?? []),
})
.passthrough();
export const GiteaActionTaskSchema = z
.object({
id: z.number(),
name: z.string().nullable().optional(),
head_branch: z.string().nullable().optional(),
head_sha: z.string(),
run_number: z.number().optional(),
event: z.string().nullable().optional(),
display_title: z.string().nullable().optional(),
status: z.string(),
need_approval: z.boolean().optional().default(false),
workflow_id: z.string().nullable().optional(),
url: z.string().nullable().optional(),
created_at: z.string().nullable().optional(),
run_started_at: z.string().nullable().optional(),
})
.passthrough();
// The item shape is validated per-task rather than as `z.array(GiteaActionTaskSchema)`
// so one malformed task (missing id/status/head_sha) drops only itself instead of
// throwing out the whole page and zeroing every Actions check for the PR.
export const GiteaActionsListResponseSchema = z
.object({
workflow_runs: z
.array(z.unknown())
.nullable()
.optional()
.transform((value) => value ?? []),
total_count: z.number().optional(),
})
.passthrough();
export type GiteaCommitStatus = z.infer<typeof GiteaCommitStatusSchema>;
export type GiteaCombinedCommitStatus = z.infer<typeof GiteaCombinedCommitStatusSchema>;
export type GiteaActionTask = z.infer<typeof GiteaActionTaskSchema>;
export function getGiteaActionTaskName(task: GiteaActionTask): string {
return task.name || task.display_title || task.workflow_id || `actions-${task.id}`;
}
export function getUrlOrigin(value: string | null | undefined): string | null {
if (!value) return null;
try {
return new URL(value).origin;
} catch {
return null;
}
}
export function getGiteaActionRunIdFromUrl(value: string | null | undefined): number | null {
if (!value) return null;
try {
const url = new URL(value, GITEA_RELATIVE_URL_ORIGIN);
const match = url.pathname.match(/\/actions\/runs\/(\d+)(?:\/jobs\/\d+)?\/?$/);
return match?.[1] ? Number.parseInt(match[1], 10) : null;
} catch {
return null;
}
}
function isNativeActionJobUrl(
targetUrl: string | null | undefined,
nativeOrigins: ReadonlySet<string>,
nativeRunIds: ReadonlySet<number>,
): boolean {
if (!targetUrl) return false;
try {
const url = new URL(targetUrl, GITEA_RELATIVE_URL_ORIGIN);
if (!/\/actions\/runs\/\d+\/jobs\/\d+\/?$/.test(url.pathname)) return false;
if (url.origin !== GITEA_RELATIVE_URL_ORIGIN && !nativeOrigins.has(url.origin)) return false;
const runId = getGiteaActionRunIdFromUrl(targetUrl);
return runId !== null && nativeRunIds.has(runId);
} catch {
return false;
}
}
// A "shadow" is the commit status Gitea synthesizes to mirror one of its own
// Actions jobs; keeping both would double-report every job. Detection is purely
// structural: Gitea always creates these statuses with a target_url of the form
// "<run link>/jobs/<job id>" (services/actions/commit_status.go upstream), so a
// status is a shadow exactly when its URL points at a job of a run we actually
// fetched from the Actions API. Anything else - external CI, URL-less statuses,
// contexts that merely look like "<workflow> / <job> (<event>)" - is kept.
export function isGiteaActionShadowStatus(
status: GiteaCommitStatus,
nativeOrigins: ReadonlySet<string>,
nativeRunIds: ReadonlySet<number>,
): boolean {
return isNativeActionJobUrl(status.target_url, nativeOrigins, nativeRunIds);
}
function getGiteaActionWorkflowIdentity(task: GiteaActionTask): string {
if (task.workflow_id) {
return `workflow\u0000${task.workflow_id}`;
}
// Instances that omit workflow_id (older Gitea/Forgejo payloads) still need
// reruns of the same job collapsed to the latest execution, so fall back to
// the job name before treating the task as its own group.
const name = task.name || task.display_title;
if (name) {
return `name\u0000${name}`;
}
return `task\u0000${getGiteaActionExecutionIdentity(task)}`;
}
function getGiteaActionExecutionIdentity(task: GiteaActionTask): string {
if (task.run_number !== undefined) return `run-number\u0000${task.run_number}`;
const runId = getGiteaActionRunIdFromUrl(task.url);
if (runId !== null) return `run-id\u0000${runId}`;
if (task.url) return `url\u0000${task.url}`;
return `task\u0000${task.id}`;
}
function parseGiteaActionTaskTime(task: GiteaActionTask): number {
const timestamp = task.created_at ?? task.run_started_at ?? null;
if (!timestamp) {
return 0;
}
const time = Date.parse(timestamp);
return Number.isNaN(time) ? 0 : time;
}
function compareGiteaActionTaskRecency(left: GiteaActionTask, right: GiteaActionTask): number {
const leftRunNumber = left.run_number ?? 0;
const rightRunNumber = right.run_number ?? 0;
if (leftRunNumber !== rightRunNumber) {
return leftRunNumber - rightRunNumber;
}
const leftTime = parseGiteaActionTaskTime(left);
const rightTime = parseGiteaActionTaskTime(right);
if (leftTime !== rightTime) {
return leftTime - rightTime;
}
return left.id - right.id;
}
export function parseGiteaActionTasks(rawTasks: unknown[]): GiteaActionTask[] {
const tasks: GiteaActionTask[] = [];
for (const raw of rawTasks) {
const parsed = GiteaActionTaskSchema.safeParse(raw);
if (parsed.success) {
tasks.push(parsed.data);
}
}
return tasks;
}
/**
* Keep all sibling tasks from the latest execution of each workflow.
* Per docs/forge-providers.md, ambiguous same-run tasks are preserved because
* display names are not stable job identities and `/actions/tasks` omits rerun
* attempt numbers.
*/
export function latestGiteaActionTasksByWorkflow(tasks: GiteaActionTask[]): GiteaActionTask[] {
const latestExecutions = new Map<string, GiteaActionTask>();
for (const task of tasks) {
const identity = getGiteaActionWorkflowIdentity(task);
const current = latestExecutions.get(identity);
if (!current || compareGiteaActionTaskRecency(current, task) < 0) {
latestExecutions.set(identity, task);
}
}
return tasks.filter((task) => {
const latest = latestExecutions.get(getGiteaActionWorkflowIdentity(task));
return (
latest !== undefined &&
getGiteaActionExecutionIdentity(task) === getGiteaActionExecutionIdentity(latest)
);
});
}
function parseTeaLogins(stdout: string): z.infer<typeof GiteaLoginSchema>[] {
try {
return z.array(GiteaLoginSchema).safeParse(JSON.parse(stdout)).data ?? [];
} catch {
return [];
}
}
export function findTeaLoginNameForBaseUrl(stdout: string, baseUrl: string): string | null {
const match = parseTeaLogins(stdout).find((login) => {
if (!login.name || !login.url) return false;
try {
const url = new URL(login.url);
return `${url.origin}${url.pathname.replace(/\/+$/, "")}` === baseUrl;
} catch {
return false;
}
});
return match?.name ?? null;
}
export function findTeaLoginNameForHost(stdout: string, host: string): string | null {
const targetHost = normalizeHost(host);
const match = parseTeaLogins(stdout).find((login) => {
const candidates = [login.ssh_host, login.name];
if (login.url) {
try {
candidates.push(new URL(login.url).hostname);
} catch {
// ignore malformed login url
}
}
return candidates.some((candidate) => candidate && normalizeHost(candidate) === targetHost);
});
return match?.name ?? null;
}
+44 -227
View File
@@ -61,6 +61,23 @@ import type {
SearchIssuesAndPrsOptions,
SearchResult,
} from "./forge-service.js";
import {
findTeaLoginNameForHost,
getGiteaActionRunIdFromUrl,
getGiteaActionTaskName,
getUrlOrigin,
GITEA_ACTION_MAX_PAGES,
GITEA_ACTION_PAGE_LIMIT,
GiteaActionsListResponseSchema,
GiteaCombinedCommitStatusSchema,
isGiteaActionShadowStatus,
latestGiteaActionTasksByWorkflow,
parseGiteaActionTasks,
type GiteaActionTask,
type GiteaCombinedCommitStatus,
type GiteaCommitStatus,
} from "./gitea-checks.js";
import { createGiteaChangeRequestSource } from "./gitea-change-requests.js";
import { isGiteaStatusFacts, type GiteaStatusFacts } from "./gitea-facts.js";
const TEA_ENV = {
@@ -77,10 +94,6 @@ const reviewCommentsLimit = pLimit(REVIEW_COMMENTS_FAN_OUT_CONCURRENCY);
// short cache, each poll re-derives the PR head SHA from scratch (branch name +
// PR lookup + PR view). The TTL keeps a new push visible within one poll cycle.
const CURRENT_PR_HEAD_SHA_CACHE_TTL_MS = 30_000;
// 50 is the page-size cap Gitea enforces on list endpoints; five pages bounds
// the sweep to the 250 most recent Actions tasks.
const GITEA_ACTION_PAGE_LIMIT = 50;
const GITEA_ACTION_MAX_PAGES = 5;
// PullRequestFlowAGit in forgejo models/issues/pull.go
const GITEA_PULL_REQUEST_FLOW_AGIT = 1;
@@ -142,6 +155,8 @@ export interface CreateGiteaServiceOptions {
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
resolveCurrentBranch?: (cwd: string) => Promise<string | null>;
now?: () => number;
watchPollMs?: number;
watchInitialDelayMs?: number;
}
/**
@@ -180,14 +195,6 @@ const GiteaIssueListItemSchema = z
})
.passthrough();
const GiteaLoginSchema = z
.object({
name: z.string().optional(),
url: z.string().optional(),
ssh_host: z.string().optional(),
})
.passthrough();
const GiteaUserSchema = z
.object({
login: z.string().optional(),
@@ -288,55 +295,6 @@ const GiteaCurrentPullRequestApiSchema = z
})
.passthrough();
const GiteaCommitStatusSchema = z
.object({
id: z.number(),
status: z.string(),
target_url: z.string().nullable().optional(),
description: z.string().nullable().optional(),
url: z.string().nullable().optional(),
context: z.string().optional().default(""),
creator: z.unknown().nullable().optional(),
})
.passthrough();
const GiteaCombinedCommitStatusSchema = z
.object({
state: z.string().optional().default(""),
sha: z.string().optional(),
total_count: z.number().optional(),
statuses: z.array(GiteaCommitStatusSchema).optional().default([]),
})
.passthrough();
const GiteaActionTaskSchema = z
.object({
id: z.number(),
name: z.string().nullable().optional(),
head_branch: z.string().nullable().optional(),
head_sha: z.string(),
run_number: z.number().optional(),
event: z.string().nullable().optional(),
display_title: z.string().nullable().optional(),
status: z.string(),
need_approval: z.boolean().optional().default(false),
workflow_id: z.string().nullable().optional(),
url: z.string().nullable().optional(),
created_at: z.string().nullable().optional(),
run_started_at: z.string().nullable().optional(),
})
.passthrough();
// The item shape is validated per-task rather than as `z.array(GiteaActionTaskSchema)`
// so one malformed task (missing id/status/head_sha) drops only itself instead of
// throwing out the whole page and zeroing every Actions check for the PR.
const GiteaActionsListResponseSchema = z
.object({
workflow_runs: z.array(z.unknown()).optional().default([]),
total_count: z.number().optional(),
})
.passthrough();
const GiteaActionRunPullRequestRefSchema = z
.object({
repo: z.object({ id: z.number().optional() }).passthrough().nullable().optional(),
@@ -410,9 +368,6 @@ type GiteaPrListItem = z.infer<typeof GiteaPrListItemSchema>;
type GiteaIssueListItem = z.infer<typeof GiteaIssueListItemSchema>;
type GiteaPullRequestView = z.infer<typeof GiteaPullRequestViewSchema>;
type GiteaCurrentPullRequestApi = z.infer<typeof GiteaCurrentPullRequestApiSchema>;
type GiteaCommitStatus = z.infer<typeof GiteaCommitStatusSchema>;
type GiteaCombinedCommitStatus = z.infer<typeof GiteaCombinedCommitStatusSchema>;
type GiteaActionTask = z.infer<typeof GiteaActionTaskSchema>;
type GiteaIssueComment = z.infer<typeof GiteaIssueCommentSchema>;
type GiteaReview = z.infer<typeof GiteaReviewSchema>;
type GiteaReviewComment = z.infer<typeof GiteaReviewCommentSchema>;
@@ -797,10 +752,6 @@ function deriveGiteaActionRequiredRunIds(runs: unknown[], sha: string): Set<numb
return runIds;
}
function getGiteaActionTaskName(task: GiteaActionTask): string {
return task.name || task.display_title || task.workflow_id || `actions-${task.id}`;
}
function toGiteaActionTaskCheck(task: GiteaActionTask): PullRequestCheck {
const rawStatus = task.status.toLowerCase();
return {
@@ -814,136 +765,6 @@ function toGiteaActionTaskCheck(task: GiteaActionTask): PullRequestCheck {
};
}
function getGiteaActionWorkflowIdentity(task: GiteaActionTask): string {
if (task.workflow_id) {
return `workflow\u0000${task.workflow_id}`;
}
// Instances that omit workflow_id (older Gitea/Forgejo payloads) still need
// reruns of the same job collapsed to the latest execution, so fall back to
// the job name before treating the task as its own group.
const name = task.name || task.display_title;
if (name) {
return `name\u0000${name}`;
}
return `task\u0000${getGiteaActionExecutionIdentity(task)}`;
}
function getGiteaActionExecutionIdentity(task: GiteaActionTask): string {
if (task.run_number !== undefined) return `run-number\u0000${task.run_number}`;
const runId = getGiteaActionRunIdFromUrl(task.url);
if (runId !== null) return `run-id\u0000${runId}`;
if (task.url) return `url\u0000${task.url}`;
return `task\u0000${task.id}`;
}
function parseGiteaActionTaskTime(task: GiteaActionTask): number {
const timestamp = task.created_at ?? task.run_started_at ?? null;
if (!timestamp) {
return 0;
}
const time = Date.parse(timestamp);
return Number.isNaN(time) ? 0 : time;
}
function compareGiteaActionTaskRecency(left: GiteaActionTask, right: GiteaActionTask): number {
const leftRunNumber = left.run_number ?? 0;
const rightRunNumber = right.run_number ?? 0;
if (leftRunNumber !== rightRunNumber) {
return leftRunNumber - rightRunNumber;
}
const leftTime = parseGiteaActionTaskTime(left);
const rightTime = parseGiteaActionTaskTime(right);
if (leftTime !== rightTime) {
return leftTime - rightTime;
}
return left.id - right.id;
}
function parseGiteaActionTasks(rawTasks: unknown[]): GiteaActionTask[] {
const tasks: GiteaActionTask[] = [];
for (const raw of rawTasks) {
const parsed = GiteaActionTaskSchema.safeParse(raw);
if (parsed.success) {
tasks.push(parsed.data);
}
}
return tasks;
}
function latestGiteaActionTasksByWorkflow(tasks: GiteaActionTask[]): GiteaActionTask[] {
const latestExecutions = new Map<string, GiteaActionTask>();
for (const task of tasks) {
const identity = getGiteaActionWorkflowIdentity(task);
const current = latestExecutions.get(identity);
if (!current || compareGiteaActionTaskRecency(current, task) < 0) {
latestExecutions.set(identity, task);
}
}
return tasks.filter((task) => {
const latest = latestExecutions.get(getGiteaActionWorkflowIdentity(task));
return (
latest !== undefined &&
getGiteaActionExecutionIdentity(task) === getGiteaActionExecutionIdentity(latest)
);
});
}
function getUrlOrigin(value: string | null | undefined): string | null {
if (!value) return null;
try {
return new URL(value).origin;
} catch {
return null;
}
}
const GITEA_RELATIVE_URL_ORIGIN = "https://gitea.invalid";
function getGiteaActionRunIdFromUrl(value: string | null | undefined): number | null {
if (!value) return null;
try {
const url = new URL(value, GITEA_RELATIVE_URL_ORIGIN);
const match = url.pathname.match(/\/actions\/runs\/(\d+)(?:\/jobs\/\d+)?\/?$/);
return match?.[1] ? Number.parseInt(match[1], 10) : null;
} catch {
return null;
}
}
function isNativeActionJobUrl(
targetUrl: string | null | undefined,
nativeOrigins: ReadonlySet<string>,
nativeRunIds: ReadonlySet<number>,
): boolean {
if (!targetUrl) return false;
try {
const url = new URL(targetUrl, GITEA_RELATIVE_URL_ORIGIN);
if (!/\/actions\/runs\/\d+\/jobs\/\d+\/?$/.test(url.pathname)) return false;
if (url.origin !== GITEA_RELATIVE_URL_ORIGIN && !nativeOrigins.has(url.origin)) return false;
const runId = getGiteaActionRunIdFromUrl(targetUrl);
return runId !== null && nativeRunIds.has(runId);
} catch {
return false;
}
}
// A "shadow" is the commit status Gitea synthesizes to mirror one of its own
// Actions jobs; keeping both would double-report every job. Detection is purely
// structural: Gitea always creates these statuses with a target_url of the form
// "<run link>/jobs/<job id>" (services/actions/commit_status.go upstream), so a
// status is a shadow exactly when its URL points at a job of a run we actually
// fetched from the Actions API. Anything else - external CI, URL-less statuses,
// contexts that merely look like "<workflow> / <job> (<event>)" - is kept.
function isGiteaActionShadowStatus(
status: GiteaCommitStatus,
nativeOrigins: ReadonlySet<string>,
nativeRunIds: ReadonlySet<number>,
): boolean {
return isNativeActionJobUrl(status.target_url, nativeOrigins, nativeRunIds);
}
function combineGiteaChecks(
commitStatuses: GiteaCommitStatus[],
actionTasks: GiteaActionTask[],
@@ -1219,32 +1040,6 @@ export async function probeGiteaHost(host: string): Promise<boolean> {
}
}
function findTeaLoginNameForHost(stdout: string, host: string): string | null {
let data: unknown;
try {
data = JSON.parse(stdout);
} catch {
return null;
}
const parsed = z.array(GiteaLoginSchema).safeParse(data);
if (!parsed.success) {
return null;
}
const target = host.toLowerCase();
const match = parsed.data.find((login) => {
const candidates = [login.ssh_host, login.name];
if (login.url) {
try {
candidates.push(new URL(login.url).hostname);
} catch {
// ignore malformed login url
}
}
return candidates.some((candidate) => candidate?.toLowerCase() === target);
});
return match?.name ?? null;
}
function hostHasLogin(stdout: string, host: string): boolean {
return findTeaLoginNameForHost(stdout, host) !== null;
}
@@ -1409,19 +1204,35 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
const now = options.now ?? Date.now;
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
async function runRaw(
args: string[],
runOptions: TeaCommandRunnerOptions,
): Promise<TeaCommandResult> {
const teaPath = await resolveTea();
if (!teaPath) {
throw new TeaCliMissingError();
}
try {
const result = await runner(args, runOptions);
return result.stdout.trim();
return await runner(args, runOptions);
} catch (error) {
throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd });
}
}
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
const result = await runRaw(args, runOptions);
return result.stdout.trim();
}
const changeRequests = createGiteaChangeRequestSource({
runCommand: runRaw,
createAuthError: (stderr) => new TeaAuthenticationError({ stderr }),
createCommandError: (params) => new TeaCommandError(params),
now,
pollIntervalMs: options.watchPollMs,
initialDelayMs: options.watchInitialDelayMs,
});
function runJsonParse<T>(
args: string[],
runOptions: TeaCommandRunnerOptions,
@@ -2359,6 +2170,8 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return notSupported("disablePullRequestAutoMerge");
},
changeRequests,
invalidate(input: { cwd: string }): void {
const prefix = `${input.cwd}:`;
for (const key of currentPrHeadShaCache.keys()) {
@@ -2367,5 +2180,9 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
}
}
},
dispose(): void {
changeRequests.dispose();
},
};
}
@@ -28,28 +28,17 @@ index 73466dd..8440ac9 100644
auto textSize = textLayoutManager_
diff --git a/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt b/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt
index 1794b53..eca5e57 100644
index 9e429b8..1d10014 100644
--- a/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt
+++ b/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt
@@ -33,8 +33,8 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
return mOnPasteListener
}
@@ -36,2 +36,2 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
- override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
- val ic = super.onCreateInputConnection(outAttrs)
+ override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
+ val ic = super.onCreateInputConnection(outAttrs) ?: return null
EditorInfoCompat.setContentMimeTypes(outAttrs, arrayOf("*/*"))
@@ -55,6 +55,6 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
true
}
@@ -58 +58 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
- return InputConnectionCompat.createWrapper(ic!!, outAttrs, callback)
+ return InputConnectionCompat.createWrapper(ic, outAttrs, callback)
}
}
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js
index 51b9dfa..501badf 100644
--- a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js
@@ -119,18 +108,10 @@ index 51b9dfa..501badf 100644
// For Android, PasteTextInput already handles everything internally
// Just need to adapt the onPaste callback format
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js
index 5119e65..77c3aea 100644
index 5119e65..287216a 100644
--- a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js
+++ b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js
@@ -16,7 +16,6 @@ var _nullthrows = _interopRequireDefault(require("nullthrows"));
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
-const emptyFunctionThatReturnsTrue = () => true;
function useMergeRefs(...refs) {
return React.useCallback(current => {
for (const ref of refs) {
@@ -52,6 +51,7 @@ function InternalTextInput(props) {
@@ -52,6 +52,7 @@ function InternalTextInput(props) {
end: propsSelection.end ?? propsSelection.start
}, [propsSelection]);
const [mostRecentEventCount, setMostRecentEventCount] = React.useState(0);
@@ -138,7 +119,7 @@ index 5119e65..77c3aea 100644
const [lastNativeText, setLastNativeText] = React.useState(props.value);
const [lastNativeSelectionState, setLastNativeSelection] = React.useState({
selection: {
@@ -103,7 +103,12 @@ function InternalTextInput(props) {
@@ -103,7 +104,12 @@ function InternalTextInput(props) {
Object.assign(instance, {
clear() {
if (inputRef.current != null) {
@@ -152,7 +133,7 @@ index 5119e65..77c3aea 100644
}
},
isFocused() {
@@ -114,12 +119,12 @@ function InternalTextInput(props) {
@@ -114,12 +120,12 @@ function InternalTextInput(props) {
},
setSelection(start, end) {
if (inputRef.current != null) {
@@ -167,7 +148,7 @@ index 5119e65..77c3aea 100644
const ref = useMergeRefs(setLocalRef, props.forwardedRef);
const _onChange = event => {
const currentText = event.nativeEvent.text;
@@ -128,6 +133,7 @@ function InternalTextInput(props) {
@@ -128,6 +134,7 @@ function InternalTextInput(props) {
if (inputRef.current == null) {
return;
}
@@ -175,14 +156,6 @@ index 5119e65..77c3aea 100644
setLastNativeText(currentText);
setMostRecentEventCount(event.nativeEvent.eventCount);
};
@@ -294,7 +300,6 @@ function InternalTextInput(props) {
onPaste: _onPaste,
onScroll: _onScroll,
onSelectionChange: _onSelectionChange,
- onSelectionChangeShouldSetResponder: emptyFunctionThatReturnsTrue,
placeholder: placeholder,
style: _style,
text: text,
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js
index 75fe015..1d3cd64 100644
--- a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js
@@ -252,18 +225,10 @@ index 75fe015..1d3cd64 100644
// For Android, PasteTextInput already handles everything internally
// Just need to adapt the onPaste callback format
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js
index 39bd607..832dcc2 100644
index 39bd607..f2b1d2f 100644
--- a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js
+++ b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js
@@ -10,7 +10,6 @@ import usePressability from 'react-native/Libraries/Pressability/usePressability
import flattenStyle from 'react-native/Libraries/StyleSheet/flattenStyle';
import nullthrows from 'nullthrows';
import { jsx as _jsx } from "react/jsx-runtime";
-const emptyFunctionThatReturnsTrue = () => true;
function useMergeRefs(...refs) {
return React.useCallback(current => {
for (const ref of refs) {
@@ -46,6 +45,7 @@ function InternalTextInput(props) {
@@ -46,6 +46,7 @@ function InternalTextInput(props) {
end: propsSelection.end ?? propsSelection.start
}, [propsSelection]);
const [mostRecentEventCount, setMostRecentEventCount] = React.useState(0);
@@ -271,7 +236,7 @@ index 39bd607..832dcc2 100644
const [lastNativeText, setLastNativeText] = React.useState(props.value);
const [lastNativeSelectionState, setLastNativeSelection] = React.useState({
selection: {
@@ -97,7 +97,12 @@ function InternalTextInput(props) {
@@ -97,7 +98,12 @@ function InternalTextInput(props) {
Object.assign(instance, {
clear() {
if (inputRef.current != null) {
@@ -285,7 +250,7 @@ index 39bd607..832dcc2 100644
}
},
isFocused() {
@@ -108,12 +113,12 @@ function InternalTextInput(props) {
@@ -108,12 +114,12 @@ function InternalTextInput(props) {
},
setSelection(start, end) {
if (inputRef.current != null) {
@@ -300,7 +265,7 @@ index 39bd607..832dcc2 100644
const ref = useMergeRefs(setLocalRef, props.forwardedRef);
const _onChange = event => {
const currentText = event.nativeEvent.text;
@@ -122,6 +127,7 @@ function InternalTextInput(props) {
@@ -122,6 +128,7 @@ function InternalTextInput(props) {
if (inputRef.current == null) {
return;
}
@@ -308,14 +273,6 @@ index 39bd607..832dcc2 100644
setLastNativeText(currentText);
setMostRecentEventCount(event.nativeEvent.eventCount);
};
@@ -288,7 +294,6 @@ function InternalTextInput(props) {
onPaste: _onPaste,
onScroll: _onScroll,
onSelectionChange: _onSelectionChange,
- onSelectionChangeShouldSetResponder: emptyFunctionThatReturnsTrue,
placeholder: placeholder,
style: _style,
text: text,
diff --git a/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx b/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx
index 12befab..0d23ca5 100644
--- a/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx
@@ -385,19 +342,10 @@ index 12befab..0d23ca5 100644
// For Android, PasteTextInput already handles everything internally
// Just need to adapt the onPaste callback format
diff --git a/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx b/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx
index dcc4a2b..7d10e11 100644
index dcc4a2b..1156458 100644
--- a/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx
+++ b/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx
@@ -27,8 +27,6 @@ import usePressability from 'react-native/Libraries/Pressability/usePressability
import flattenStyle from 'react-native/Libraries/StyleSheet/flattenStyle';
import nullthrows from 'nullthrows';
-const emptyFunctionThatReturnsTrue = () => true;
-
function useMergeRefs<Instance>(
...refs: ReadonlyArray<React.ForwardedRef<Instance> | null | undefined>
): (arg0: Instance | null) => void {
@@ -84,6 +82,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
@@ -84,6 +84,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
const [mostRecentEventCount, setMostRecentEventCount] =
React.useState<number>(0);
@@ -405,7 +353,7 @@ index dcc4a2b..7d10e11 100644
const [lastNativeText, setLastNativeText] = React.useState<
string | undefined
>(props.value);
@@ -181,13 +180,24 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
@@ -181,13 +182,24 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
if (inputRef.current != null) {
Commands.setTextAndSelection(
inputRef.current,
@@ -431,7 +379,7 @@ index dcc4a2b..7d10e11 100644
isFocused(): boolean {
return (
TextInputState.currentlyFocusedInput() ===
@@ -203,7 +213,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
@@ -203,7 +215,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
if (inputRef.current != null) {
Commands.setTextAndSelection(
inputRef.current,
@@ -440,7 +388,7 @@ index dcc4a2b..7d10e11 100644
null,
start,
end
@@ -213,7 +223,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
@@ -213,7 +225,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
});
}
},
@@ -449,7 +397,7 @@ index dcc4a2b..7d10e11 100644
);
const ref = useMergeRefs<PasteTextInputInstance>(
@@ -232,6 +242,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
@@ -232,6 +244,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
return;
}
@@ -457,11 +405,3 @@ index dcc4a2b..7d10e11 100644
setLastNativeText(currentText);
setMostRecentEventCount(event.nativeEvent.eventCount);
};
@@ -445,7 +456,6 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
onPaste={_onPaste}
onScroll={_onScroll}
onSelectionChange={_onSelectionChange}
- onSelectionChangeShouldSetResponder={emptyFunctionThatReturnsTrue}
placeholder={placeholder}
style={_style}
text={text}
-223
View File
@@ -1,223 +0,0 @@
diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js
index daab0e3..d3a629c 100644
--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js
+++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js
@@ -16214,12 +16214,21 @@ __DEV__ &&
else if (
"topTouchEnd" === topLevelType ||
"topTouchCancel" === topLevelType
- )
- if (
- (nativeEvent.changedTouches.forEach(recordTouchEnd),
- (touchHistory.numberActiveTouches = nativeEvent.touches.length),
- 1 === touchHistory.numberActiveTouches)
- ) {
+ ) {
+ nativeEvent.changedTouches.forEach(recordTouchEnd);
+ touchHistory.numberActiveTouches = nativeEvent.touches.length;
+ if (0 === touchHistory.numberActiveTouches) {
+ for (
+ topLevelType = 0;
+ topLevelType < touchBank.length;
+ topLevelType++
+ )
+ if (
+ ((nativeEvent = touchBank[topLevelType]),
+ null != nativeEvent && nativeEvent.touchActive)
+ )
+ nativeEvent.touchActive = !1;
+ } else if (1 === touchHistory.numberActiveTouches) {
for (
topLevelType = 0;
topLevelType < touchBank.length;
@@ -16236,6 +16245,7 @@ __DEV__ &&
(null != topLevelType && topLevelType.touchActive) ||
console.error("Cannot find single active touch.");
}
+ }
},
touchHistory: touchHistory
},
@@ -16314,12 +16324,18 @@ __DEV__ &&
nativeEvent,
nativeEventTarget
) {
- if (isStartish(topLevelType)) trackedTouchCount += 1;
+ if (isStartish(topLevelType))
+ trackedTouchCount =
+ nativeEvent && Array.isArray(nativeEvent.touches)
+ ? nativeEvent.touches.length
+ : trackedTouchCount + 1;
else if (
"topTouchEnd" === topLevelType ||
"topTouchCancel" === topLevelType
)
- if (0 <= trackedTouchCount) --trackedTouchCount;
+ if (nativeEvent && Array.isArray(nativeEvent.touches))
+ trackedTouchCount = nativeEvent.touches.length;
+ else if (0 <= trackedTouchCount) --trackedTouchCount;
else
return (
console.warn(
diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js
index 2625bf6..3d85e32 100644
--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js
+++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js
@@ -546,12 +546,21 @@ var instrumentationCallback,
else if (
"topTouchEnd" === topLevelType ||
"topTouchCancel" === topLevelType
- )
- if (
- (nativeEvent.changedTouches.forEach(recordTouchEnd),
- (touchHistory.numberActiveTouches = nativeEvent.touches.length),
- 1 === touchHistory.numberActiveTouches)
- )
+ ) {
+ nativeEvent.changedTouches.forEach(recordTouchEnd);
+ touchHistory.numberActiveTouches = nativeEvent.touches.length;
+ if (0 === touchHistory.numberActiveTouches) {
+ for (
+ topLevelType = 0;
+ topLevelType < touchBank.length;
+ topLevelType++
+ )
+ if (
+ ((nativeEvent = touchBank[topLevelType]),
+ null != nativeEvent && nativeEvent.touchActive)
+ )
+ nativeEvent.touchActive = !1;
+ } else if (1 === touchHistory.numberActiveTouches)
for (
topLevelType = 0;
topLevelType < touchBank.length;
@@ -564,6 +573,7 @@ var instrumentationCallback,
touchHistory.indexOfSingleActiveTouch = topLevelType;
break;
}
+ }
},
touchHistory: touchHistory
};
@@ -745,12 +755,18 @@ var ResponderEventPlugin = {
nativeEvent,
nativeEventTarget
) {
- if (isStartish(topLevelType)) trackedTouchCount += 1;
+ if (isStartish(topLevelType))
+ trackedTouchCount =
+ nativeEvent && Array.isArray(nativeEvent.touches)
+ ? nativeEvent.touches.length
+ : trackedTouchCount + 1;
else if (
"topTouchEnd" === topLevelType ||
"topTouchCancel" === topLevelType
)
- if (0 <= trackedTouchCount) --trackedTouchCount;
+ if (nativeEvent && Array.isArray(nativeEvent.touches))
+ trackedTouchCount = nativeEvent.touches.length;
+ else if (0 <= trackedTouchCount) --trackedTouchCount;
else return null;
ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent);
if (
diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js
index 544c754..4d5ec08 100644
--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js
+++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js
@@ -611,12 +611,21 @@ var instrumentationCallback,
else if (
"topTouchEnd" === topLevelType ||
"topTouchCancel" === topLevelType
- )
- if (
- (nativeEvent.changedTouches.forEach(recordTouchEnd),
- (touchHistory.numberActiveTouches = nativeEvent.touches.length),
- 1 === touchHistory.numberActiveTouches)
- )
+ ) {
+ nativeEvent.changedTouches.forEach(recordTouchEnd);
+ touchHistory.numberActiveTouches = nativeEvent.touches.length;
+ if (0 === touchHistory.numberActiveTouches) {
+ for (
+ topLevelType = 0;
+ topLevelType < touchBank.length;
+ topLevelType++
+ )
+ if (
+ ((nativeEvent = touchBank[topLevelType]),
+ null != nativeEvent && nativeEvent.touchActive)
+ )
+ nativeEvent.touchActive = !1;
+ } else if (1 === touchHistory.numberActiveTouches)
for (
topLevelType = 0;
topLevelType < touchBank.length;
@@ -629,6 +638,7 @@ var instrumentationCallback,
touchHistory.indexOfSingleActiveTouch = topLevelType;
break;
}
+ }
},
touchHistory: touchHistory
};
@@ -810,12 +820,18 @@ var ResponderEventPlugin = {
nativeEvent,
nativeEventTarget
) {
- if (isStartish(topLevelType)) trackedTouchCount += 1;
+ if (isStartish(topLevelType))
+ trackedTouchCount =
+ nativeEvent && Array.isArray(nativeEvent.touches)
+ ? nativeEvent.touches.length
+ : trackedTouchCount + 1;
else if (
"topTouchEnd" === topLevelType ||
"topTouchCancel" === topLevelType
)
- if (0 <= trackedTouchCount) --trackedTouchCount;
+ if (nativeEvent && Array.isArray(nativeEvent.touches))
+ trackedTouchCount = nativeEvent.touches.length;
+ else if (0 <= trackedTouchCount) --trackedTouchCount;
else return null;
ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent);
if (
diff --git a/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js b/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js
index da29336..7167a2f 100644
--- a/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js
+++ b/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js
@@ -560,9 +560,13 @@ export function processResponderEvent(
): void {
// Track touch count
if (isStartish(topLevelType)) {
- trackedTouchCount += 1;
+ trackedTouchCount = Array.isArray(nativeEvent.touches)
+ ? nativeEvent.touches.length
+ : trackedTouchCount + 1;
} else if (isEndish(topLevelType)) {
- if (trackedTouchCount >= 0) {
+ if (Array.isArray(nativeEvent.touches)) {
+ trackedTouchCount = nativeEvent.touches.length;
+ } else if (trackedTouchCount >= 0) {
trackedTouchCount -= 1;
} else {
if (__DEV__) {
diff --git a/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js b/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js
index c0b4d12..b4aab95 100644
--- a/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js
+++ b/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js
@@ -234,7 +234,14 @@ const ResponderTouchHistoryStore = {
} else if (isEndish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchEnd);
touchHistory.numberActiveTouches = nativeEvent.touches.length;
- if (touchHistory.numberActiveTouches === 1) {
+ if (touchHistory.numberActiveTouches === 0) {
+ for (let i = 0; i < touchBank.length; i++) {
+ const touchTrackToCheck = touchBank[i];
+ if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
+ touchTrackToCheck.touchActive = false;
+ }
+ }
+ } else if (touchHistory.numberActiveTouches === 1) {
for (let i = 0; i < touchBank.length; i++) {
const touchTrackToCheck = touchBank[i];
if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
@@ -152,18 +152,92 @@ index 8d78aea..b84d19e 100644
viewGroup: ViewGroup,
coords: FloatArray,
diff --git a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
index 629c155..dc0790d 100644
index 629c155..2efd508 100644
--- a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
+++ b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
@@ -19,6 +19,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
@@ -19,7 +19,9 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
private val jsGestureHandler: GestureHandler?
val rootView: ViewGroup
private var shouldIntercept = false
+ private var wasIntercepting = false
private var passingTouch = false
+ private var lastTouch: MotionEvent? = null
init {
@@ -118,6 +119,14 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
UiThreadUtil.assertOnUiThread()
@@ -47,6 +49,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
}
fun tearDown() {
+ clearLastTouch()
Log.i(
ReactConstants.TAG,
"[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView",
@@ -90,17 +93,46 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
override fun onCancel() {
shouldIntercept = true
- val time = SystemClock.uptimeMillis()
- val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply {
- action = MotionEvent.ACTION_CANCEL
- }
if (rootView is RootView) {
- rootView.onChildStartedNativeGesture(rootView, event)
+ val cancel = createReactCancelEvent()
+ try {
+ rootView.onChildStartedNativeGesture(rootView, cancel)
+ } finally {
+ cancel.recycle()
+ clearLastTouch()
+ }
}
- event.recycle()
}
}
+ private fun clearLastTouch() {
+ lastTouch?.recycle()
+ lastTouch = null
+ }
+
+ private fun createReactCancelEvent(): MotionEvent {
+ val now = SystemClock.uptimeMillis()
+ val touch = lastTouch ?: return MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
+ // The enclosing React root already dispatched this event before it reached the
+ // gesture handler. A POINTER_UP is still in MotionEvent but already ended in JS.
+ val lifted = if (touch.actionMasked == MotionEvent.ACTION_POINTER_UP) touch.actionIndex else -1
+ val count = touch.pointerCount - if (lifted >= 0) 1 else 0
+ val properties = Array(count) { MotionEvent.PointerProperties() }
+ val coords = Array(count) { MotionEvent.PointerCoords() }
+ var index = 0
+ for (pointer in 0 until touch.pointerCount) {
+ if (pointer == lifted) continue
+ touch.getPointerProperties(pointer, properties[index])
+ touch.getPointerCoords(pointer, coords[index])
+ index++
+ }
+ return MotionEvent.obtain(
+ touch.downTime, now, MotionEvent.ACTION_CANCEL, count, properties, coords,
+ touch.metaState, touch.buttonState, touch.xPrecision, touch.yPrecision,
+ touch.deviceId, touch.edgeFlags, touch.source, touch.flags,
+ )
+ }
+
fun requestDisallowInterceptTouchEvent() {
// If this method gets called it means that some native view is attempting to grab lock for
// touch event delivery. In that case we cancel all gesture recognizers
@@ -115,9 +147,25 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
// We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell
// if `requestDisallow` has been called as a result of a normal gesture handling process or
// as a result of one of the gesture handlers activating
+ // Keep the stream for recognizers that activate between events (e.g. long press).
+ // Once native handling begins, React no longer receives the remaining touches.
+ if (!event.isHoverAction() && (!shouldIntercept || event.actionMasked == MotionEvent.ACTION_DOWN)) {
+ clearLastTouch()
+ if (event.actionMasked != MotionEvent.ACTION_UP && event.actionMasked != MotionEvent.ACTION_CANCEL) {
+ lastTouch = MotionEvent.obtainNoHistory(event)
+ }
+ }
passingTouch = true
orchestrator!!.onTouchEvent(event)
passingTouch = false
-11
View File
@@ -82,17 +82,6 @@ const patchedPackages = [
patchPrefix: "react-native-svg+",
cwd: "packages/app",
},
// Reconcile ResponderEventPlugin trackedTouchCount and ResponderTouchHistoryStore touchBank with
// nativeEvent.touches.length so an unmatched touch start or single-pointer synthetic cancel
// (e.g. Modal dismiss while touching, RNGH pinch takeover, or double ACTION_DOWN in
// ReactRootView/ReactModalHostView) self-heals instead of leaving trackedTouchCount > 0 or stale
// active contacts in touchBank. Remove once upstream React/React Native reconciles both.
{
nodeModulesPath: "node_modules/react-native",
patchPrefix: "react-native+",
},
// Keep Android PasteTextInput aligned with RN AndroidTextInput (omit iOS-only
// onSelectionChangeShouldSetResponder), plus ref/eventCount/trailing-newline fixes.
{
nodeModulesPath: "node_modules/@mattermost/react-native-paste-input",
patchPrefix: "@mattermost+react-native-paste-input+",
-289
View File
@@ -1,11 +1,9 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import vm from "node:vm";
const script = path.resolve("scripts", "postinstall-patches.mjs");
const bin = path.resolve("node_modules", ".bin");
@@ -136,290 +134,3 @@ test("a missing patch-package fails the install and leaves the package in place"
rmSync(root, { recursive: true, force: true });
}
});
function loadReactFabricDispatchEvent(bundleName, isDev) {
const bundlePath = path.resolve(
"node_modules/react-native/Libraries/Renderer/implementations",
bundleName,
);
const code = readFileSync(bundlePath, "utf8");
const nodeRequire = createRequire(import.meta.url);
let dispatchEvent = null;
const warnings = [];
const rawEventListeners = new Map();
const nativeFabricUIManager = {
createNode: () => ({}),
cloneNodeWithNewChildren: () => ({}),
cloneNodeWithNewChildrenAndProps: () => ({}),
cloneNodeWithNewProps: () => ({}),
createChildSet: () => ({}),
appendChild: () => {},
appendChildToSet: () => {},
completeRoot: () => {},
registerEventHandler: (fn) => {
dispatchEvent = fn;
},
setIsJSResponder: () => {},
clearIsJSResponder: () => {},
unstable_DiscreteEventPriority: 1,
unstable_ContinuousEventPriority: 2,
unstable_IdleEventPriority: 3,
unstable_getCurrentEventPriority: () => 1,
};
const privateInterface = {
ReactNativeViewConfigRegistry: {
get: () => ({}),
customBubblingEventTypes: {
topTouchStart: {
phasedRegistrationNames: { bubbled: "onTouchStart", captured: "onTouchStartCapture" },
},
topTouchMove: {
phasedRegistrationNames: { bubbled: "onTouchMove", captured: "onTouchMoveCapture" },
},
topTouchEnd: {
phasedRegistrationNames: { bubbled: "onTouchEnd", captured: "onTouchEndCapture" },
},
topTouchCancel: {
phasedRegistrationNames: { bubbled: "onTouchCancel", captured: "onTouchCancelCapture" },
},
topSelectionChange: {
phasedRegistrationNames: {
bubbled: "onSelectionChange",
captured: "onSelectionChangeCapture",
},
},
},
customDirectEventTypes: {},
},
RawEventEmitter: {
emit: (name, payload) => {
for (const fn of rawEventListeners.get(name) ?? []) {
fn(payload);
}
},
},
UIManager: {},
deepDiffer: () => false,
flattenStyle: (s) => s,
getNativeTagFromPublicInstance: () => null,
getNodeFromPublicInstance: () => null,
legacySendAccessibilityEvent: () => {},
createPublicInstance: (tag) => ({ _nativeTag: tag }),
createPublicTextInstance: () => ({}),
ReactFiberErrorDialog: { showErrorDialog: () => true },
Platform: { OS: "android" },
};
const customRequire = (id) => {
if (id === "react") {
return nodeRequire("react");
}
if (id === "scheduler") {
return nodeRequire("scheduler");
}
if (id === "react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore") {
return {};
}
if (id === "react-native/Libraries/ReactPrivate/ReactNativePrivateInterface") {
return privateInterface;
}
return nodeRequire(id);
};
const moduleObj = { exports: {} };
const sandbox = {
__DEV__: isDev,
console: {
...console,
warn: (...args) => warnings.push(args.join(" ")),
error: (...args) => warnings.push(args.join(" ")),
},
exports: moduleObj.exports,
module: moduleObj,
nativeFabricUIManager,
performance,
queueMicrotask,
require: customRequire,
setTimeout,
clearTimeout,
};
sandbox.global = sandbox;
sandbox.globalThis = sandbox;
vm.runInNewContext(code, sandbox, { filename: bundleName });
assert.equal(
typeof dispatchEvent,
"function",
`Expected ${bundleName} to register dispatchEvent`,
);
return { dispatchEvent, warnings };
}
function createHostFiber(type, props, parent = null) {
const publicInstance = { _nativeTag: Math.floor(Math.random() * 100000) + 1 };
return {
tag: 5,
type,
return: parent,
alternate: null,
stateNode: {
canonical: {
currentProps: props,
publicInstance,
publicInstanceType: 0,
},
},
};
}
function makeTouch(identifier, timestamp) {
return {
identifier,
target: 1,
pageX: 100,
pageY: 100,
locationX: 10,
locationY: 10,
timestamp,
};
}
for (const [bundleName, isDev] of [
["ReactFabric-dev.js", true],
["ReactFabric-prod.js", false],
["ReactFabric-profiling.js", false],
]) {
test(`${bundleName} reconciles trackedTouchCount from nativeEvent.touches after a dropped touch end`, () => {
const { dispatchEvent, warnings } = loadReactFabricDispatchEvent(bundleName, isDev);
const rootFiber = createHostFiber("RCTView", {});
let inputGrants = 0;
let buttonGrants = 0;
const inputFiber = createHostFiber(
"PasteTextInput",
{
onSelectionChangeShouldSetResponder: () => true,
onResponderGrant: () => {
inputGrants += 1;
},
},
rootFiber,
);
const buttonFiber = createHostFiber(
"RCTView",
{
onStartShouldSetResponder: () => true,
onResponderGrant: () => {
buttonGrants += 1;
},
},
rootFiber,
);
// 1. Unmatched touch start (e.g. Modal dismissed while touch is down or double ACTION_DOWN).
const orphanTouch = makeTouch(0, 1);
dispatchEvent(rootFiber, "topTouchStart", {
touches: [orphanTouch],
changedTouches: [orphanTouch],
});
// 2. Subsequent normal tap completes with zero remaining native touches.
const tapTouch = makeTouch(1, 2);
dispatchEvent(inputFiber, "topTouchStart", {
touches: [tapTouch],
changedTouches: [tapTouch],
});
dispatchEvent(inputFiber, "topTouchEnd", {
touches: [],
changedTouches: [tapTouch],
});
// 3. Typing triggers topSelectionChange. With trackedTouchCount reconciled to 0,
// the input must not claim responder and swallow the next tap on a sibling button.
dispatchEvent(inputFiber, "topSelectionChange", {
selection: { start: 1, end: 1 },
});
assert.equal(
inputGrants,
0,
"topSelectionChange must not claim responder when no touches are active",
);
// 4. First tap on sibling send button must be granted immediately.
const sendTouch = makeTouch(2, 3);
dispatchEvent(buttonFiber, "topTouchStart", {
touches: [sendTouch],
changedTouches: [sendTouch],
});
dispatchEvent(buttonFiber, "topTouchEnd", {
touches: [],
changedTouches: [sendTouch],
});
assert.equal(buttonGrants, 1, "first tap on sibling button must receive responder grant");
// 5. Two-finger gesture cancelled by a single synthetic topTouchCancel (e.g. RNGH pinch takeover)
// must reconcile trackedTouchCount to 0 and mark every touchBank contact inactive before
// onResponderTerminate runs.
let terminatedHistory = null;
const gestureFiber = createHostFiber(
"RCTView",
{
onStartShouldSetResponder: () => true,
onResponderTerminate: (event) => {
terminatedHistory = {
numberActiveTouches: event.touchHistory.numberActiveTouches,
activeBankIds: Array.from(event.touchHistory.touchBank, (record, index) =>
record?.touchActive ? index : -1,
).filter((index) => index >= 0),
};
},
},
rootFiber,
);
const p0 = makeTouch(3, 4);
const p1 = makeTouch(4, 5);
dispatchEvent(gestureFiber, "topTouchStart", { touches: [p0], changedTouches: [p0] });
dispatchEvent(gestureFiber, "topTouchStart", { touches: [p0, p1], changedTouches: [p1] });
dispatchEvent(gestureFiber, "topTouchCancel", { touches: [], changedTouches: [p0] });
assert.deepEqual(terminatedHistory, {
numberActiveTouches: 0,
activeBankIds: [],
});
dispatchEvent(inputFiber, "topSelectionChange", { selection: { start: 2, end: 2 } });
assert.equal(
inputGrants,
0,
"single topTouchCancel after 2-finger touch must reset trackedTouchCount to 0",
);
// 6. Multi-touch cancel emitting two topTouchCancel events with touches: [] must stay at 0 without warning.
const t0 = makeTouch(5, 6);
const t1 = makeTouch(6, 7);
dispatchEvent(rootFiber, "topTouchStart", { touches: [t0], changedTouches: [t0] });
dispatchEvent(rootFiber, "topTouchStart", { touches: [t0, t1], changedTouches: [t1] });
dispatchEvent(rootFiber, "topTouchCancel", { touches: [], changedTouches: [t0, t1] });
dispatchEvent(rootFiber, "topTouchCancel", { touches: [], changedTouches: [t0, t1] });
dispatchEvent(inputFiber, "topSelectionChange", { selection: { start: 3, end: 3 } });
assert.equal(inputGrants, 0, "multi-touch cancel must leave trackedTouchCount at 0");
assert.deepEqual(
warnings.filter((w) => w.includes("trackedTouchCount")),
[],
);
});
}
test("patched @mattermost/react-native-paste-input Android PasteTextInput does not claim responder on selection change", () => {
for (const relPath of [
"node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx",
"node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js",
"node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js",
]) {
const source = readFileSync(path.resolve(relPath), "utf8");
assert.equal(
source.includes("onSelectionChangeShouldSetResponder"),
false,
`${relPath} must not set onSelectionChangeShouldSetResponder (matches RN AndroidTextInput)`,
);
}
});