The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
Fix request storm polling and issue-list coalescing (#9190)
Dotta176645187ce7
diff --git a/packages/db/src/migrations/0141_heartbeat_runs_company_created_at_index.sql b/packages/db/src/migrations/0141_heartbeat_runs_company_created_at_index.sqlnew file mode 100644index 0000000000..12f375720e--- /dev/null+++ b/packages/db/src/migrations/0141_heartbeat_runs_company_created_at_index.sql@@ -0,0 +1,2 @@+CREATE INDEX IF NOT EXISTS "heartbeat_runs_company_created_at_desc_idx"+ ON "heartbeat_runs" USING btree ("company_id", "created_at" DESC);diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.jsonindex 3703625b25..c06cb52cf0 100644--- a/packages/db/src/migrations/meta/_journal.json+++ b/packages/db/src/migrations/meta/_journal.json@@ -974,6 +974,13 @@"when": 1783555300000,"tag": "0140_built_in_managed_resources","breakpoints": true+ },+ {+ "idx": 141,+ "version": "7",+ "when": 1783555301000,+ "tag": "0141_heartbeat_runs_company_created_at_index",+ "breakpoints": true}]}diff --git a/packages/db/src/schema/heartbeat_runs.ts b/packages/db/src/schema/heartbeat_runs.tsindex 3d0e39f671..0f3590bb0f 100644--- a/packages/db/src/schema/heartbeat_runs.ts+++ b/packages/db/src/schema/heartbeat_runs.ts@@ -84,5 +84,9 @@ export const heartbeatRuns = pgTable(table.status,table.processStartedAt,),+ companyCreatedAtDescIdx: index("heartbeat_runs_company_created_at_desc_idx").on(+ table.companyId,+ table.createdAt.desc(),+ ),}),);diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 261e6301db..911c5a7980 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -680,6 +680,7 @@ export type {ExternalObjectMentionGroup,ExternalObjectSummary,ExternalObjectSummaryItem,+ CompactIssue,Issue,IssueAssigneeAdapterOverrides,IssueBlockerDiagnosticFlag,diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.tsindex 246c30f161..c7e820f8d2 100644--- a/packages/shared/src/types/index.ts+++ b/packages/shared/src/types/index.ts@@ -311,6 +311,7 @@ export type {ExternalObjectSummaryItem,} from "./external-object.js";export type {+ CompactIssue,Issue,IssueWorkMode,IssueAssigneeAdapterOverrides,diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.tsindex 5be8c89cd0..4a792e0093 100644--- a/packages/shared/src/types/issue.ts+++ b/packages/shared/src/types/issue.ts@@ -776,6 +776,57 @@ export interface Issue {updatedAt: Date;}+export type CompactIssue = Pick<+ Issue,+ | "id"+ | "companyId"+ | "projectId"+ | "projectWorkspaceId"+ | "goalId"+ | "parentId"+ | "title"+ | "description"+ | "status"+ | "workMode"+ | "priority"+ | "assigneeAgentId"+ | "assigneeUserId"+ | "checkoutRunId"+ | "executionRunId"+ | "executionAgentNameKey"+ | "executionLockedAt"+ | "createdByAgentId"+ | "createdByUserId"+ | "issueNumber"+ | "identifier"+ | "originKind"+ | "originId"+ | "originRunId"+ | "requestDepth"+ | "billingCode"+ | "executionWorkspaceId"+ | "startedAt"+ | "completedAt"+ | "cancelledAt"+ | "createdAt"+ | "updatedAt"+> & {+ labelIds?: string[];+ labels?: IssueLabel[];+ blockedBy?: IssueRelationIssueSummary[];+ blockerAttention?: IssueBlockerAttention;+ blockedInboxAttention?: IssueBlockedInboxAttention | null;+ productivityReview?: IssueProductivityReview | null;+ scheduledRetry?: IssueScheduledRetry | null;+ liveDescendantCount?: number;+ myLastTouchAt?: Date | null;+ lastExternalCommentAt?: Date | null;+ lastActivityAt?: Date | null;+ isUnreadForMe?: boolean;+ activeRecoveryAction: IssueRecoveryAction | null;+ successfulRunHandoff: SuccessfulRunHandoffState | null;+};+/*** Where a comment's derived (non-stored-author) agent attribution came from,* in descending confidence:diff --git a/server/src/__tests__/api-compression.test.ts b/server/src/__tests__/api-compression.test.tsnew file mode 100644index 0000000000..1e727caeb3--- /dev/null+++ b/server/src/__tests__/api-compression.test.ts@@ -0,0 +1,187 @@+import express from "express";+import { createServer } from "node:http";+import { request as httpRequest } from "node:http";+import type { AddressInfo } from "node:net";+import { deflateSync, gunzipSync, inflateSync } from "node:zlib";+import { afterEach, describe, expect, it } from "vitest";+import { apiCompression } from "../middleware/api-compression.js";++type RawResponse = {+ statusCode: number;+ headers: Record<string, string | string[] | undefined>;+ body: Buffer;+};++const openServers: Array<ReturnType<typeof createServer>> = [];++afterEach(async () => {+ await Promise.all(openServers.splice(0).map((server) => new Promise<void>((resolve, reject) => {+ server.close((err) => err ? reject(err) : resolve());+ })));+});++function issueListFixture(count: number) {+ return Array.from({ length: count }, (_, index) => ({+ id: `issue-${index}`,+ companyId: "company-1",+ identifier: `PAP-${index + 1}`,+ title: `Synthetic issue list row ${index}`,+ description: "repeatable payload used to prove API compression on the hot issue-list response",+ status: index % 2 === 0 ? "in_progress" : "todo",+ priority: "medium",+ assigneeAgentId: index % 3 === 0 ? "agent-1" : null,+ assigneeUserId: null,+ parentId: null,+ projectId: "project-1",+ goalId: "goal-1",+ createdAt: "2026-07-03T00:00:00.000Z",+ updatedAt: "2026-07-03T00:00:00.000Z",+ successfulRunHandoff: null,+ activeRecoveryAction: null,+ }));+}++async function requestRaw(app: express.Express, path: string, headers: Record<string, string> = {}): Promise<RawResponse> {+ const server = createServer(app);+ openServers.push(server);++ await new Promise<void>((resolve) => {+ server.listen(0, "127.0.0.1", resolve);+ });+ const address = server.address() as AddressInfo;++ return await new Promise<RawResponse>((resolve, reject) => {+ const req = httpRequest({+ host: "127.0.0.1",+ port: address.port,+ path,+ headers,+ }, (res) => {+ const chunks: Buffer[] = [];+ res.on("data", (chunk) => {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ });+ res.on("end", () => {+ resolve({+ statusCode: res.statusCode ?? 0,+ headers: res.headers,+ body: Buffer.concat(chunks),+ });+ });+ });+ req.on("error", reject);+ req.end();+ });+}++function buildApp() {+ const app = express();+ app.use("/api", apiCompression());+ app.get("/api/companies/:companyId/issues", (_req, res) => {+ res.json(issueListFixture(500));+ });+ app.get("/api/small", (_req, res) => {+ res.json({ ok: true });+ });+ app.get("/api/encoded", (_req, res) => {+ const body = Buffer.from(JSON.stringify({ already: "encoded" }));+ res.setHeader("Content-Type", "application/json; charset=utf-8");+ res.setHeader("Content-Encoding", "deflate");+ res.end(deflateSync(body));+ });+ app.get("/api/etag", (_req, res) => {+ res.setHeader("ETag", "\"fixture-etag\"");+ res.json(issueListFixture(500));+ });+ app.get("/api/download", (_req, res) => {+ res.setHeader("Content-Type", "application/octet-stream");+ res.write("chunk-one:");+ res.end("chunk-two");+ });+ app.get("/api/json-download", (_req, res) => {+ const chunk = JSON.stringify(issueListFixture(500));+ res.setHeader("Content-Type", "application/json; charset=utf-8");+ res.setHeader("Content-Disposition", "attachment; filename=\"issues.json\"");+ res.write(chunk.slice(0, chunk.length / 2));+ res.end(chunk.slice(chunk.length / 2));+ });+ return app;+}++describe("API compression middleware", () => {+ it("compresses the hot 500-item issue-list response with gzip when the client supports it", async () => {+ const uncompressed = await requestRaw(buildApp(), "/api/companies/company-1/issues?limit=500");+ const compressed = await requestRaw(buildApp(), "/api/companies/company-1/issues?limit=500", {+ "accept-encoding": "gzip",+ });++ expect(uncompressed.statusCode).toBe(200);+ expect(compressed.statusCode).toBe(200);+ expect(compressed.headers["content-encoding"]).toBe("gzip");+ expect(compressed.headers["vary"]).toContain("Accept-Encoding");+ expect(JSON.parse(gunzipSync(compressed.body).toString("utf8"))).toHaveLength(500);+ expect(compressed.body.byteLength).toBeLessThan(uncompressed.body.byteLength / 5);+ });++ it("uses deflate when that is the supported content encoding", async () => {+ const res = await requestRaw(buildApp(), "/api/companies/company-1/issues?limit=500", {+ "accept-encoding": "deflate",+ });++ expect(res.statusCode).toBe(200);+ expect(res.headers["content-encoding"]).toBe("deflate");+ expect(JSON.parse(inflateSync(res.body).toString("utf8"))).toHaveLength(500);+ });++ it("keeps small JSON responses uncompressed for compatibility", async () => {+ const res = await requestRaw(buildApp(), "/api/small", {+ "accept-encoding": "gzip, deflate",+ });++ expect(res.statusCode).toBe(200);+ expect(res.headers["content-encoding"]).toBeUndefined();+ expect(JSON.parse(res.body.toString("utf8"))).toEqual({ ok: true });+ });++ it("does not double-compress responses that already set Content-Encoding", async () => {+ const res = await requestRaw(buildApp(), "/api/encoded", {+ "accept-encoding": "gzip, deflate",+ });++ expect(res.statusCode).toBe(200);+ expect(res.headers["content-encoding"]).toBe("deflate");+ expect(JSON.parse(inflateSync(res.body).toString("utf8"))).toEqual({ already: "encoded" });+ });++ it("weakens strong ETag validators on compressed JSON responses", async () => {+ const res = await requestRaw(buildApp(), "/api/etag", {+ "accept-encoding": "gzip",+ });++ expect(res.statusCode).toBe(200);+ expect(res.headers["content-encoding"]).toBe("gzip");+ expect(res.headers.etag).toBe("W/\"fixture-etag\"");+ expect(JSON.parse(gunzipSync(res.body).toString("utf8"))).toHaveLength(500);+ });++ it("passes streamed non-JSON responses through without compression", async () => {+ const res = await requestRaw(buildApp(), "/api/download", {+ "accept-encoding": "gzip, deflate",+ });++ expect(res.statusCode).toBe(200);+ expect(res.headers["content-encoding"]).toBeUndefined();+ expect(res.body.toString("utf8")).toBe("chunk-one:chunk-two");+ });++ it("passes streamed JSON attachment downloads through without compression", async () => {+ const res = await requestRaw(buildApp(), "/api/json-download", {+ "accept-encoding": "gzip, deflate",+ });++ expect(res.statusCode).toBe(200);+ expect(res.headers["content-disposition"]).toBe("attachment; filename=\"issues.json\"");+ expect(res.headers["content-encoding"]).toBeUndefined();+ expect(JSON.parse(res.body.toString("utf8"))).toHaveLength(500);+ });+});diff --git a/server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts b/server/src/__tests__/heartbeat-workspace-finalize-branch.test.tsindex 15871f94a6..994c9c065f 100644--- a/server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts+++ b/server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts@@ -124,6 +124,23 @@ async function waitForRuntimeStateLastRun(db: Db, agentId: string, runId: string}}+async function deleteHeartbeatRowsAfterActivityLogDrains(db: Db) {+ let lastError: unknown = null;+ for (let attempt = 0; attempt < 10; attempt += 1) {+ await db.delete(activityLog);+ await db.delete(heartbeatRunEvents);+ try {+ await db.delete(heartbeatRuns);+ await db.delete(agentWakeupRequests);+ return;+ } catch (error) {+ lastError = error;+ await new Promise((resolve) => setTimeout(resolve, 25));+ }+ }+ throw lastError;+}+function readAdapterWorkspace(input: unknown) {const context = (input as { context?: Record<string, unknown> }).context ?? {};const workspace = context.paperclipWorkspace as Record<string, unknown> | undefined;@@ -278,12 +295,8 @@ describeEmbeddedPostgres("heartbeat workspace finalization branch guard", () =>await db.delete(documents);await db.delete(agentTaskSessions);await db.delete(environmentLeases);- await db.delete(activityLog);- await db.delete(heartbeatRunEvents);- // Heartbeat finalization can emit run-linked activity after the first- // cleanup pass observes all runs as non-active.- await db.delete(activityLog);- await db.delete(heartbeatRuns);+ await db.delete(workspaceOperations);+ await deleteHeartbeatRowsAfterActivityLogDrains(db);await db.delete(issueComments);await db.delete(issues);await db.delete(projectWorkspaces);@@ -291,7 +304,6 @@ describeEmbeddedPostgres("heartbeat workspace finalization branch guard", () =>await db.delete(agentWakeupRequests);await db.delete(agentRuntimeState);await db.delete(agents);- await db.delete(workspaceOperations);await db.delete(executionWorkspaces);await db.delete(environments);await db.delete(companySkills);diff --git a/server/src/__tests__/issue-list-assignee-filter-routes.test.ts b/server/src/__tests__/issue-list-assignee-filter-routes.test.tsindex e3b119c2c6..3519986916 100644--- a/server/src/__tests__/issue-list-assignee-filter-routes.test.ts+++ b/server/src/__tests__/issue-list-assignee-filter-routes.test.ts@@ -2,13 +2,19 @@ import { randomUUID } from "node:crypto";import express from "express";import request from "supertest";import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";-import { agents, companies, companyMemberships, createDb, heartbeatRuns, issues, principalPermissionGrants } from "@paperclipai/db";+import { activityLog, agents, companies, companyMemberships, createDb, heartbeatRuns, issues, principalPermissionGrants } from "@paperclipai/db";import {getEmbeddedPostgresTestSupport,startEmbeddedPostgresTestDatabase,} from "./helpers/embedded-postgres.js";import { errorHandler } from "../middleware/index.js";-import { issueRoutes } from "../routes/issues.js";+import {+ __clearIssueListResponseCacheForTests,+ __getIssueListResponseCacheSizeForTests,+ ISSUE_LIST_SERVER_CACHE_MAX_ENTRIES,+ issueRoutes,+} from "../routes/issues.js";+import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";import { ensureHumanRoleDefaultGrants } from "../services/principal-access-compatibility.js";const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();@@ -30,8 +36,10 @@ describeEmbeddedPostgres("issue list routes assigneeAgentId filter", () => {}, 20_000);afterEach(async () => {+ __clearIssueListResponseCacheForTests();await db.delete(issues);await db.delete(heartbeatRuns);+ await db.delete(activityLog);await db.delete(agents);await db.delete(principalPermissionGrants);await db.delete(companyMemberships);@@ -42,21 +50,25 @@ describeEmbeddedPostgres("issue list routes assigneeAgentId filter", () => {await tempDb?.cleanup();});- function createApp(companyId: string) {+ function createApp(+ companyId: string,+ opts: Parameters<typeof issueRoutes>[2] = {},+ ) {const app = express();app.use(express.json());app.use((req, _res, next) => {+ const userId = req.header("x-test-user-id") ?? "cloud-user-1";(req as any).actor = {type: "board",- userId: "cloud-user-1",+ userId,companyIds: [companyId],- memberships: [{ companyId, membershipRole: "owner", status: "active" }],+ memberships: [{ companyId, membershipRole: "owner", status: "active", principalId: userId }],source: "cloud_tenant",isInstanceAdmin: false,};next();});- app.use("/api", issueRoutes(db, {} as any));+ app.use("/api", issueRoutes(db, {} as any, opts));app.use(errorHandler);return app;}@@ -66,18 +78,18 @@ describeEmbeddedPostgres("issue list routes assigneeAgentId filter", () => {return `P${randomUUID().replace(/-/g, "").slice(0, 4).toUpperCase()}`;}- async function seedCloudTenantMember(companyId: string) {+ async function seedCloudTenantMember(companyId: string, userId = "cloud-user-1") {await db.insert(companyMemberships).values({companyId,principalType: "user",- principalId: "cloud-user-1",+ principalId: userId,status: "active",membershipRole: "owner",updatedAt: new Date(),});await ensureHumanRoleDefaultGrants(db, {companyId,- principalId: "cloud-user-1",+ principalId: userId,membershipRole: "owner",grantedByUserId: null,});@@ -135,6 +147,349 @@ describeEmbeddedPostgres("issue list routes assigneeAgentId filter", () => {expect(res.body.map((issue: { id: string }) => issue.id)).toEqual([unassignedIssueId]);});+ it("returns compact issue list rows with recovery chips but without detail-only fields", async () => {+ const companyId = randomUUID();+ const ownerAgentId = randomUUID();+ const issueId = randomUUID();+ const sourceRunId = randomUUID();++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: uniqueIssuePrefix(),+ requireBoardApprovalForNewAgents: false,+ });+ await seedCloudTenantMember(companyId);+ await db.insert(agents).values({+ id: ownerAgentId,+ companyId,+ name: "Recovery owner",+ role: "engineer",+ status: "active",+ adapterType: "codex_local",+ adapterConfig: {},+ runtimeConfig: {},+ permissions: {},+ });+ await db.insert(issues).values({+ id: issueId,+ companyId,+ title: "Compact issue",+ description: "This long detail belongs on the issue detail endpoint, not the board list.",+ status: "todo",+ priority: "medium",+ billingCode: "product",+ });+ const recoveryAction = await issueRecoveryActionService(db).upsertSourceScoped({+ companyId,+ sourceIssueId: issueId,+ kind: "missing_disposition",+ ownerType: "agent",+ ownerAgentId,+ cause: "successful_run_missing_issue_disposition",+ fingerprint: "missing-disposition:compact-route",+ evidence: { sourceRunId: "run-1" },+ nextAction: "Choose a valid issue disposition.",+ wakePolicy: { type: "wake_owner" },+ });+ await db.insert(activityLog).values({+ companyId,+ actorType: "system",+ actorId: "system",+ action: "issue.successful_run_handoff_required",+ entityType: "issue",+ entityId: issueId,+ agentId: ownerAgentId,+ runId: null,+ details: {+ sourceRunId,+ detectedProgressSummary: "Implemented the requested change without choosing a disposition.",+ },+ });++ const app = createApp(companyId);+ const res = await request(app)+ .get(`/api/companies/${companyId}/issues`)+ .query({ view: "compact", limit: "20" });++ expect(res.status, JSON.stringify(res.body)).toBe(200);+ expect(res.headers.etag).toMatch(/^"compact-issues:/);+ expect(res.headers["cache-control"]).toBe("private, must-revalidate");+ expect(res.body).toHaveLength(1);+ expect(res.body[0]).toMatchObject({+ id: issueId,+ companyId,+ title: "Compact issue",+ description: "This long detail belongs on the issue detail endpoint, not the board list.",+ status: "todo",+ priority: "medium",+ billingCode: "product",+ activeRecoveryAction: {+ id: recoveryAction.id,+ sourceIssueId: issueId,+ ownerAgentId,+ kind: "missing_disposition",+ },+ successfulRunHandoff: {+ state: "required",+ required: true,+ sourceRunId,+ assigneeAgentId: ownerAgentId,+ },+ });+ expect(res.body[0]).not.toHaveProperty("workProducts");+ expect(res.body[0]).not.toHaveProperty("project");+ expect(res.body[0]).not.toHaveProperty("goal");+ });++ it("returns 304 for unchanged compact issue list ETags", async () => {+ const companyId = randomUUID();+ const issueId = randomUUID();++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: uniqueIssuePrefix(),+ requireBoardApprovalForNewAgents: false,+ });+ await seedCloudTenantMember(companyId);+ await db.insert(issues).values({+ id: issueId,+ companyId,+ title: "Cached compact issue",+ status: "todo",+ priority: "medium",+ });++ const app = createApp(companyId);+ const first = await request(app)+ .get(`/api/companies/${companyId}/issues`)+ .query({ view: "compact", limit: "20" });+ expect(first.status, JSON.stringify(first.body)).toBe(200);+ expect(first.headers.etag).toBeTruthy();++ const second = await request(app)+ .get(`/api/companies/${companyId}/issues`)+ .query({ view: "compact", limit: "20" })+ .set("If-None-Match", first.headers.etag);++ expect(second.status).toBe(304);+ expect(second.text).toBe("");+ });++ it("coalesces simultaneous identical compact issue-list requests into one service computation", async () => {+ const companyId = randomUUID();+ const issueId = randomUUID();+ let computeCount = 0;++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: uniqueIssuePrefix(),+ requireBoardApprovalForNewAgents: false,+ });+ await seedCloudTenantMember(companyId);+ await db.insert(issues).values({+ id: issueId,+ companyId,+ title: "Coalesced issue",+ status: "todo",+ priority: "medium",+ });++ const app = createApp(companyId, {+ issueListDiagnostics: {+ async onComputeStart() {+ computeCount += 1;+ await new Promise((resolve) => setTimeout(resolve, 50));+ },+ },+ });+ const responses = await Promise.all(Array.from({ length: 10 }, () =>+ request(app)+ .get(`/api/companies/${companyId}/issues`)+ .query({ view: "compact", limit: "20" })+ ));++ expect(responses.every((res) => res.status === 200)).toBe(true);+ expect(responses.map((res) => res.body.map((issue: { id: string }) => issue.id))).toEqual(+ Array.from({ length: 10 }, () => [issueId]),+ );+ expect(computeCount).toBe(1);+ expect(responses.some((res) => res.headers["x-paperclip-request-cache"] === "coalesced")).toBe(true);+ });++ it("keeps compact issue-list cache keys separated by board user identity", async () => {+ const companyId = randomUUID();+ const issueId = randomUUID();+ let computeCount = 0;++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: uniqueIssuePrefix(),+ requireBoardApprovalForNewAgents: false,+ });+ await seedCloudTenantMember(companyId, "cloud-user-1");+ await seedCloudTenantMember(companyId, "cloud-user-2");+ await db.insert(issues).values({+ id: issueId,+ companyId,+ title: "Separated issue",+ status: "todo",+ priority: "medium",+ });++ const app = createApp(companyId, {+ issueListDiagnostics: {+ async onComputeStart() {+ computeCount += 1;+ await new Promise((resolve) => setTimeout(resolve, 40));+ },+ },+ });+ const [first, second] = await Promise.all([+ request(app)+ .get(`/api/companies/${companyId}/issues`)+ .set("X-Test-User-Id", "cloud-user-1")+ .query({ view: "compact", limit: "20" }),+ request(app)+ .get(`/api/companies/${companyId}/issues`)+ .set("X-Test-User-Id", "cloud-user-2")+ .query({ view: "compact", limit: "20" }),+ ]);++ expect(first.status, JSON.stringify(first.body)).toBe(200);+ expect(second.status, JSON.stringify(second.body)).toBe(200);+ expect(computeCount).toBe(2);+ expect(first.headers["x-paperclip-request-cache"]).toBe("miss");+ expect(second.headers["x-paperclip-request-cache"]).toBe("miss");+ });++ it("serves repeated compact issue-list requests from the short server cache", async () => {+ const companyId = randomUUID();+ const issueId = randomUUID();+ let computeCount = 0;++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: uniqueIssuePrefix(),+ requireBoardApprovalForNewAgents: false,+ });+ await seedCloudTenantMember(companyId);+ await db.insert(issues).values({+ id: issueId,+ companyId,+ title: "Cached issue",+ status: "todo",+ priority: "medium",+ });++ const app = createApp(companyId, {+ issueListDiagnostics: {+ onComputeStart() {+ computeCount += 1;+ },+ },+ });+ const first = await request(app)+ .get(`/api/companies/${companyId}/issues`)+ .query({ view: "compact", limit: "20" });+ const second = await request(app)+ .get(`/api/companies/${companyId}/issues`)+ .query({ view: "compact", limit: "20" });++ expect(first.status, JSON.stringify(first.body)).toBe(200);+ expect(second.status, JSON.stringify(second.body)).toBe(200);+ expect(computeCount).toBe(1);+ expect(first.headers["x-paperclip-request-cache"]).toBe("miss");+ expect(second.headers["x-paperclip-request-cache"]).toBe("hit");+ });++ it("bounds compact issue-list server cache entries", async () => {+ const companyId = randomUUID();+ const issueId = randomUUID();++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: uniqueIssuePrefix(),+ requireBoardApprovalForNewAgents: false,+ });+ await seedCloudTenantMember(companyId);+ await db.insert(issues).values({+ id: issueId,+ companyId,+ title: "Bounded cache issue",+ status: "todo",+ priority: "medium",+ });++ const app = createApp(companyId);+ for (let index = 0; index < ISSUE_LIST_SERVER_CACHE_MAX_ENTRIES + 5; index += 1) {+ const res = await request(app)+ .get(`/api/companies/${companyId}/issues`)+ .query({ view: "compact", limit: "20", q: `cache-key-${index}` });+ expect(res.status, JSON.stringify(res.body)).toBe(200);+ }++ expect(__getIssueListResponseCacheSizeForTests()).toBe(ISSUE_LIST_SERVER_CACHE_MAX_ENTRIES);+ });++ it("logs request_storm_detected for identical in-flight compact issue-list fanout without query values", async () => {+ const companyId = randomUUID();+ const issueId = randomUUID();+ const stormEvents: unknown[] = [];++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: uniqueIssuePrefix(),+ requireBoardApprovalForNewAgents: false,+ });+ await seedCloudTenantMember(companyId);+ await db.insert(issues).values({+ id: issueId,+ companyId,+ title: "Storm issue",+ status: "todo",+ priority: "medium",+ });++ const app = createApp(companyId, {+ issueListDiagnostics: {+ async onComputeStart() {+ await new Promise((resolve) => setTimeout(resolve, 50));+ },+ onStormDetected(event) {+ stormEvents.push(event);+ },+ },+ });+ const responses = await Promise.all(Array.from({ length: 5 }, () =>+ request(app)+ .get(`/api/companies/${companyId}/issues`)+ .set("Referer", "http://localhost:3100/issues?q=do-not-log-this")+ .set("X-Paperclip-Tab-Visible", "visible")+ .query({ view: "compact", limit: "20", q: "do-not-log-this" })+ ));++ expect(responses.every((res) => res.status === 200)).toBe(true);+ expect(stormEvents).toHaveLength(1);+ expect(stormEvents[0]).toMatchObject({+ event: "request_storm_detected",+ route: "GET /api/companies/:companyId/issues",+ companyId,+ visibilityHint: "visible",+ referer: "/issues",+ });+ expect((stormEvents[0] as { queryKeys: string[] }).queryKeys).toEqual(+ expect.arrayContaining(["limit", "q", "view"]),+ );+ expect(JSON.stringify(stormEvents[0])).not.toContain("do-not-log-this");+ });+it("keeps UUID assignee filtering behavior unchanged", async () => {const companyId = randomUUID();const assigneeAgentId = randomUUID();diff --git a/server/src/__tests__/low-trust-red-team-routes.test.ts b/server/src/__tests__/low-trust-red-team-routes.test.tsindex f8fe6b53e8..53d701af99 100644--- a/server/src/__tests__/low-trust-red-team-routes.test.ts+++ b/server/src/__tests__/low-trust-red-team-routes.test.ts@@ -97,6 +97,21 @@ async function deleteHeartbeatRunsAndWakeupsAfterActivityLogDrains(db: Db) {}}+async function deleteCompanySkillsAfterLateHeartbeatWritesDrain(db: Db) {+ let lastError: unknown = null;+ for (let attempt = 0; attempt < 10; attempt += 1) {+ await db.delete(companySkills);+ try {+ await db.delete(companies);+ return;+ } catch (error) {+ lastError = error;+ await new Promise((resolve) => setTimeout(resolve, 25));+ }+ }+ throw lastError;+}+function expectNoCanary(value: unknown, ...markers: string[]) {const serialized = JSON.stringify(value);for (const marker of markers) expect(serialized).not.toContain(marker);@@ -660,8 +675,7 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>await db.delete(companyMemberships);await db.delete(agents);await db.delete(projects);- await db.delete(companySkills);- await db.delete(companies);+ await deleteCompanySkillsAfterLateHeartbeatWritesDrain(db);});afterAll(async () => {@@ -1198,6 +1212,11 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>});expectNoCanary(bogusRunContext.body, fixture.canaries.raw);+ await db.update(heartbeatRuns).set({+ status: "succeeded",+ finishedAt: new Date(),+ updatedAt: new Date(),+ }).where(eq(heartbeatRuns.id, fixture.runs.standard.id));await db.update(agents).set({status: "idle",adapterType: "openclaw_gateway",@@ -1211,6 +1230,7 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>},waitTimeoutMs: 2_000,},+ runtimeConfig: { heartbeat: { wakeOnDemand: true } },}).where(eq(agents.id, fixture.agents.standard.id));await db.update(heartbeatRuns).set({status: "succeeded",diff --git a/server/src/app.ts b/server/src/app.tsindex 566baa7104..e5c266f469 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -71,6 +71,7 @@ import type { BetterAuthSessionResult } from "./auth/better-auth.js";import { createCachedViteHtmlRenderer } from "./vite-html-renderer.js";import { DEFAULT_JSON_BODY_LIMIT, PORTABLE_JSON_BODY_LIMIT } from "./http/body-limits.js";import { COMPANY_IMPORT_API_PATH } from "./routes/company-import-paths.js";+import { apiCompression } from "./middleware/api-compression.js";type UiMode = "none" | "static" | "vite-dev";const FEEDBACK_EXPORT_FLUSH_INTERVAL_MS = 5_000;@@ -179,6 +180,7 @@ export async function createApp(limit: DEFAULT_JSON_BODY_LIMIT,verify: captureRawBody,}));+ app.use("/api", apiCompression());app.use(httpLogger);const privateHostnameGateEnabled = shouldEnablePrivateHostnameGuard({deploymentMode: opts.deploymentMode,diff --git a/server/src/middleware/api-compression.ts b/server/src/middleware/api-compression.tsnew file mode 100644index 0000000000..58dfeb33c2--- /dev/null+++ b/server/src/middleware/api-compression.ts@@ -0,0 +1,223 @@+import type { RequestHandler } from "express";+import { promisify } from "node:util";+import { deflate, gzip } from "node:zlib";++export const API_COMPRESSION_THRESHOLD_BYTES = 1024;++const gzipAsync = promisify(gzip);+const deflateAsync = promisify(deflate);++type SupportedEncoding = "gzip" | "deflate";++type ApiCompressionOptions = {+ thresholdBytes?: number;+};++type EncodingPreference = {+ encoding: string;+ q: number;+};++function parseAcceptEncoding(value: string | string[] | undefined): EncodingPreference[] {+ const raw = Array.isArray(value) ? value.join(",") : value;+ if (!raw) return [];++ return raw+ .split(",")+ .map((part) => {+ const [encodingPart, ...paramParts] = part.trim().split(";");+ const encoding = encodingPart?.trim().toLowerCase() ?? "";+ const qParam = paramParts+ .map((param) => param.trim())+ .find((param) => param.toLowerCase().startsWith("q="));+ const parsedQ = qParam ? Number(qParam.slice(2)) : 1;+ const q = Number.isFinite(parsedQ) ? parsedQ : 0;+ return { encoding, q };+ })+ .filter((entry) => entry.encoding.length > 0);+}++function selectEncoding(value: string | string[] | undefined): SupportedEncoding | null {+ const preferences = parseAcceptEncoding(value).filter((entry) => entry.q > 0);+ const findQ = (encoding: SupportedEncoding) =>+ preferences.find((entry) => entry.encoding === encoding)?.q ??+ preferences.find((entry) => entry.encoding === "*")?.q ??+ 0;++ const gzipQ = findQ("gzip");+ const deflateQ = findQ("deflate");+ if (gzipQ <= 0 && deflateQ <= 0) return null;+ return gzipQ >= deflateQ ? "gzip" : "deflate";+}++function isJsonContentType(value: unknown): boolean {+ const contentType = String(value ?? "").toLowerCase();+ return contentType.includes("application/json") || contentType.includes("+json");+}++function shouldSkipForCacheControl(value: unknown): boolean {+ return /\bno-transform\b/i.test(String(value ?? ""));+}++function shouldSkipForStreamedResponse(res: Parameters<RequestHandler>[1]): boolean {+ return (+ res.hasHeader("Content-Disposition") ||+ res.hasHeader("Accept-Ranges") ||+ res.hasHeader("Content-Range")+ );+}++function statusAllowsBody(statusCode: number): boolean {+ return statusCode !== 204 && statusCode !== 304 && statusCode >= 200;+}++function shouldPassthroughWrite(res: Parameters<RequestHandler>[1]): boolean {+ const contentType = res.getHeader("Content-Type");+ const alreadyEncoded = res.hasHeader("Content-Encoding") && String(res.getHeader("Content-Encoding")).toLowerCase() !== "identity";+ return (+ alreadyEncoded ||+ !statusAllowsBody(res.statusCode) ||+ shouldSkipForCacheControl(res.getHeader("Cache-Control")) ||+ shouldSkipForStreamedResponse(res) ||+ contentType === undefined ||+ !isJsonContentType(contentType)+ );+}++function weakenStrongEtag(res: Parameters<RequestHandler>[1]): void {+ const etag = res.getHeader("ETag");+ if (etag === undefined) return;++ const weaken = (value: string) => /^W\//i.test(value) ? value : `W/${value}`;+ if (Array.isArray(etag)) {+ res.setHeader("ETag", etag.map((value) => weaken(String(value))));+ return;+ }++ res.setHeader("ETag", weaken(String(etag)));+}++function normalizeEndArgs(args: unknown[]): {+ chunk: unknown;+ encoding: BufferEncoding | undefined;+ callback: (() => void) | undefined;+} {+ const [chunk, encodingOrCallback, callback] = args;+ return {+ chunk,+ encoding: typeof encodingOrCallback === "string" ? encodingOrCallback as BufferEncoding : undefined,+ callback:+ typeof encodingOrCallback === "function"+ ? encodingOrCallback as () => void+ : typeof callback === "function"+ ? callback as () => void+ : undefined,+ };+}++export function apiCompression(options: ApiCompressionOptions = {}): RequestHandler {+ const thresholdBytes = options.thresholdBytes ?? API_COMPRESSION_THRESHOLD_BYTES;++ return (req, res, next) => {+ const selectedEncoding = selectEncoding(req.headers["accept-encoding"]);+ if (!selectedEncoding || req.method === "HEAD") {+ next();+ return;+ }++ const chunks: Buffer[] = [];+ const writeCallbacks: Array<() => void> = [];+ let passthrough = false;++ const originalWrite = res.write.bind(res);+ const originalEnd = res.end.bind(res);+ const originalFlushHeaders = res.flushHeaders?.bind(res);++ const restore = () => {+ res.write = originalWrite as typeof res.write;+ res.end = originalEnd as typeof res.end;+ if (originalFlushHeaders) {+ res.flushHeaders = originalFlushHeaders as typeof res.flushHeaders;+ }+ };++ const beginPassthrough = () => {+ if (passthrough) return;+ passthrough = true;+ restore();+ for (const buffered of chunks.splice(0)) {+ originalWrite(buffered);+ }+ for (const writeCallback of writeCallbacks.splice(0)) writeCallback();+ };++ res.write = ((chunk: unknown, encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void), callback?: (error?: Error | null) => void) => {+ if (passthrough) {+ return originalWrite(chunk as never, encodingOrCallback as never, callback as never);+ }+ if (shouldPassthroughWrite(res)) {+ beginPassthrough();+ return originalWrite(chunk as never, encodingOrCallback as never, callback as never);+ }+ if (chunk !== undefined) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), typeof encodingOrCallback === "string" ? encodingOrCallback : undefined));+ }+ const writeCallback = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;+ if (writeCallback) writeCallbacks.push(() => writeCallback(null));+ return true;+ }) as typeof res.write;++ res.end = ((...args: unknown[]) => {+ restore();+ const { chunk, encoding, callback } = normalizeEndArgs(args);+ if (chunk !== undefined) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), encoding));+ }++ const body = Buffer.concat(chunks);+ const alreadyEncoded = res.hasHeader("Content-Encoding") && String(res.getHeader("Content-Encoding")).toLowerCase() !== "identity";+ const shouldCompress =+ !passthrough &&+ !alreadyEncoded &&+ statusAllowsBody(res.statusCode) &&+ body.length >= thresholdBytes &&+ isJsonContentType(res.getHeader("Content-Type")) &&+ !shouldSkipForCacheControl(res.getHeader("Cache-Control")) &&+ !shouldSkipForStreamedResponse(res);++ if (!shouldCompress) {+ const result = originalEnd(body, callback);+ for (const writeCallback of writeCallbacks) writeCallback();+ return result;+ }++ void (async () => {+ try {+ const compressed = selectedEncoding === "gzip"+ ? await gzipAsync(body)+ : await deflateAsync(body);+ res.vary("Accept-Encoding");+ res.setHeader("Content-Encoding", selectedEncoding);+ res.setHeader("Content-Length", String(compressed.length));+ weakenStrongEtag(res);+ res.removeHeader("Content-MD5");+ originalEnd(compressed, callback);+ for (const writeCallback of writeCallbacks) writeCallback();+ } catch (error) {+ res.destroy(error instanceof Error ? error : new Error(String(error)));+ }+ })();+ return res;+ }) as typeof res.end;++ if (originalFlushHeaders) {+ res.flushHeaders = (() => {+ passthrough = true;+ restore();+ return originalFlushHeaders();+ }) as typeof res.flushHeaders;+ }++ next();+ };+}diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.tsindex a9ba840c58..7d67db4734 100644--- a/server/src/routes/issues.ts+++ b/server/src/routes/issues.ts@@ -1,4 +1,4 @@-import { randomUUID } from "node:crypto";+import { createHash, randomUUID } from "node:crypto";import { Router, type Request, type Response } from "express";import multer from "multer";import { z } from "zod";@@ -61,6 +61,7 @@ import {isClosedIsolatedExecutionWorkspace,isUuidLike,normalizeIssueIdentifier as normalizeIssueReferenceIdentifier,+ type CompactIssue,type CompanySearchQuery,type CompanySearchResponse,type ExecutionWorkspace,@@ -105,6 +106,7 @@ import {ISSUE_LIST_MAX_LIMIT,issueReferenceService,issueService,+ type IssueFilters,clampIssueListLimit,documentService,documentAnnotationService,@@ -2011,6 +2013,420 @@ class AutoApprovalIssueMissingError extends Error {}}+function toCompactIssue(issue: any): CompactIssue {+ return {+ id: issue.id,+ companyId: issue.companyId,+ projectId: issue.projectId,+ projectWorkspaceId: issue.projectWorkspaceId,+ goalId: issue.goalId,+ parentId: issue.parentId,+ title: issue.title,+ description: issue.description,+ status: issue.status,+ workMode: issue.workMode,+ priority: issue.priority,+ assigneeAgentId: issue.assigneeAgentId,+ assigneeUserId: issue.assigneeUserId,+ checkoutRunId: issue.checkoutRunId,+ executionRunId: issue.executionRunId,+ executionAgentNameKey: issue.executionAgentNameKey,+ executionLockedAt: issue.executionLockedAt,+ createdByAgentId: issue.createdByAgentId,+ createdByUserId: issue.createdByUserId,+ issueNumber: issue.issueNumber,+ identifier: issue.identifier,+ originKind: issue.originKind,+ originId: issue.originId,+ originRunId: issue.originRunId,+ requestDepth: issue.requestDepth,+ billingCode: issue.billingCode,+ executionWorkspaceId: issue.executionWorkspaceId,+ startedAt: issue.startedAt,+ completedAt: issue.completedAt,+ cancelledAt: issue.cancelledAt,+ createdAt: issue.createdAt,+ updatedAt: issue.updatedAt,+ ...(issue.labelIds ? { labelIds: issue.labelIds } : {}),+ ...(issue.labels ? { labels: issue.labels } : {}),+ ...(issue.blockedBy ? { blockedBy: issue.blockedBy } : {}),+ ...(issue.blockerAttention ? { blockerAttention: issue.blockerAttention } : {}),+ ...(issue.blockedInboxAttention !== undefined ? { blockedInboxAttention: issue.blockedInboxAttention } : {}),+ ...(issue.productivityReview ? { productivityReview: issue.productivityReview } : {}),+ ...(issue.scheduledRetry ? { scheduledRetry: issue.scheduledRetry } : {}),+ ...(issue.liveDescendantCount !== undefined ? { liveDescendantCount: issue.liveDescendantCount } : {}),+ ...(issue.myLastTouchAt !== undefined ? { myLastTouchAt: issue.myLastTouchAt } : {}),+ ...(issue.lastExternalCommentAt !== undefined ? { lastExternalCommentAt: issue.lastExternalCommentAt } : {}),+ ...(issue.lastActivityAt !== undefined ? { lastActivityAt: issue.lastActivityAt } : {}),+ ...(issue.isUnreadForMe !== undefined ? { isUnreadForMe: issue.isUnreadForMe } : {}),+ activeRecoveryAction: issue.activeRecoveryAction ?? null,+ successfulRunHandoff: issue.successfulRunHandoff ?? null,+ };+}++function compactIssueListEtag(issues: CompactIssue[]): string {+ const hash = createHash("sha256")+ .update(JSON.stringify(issues))+ .digest("base64url");+ return `"compact-issues:${hash}"`;+}++function requestMatchesEtag(ifNoneMatchHeader: string | undefined, etag: string): boolean {+ if (!ifNoneMatchHeader) return false;+ return ifNoneMatchHeader+ .split(",")+ .map((value) => value.trim())+ .some((value) => value === "*" || value === etag || value === `W/${etag}`);+}++const ISSUE_LIST_SERVER_CACHE_TTL_MS = 2_000;+const ISSUE_LIST_SERVER_CACHE_STALE_MS = 5_000;+export const ISSUE_LIST_SERVER_CACHE_MAX_ENTRIES = 256;+const ISSUE_LIST_STORM_WINDOW_MS = 500;+const ISSUE_LIST_STORM_THRESHOLD = 4;+const ISSUE_LIST_MAX_ACTOR_CLIENT_INFLIGHT = 8;++type IssueListPreparedResponse =+ | {+ kind: "compact";+ body: CompactIssue[];+ etag: string;+ cacheControl: string;+ }+ | {+ kind: "full";+ body: unknown[];+ };++type IssueListCacheStatus = "miss" | "hit" | "coalesced" | "stale" | "retry";++type IssueListStormEvent = {+ event: "request_storm_detected";+ route: string;+ companyId: string;+ actorType: string;+ actorIdentityHash: string;+ clientHash: string;+ cacheKeyHash: string;+ queryKeys: string[];+ identicalInFlightCount: number;+ windowMs: number;+ referer: string | null;+ visibilityHint: string | null;+};++type IssueListDiagnostics = {+ onComputeStart?: (context: { companyId: string; cacheKeyHash: string }) => void | Promise<void>;+ onStormDetected?: (event: IssueListStormEvent) => void;+};++type IssueListCacheEntry = {+ response: IssueListPreparedResponse;+ expiresAt: number;+ staleUntil: number;+};++type IssueListInflightEntry = {+ promise: Promise<IssueListPreparedResponse>;+ startedAt: number;+ waiterCount: number;+ stormLogged: boolean;+};++const issueListResponseCache = new Map<string, IssueListCacheEntry>();+const issueListInflight = new Map<string, IssueListInflightEntry>();+const issueListActorClientInflight = new Map<string, number>();++export function __getIssueListResponseCacheSizeForTests() {+ return issueListResponseCache.size;+}++export function __clearIssueListResponseCacheForTests() {+ issueListResponseCache.clear();+}++function shortHash(value: string): string {+ return createHash("sha256").update(value).digest("base64url").slice(0, 16);+}++function stableJson(value: unknown): string {+ if (value === null || typeof value !== "object") return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;+ const record = value as Record<string, unknown>;+ return `{${Object.keys(record)+ .sort()+ .filter((key) => record[key] !== undefined)+ .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`)+ .join(",")}}`;+}++function normalizeIssueListCacheValue(value: unknown): unknown {+ if (value === undefined) return undefined;+ if (value === null) return null;+ if (Array.isArray(value)) {+ return value.map(normalizeIssueListCacheValue).sort((a, b) => stableJson(a).localeCompare(stableJson(b)));+ }+ if (typeof value === "object") {+ const normalized: Record<string, unknown> = {};+ for (const [key, nestedValue] of Object.entries(value as Record<string, unknown>)) {+ const next = normalizeIssueListCacheValue(nestedValue);+ if (next !== undefined) normalized[key] = next;+ }+ return normalized;+ }+ return value;+}++function issueListActorIdentity(req: Request, companyId: string) {+ if (req.actor.type === "agent") {+ const onBehalfMembership = req.actor.onBehalfOfUserId+ ? req.actor.onBehalfOfMemberships?.find((membership) => membership.companyId === companyId) ?? null+ : null;+ const key = [+ "agent",+ companyId,+ req.actor.agentId ?? "unknown-agent",+ req.actor.keyId ?? req.actor.source ?? "agent-auth",+ req.actor.onBehalfOfUserId ?? "no-responsible-user",+ onBehalfMembership?.status ?? "no-responsible-user-status",+ onBehalfMembership?.membershipRole ?? "no-responsible-user-role",+ ].join(":");+ return { actorType: "agent", key, hash: shortHash(key) };+ }++ if (req.actor.type === "board") {+ const sessionPart = req.actor.source === "session"+ ? `cookie:${shortHash(String(req.headers.cookie ?? "no-cookie"))}`+ : req.actor.keyId ?? req.actor.source ?? "board";+ const key = [+ "board",+ companyId,+ req.actor.source ?? "board",+ req.actor.userId ?? "unknown-user",+ sessionPart,+ ].join(":");+ return { actorType: "board", key, hash: shortHash(key) };+ }++ const key = ["none", companyId, req.actor.source ?? "none"].join(":");+ return { actorType: "none", key, hash: shortHash(key) };+}++function issueListClientIdentity(req: Request) {+ const forwardedFor = Array.isArray(req.headers["x-forwarded-for"])+ ? req.headers["x-forwarded-for"][0]+ : req.headers["x-forwarded-for"];+ const client = [+ String(forwardedFor ?? req.ip ?? "unknown-ip").split(",")[0]?.trim() ?? "unknown-ip",+ req.header("user-agent") ?? "unknown-agent",+ ].join(":");+ return { key: client, hash: shortHash(client) };+}++function safeRefererPath(req: Request): string | null {+ const referer = req.header("referer");+ if (!referer) return null;+ try {+ return new URL(referer).pathname;+ } catch {+ return referer.split("?")[0]?.slice(0, 160) ?? null;+ }+}++function issueListRequestKey(input: {+ req: Request;+ companyId: string;+ normalizedQuery: Record<string, unknown>;+}) {+ const route = "GET /api/companies/:companyId/issues";+ const actor = issueListActorIdentity(input.req, input.companyId);+ const client = issueListClientIdentity(input.req);+ const normalizedQuery = normalizeIssueListCacheValue(input.normalizedQuery) as Record<string, unknown>;+ const queryKeys = Object.keys(normalizedQuery).sort();+ const key = stableJson({+ actor: actor.key,+ companyId: input.companyId,+ query: normalizedQuery,+ route,+ });+ return {+ actor,+ client,+ key,+ keyHash: shortHash(key),+ queryKeys,+ route,+ };+}++function pruneIssueListResponseCache(now: number) {+ for (const [key, entry] of issueListResponseCache) {+ if (entry.staleUntil <= now) issueListResponseCache.delete(key);+ }+}++function touchIssueListResponseCacheEntry(key: string, entry: IssueListCacheEntry) {+ issueListResponseCache.delete(key);+ issueListResponseCache.set(key, entry);+}++function trimIssueListResponseCache() {+ while (issueListResponseCache.size > ISSUE_LIST_SERVER_CACHE_MAX_ENTRIES) {+ const oldestKey = issueListResponseCache.keys().next().value as string | undefined;+ if (oldestKey === undefined) return;+ issueListResponseCache.delete(oldestKey);+ }+}++function setIssueListResponseCacheEntry(key: string, entry: IssueListCacheEntry) {+ touchIssueListResponseCacheEntry(key, entry);+ trimIssueListResponseCache();+}++function decrementIssueListActorClientInflight(actorClientKey: string) {+ const next = (issueListActorClientInflight.get(actorClientKey) ?? 1) - 1;+ if (next <= 0) issueListActorClientInflight.delete(actorClientKey);+ else issueListActorClientInflight.set(actorClientKey, next);+}++async function coordinateIssueListGet(input: {+ req: Request;+ companyId: string;+ requestKey: ReturnType<typeof issueListRequestKey>;+ allowTtlCache: boolean;+ diagnostics?: IssueListDiagnostics;+ compute: () => Promise<IssueListPreparedResponse>;+}): Promise<{+ response: IssueListPreparedResponse | null;+ cacheStatus: IssueListCacheStatus;+ identicalInFlightCount: number;+ retryAfterSeconds?: number;+}> {+ const now = Date.now();+ pruneIssueListResponseCache(now);++ const cached = input.allowTtlCache ? issueListResponseCache.get(input.requestKey.key) : undefined;+ if (cached && cached.expiresAt > now) {+ touchIssueListResponseCacheEntry(input.requestKey.key, cached);+ return { response: cached.response, cacheStatus: "hit", identicalInFlightCount: 0 };+ }++ const existing = issueListInflight.get(input.requestKey.key);+ if (existing) {+ existing.waiterCount += 1;+ const identicalInFlightCount = existing.waiterCount + 1;+ if (+ !existing.stormLogged &&+ identicalInFlightCount >= ISSUE_LIST_STORM_THRESHOLD &&+ now - existing.startedAt <= ISSUE_LIST_STORM_WINDOW_MS+ ) {+ existing.stormLogged = true;+ const event: IssueListStormEvent = {+ event: "request_storm_detected",+ route: input.requestKey.route,+ companyId: input.companyId,+ actorType: input.requestKey.actor.actorType,+ actorIdentityHash: input.requestKey.actor.hash,+ clientHash: input.requestKey.client.hash,+ cacheKeyHash: input.requestKey.keyHash,+ queryKeys: input.requestKey.queryKeys,+ identicalInFlightCount,+ windowMs: now - existing.startedAt,+ referer: safeRefererPath(input.req),+ visibilityHint: input.req.header("x-paperclip-tab-visible") ?? null,+ };+ logger.warn(event, "request_storm_detected");+ input.diagnostics?.onStormDetected?.(event);+ }+ const response = await existing.promise;+ return { response, cacheStatus: "coalesced", identicalInFlightCount };+ }++ const actorClientKey = `${input.requestKey.actor.key}:${input.requestKey.client.key}`;+ const actorClientInflight = issueListActorClientInflight.get(actorClientKey) ?? 0;+ if (actorClientInflight >= ISSUE_LIST_MAX_ACTOR_CLIENT_INFLIGHT) {+ if (cached && cached.staleUntil > now) {+ touchIssueListResponseCacheEntry(input.requestKey.key, cached);+ return { response: cached.response, cacheStatus: "stale", identicalInFlightCount: 0 };+ }+ return { response: null, cacheStatus: "retry", identicalInFlightCount: 0, retryAfterSeconds: 1 };+ }++ issueListActorClientInflight.set(actorClientKey, actorClientInflight + 1);+ const promise = (async () => {+ await input.diagnostics?.onComputeStart?.({+ companyId: input.companyId,+ cacheKeyHash: input.requestKey.keyHash,+ });+ return input.compute();+ })();+ const inflightEntry: IssueListInflightEntry = {+ promise,+ startedAt: now,+ waiterCount: 0,+ stormLogged: false,+ };+ issueListInflight.set(input.requestKey.key, inflightEntry);++ try {+ const response = await promise;+ if (input.allowTtlCache) {+ setIssueListResponseCacheEntry(input.requestKey.key, {+ response,+ expiresAt: Date.now() + ISSUE_LIST_SERVER_CACHE_TTL_MS,+ staleUntil: Date.now() + ISSUE_LIST_SERVER_CACHE_STALE_MS,+ });+ }+ return { response, cacheStatus: "miss", identicalInFlightCount: 1 };+ } finally {+ if (issueListInflight.get(input.requestKey.key) === inflightEntry) {+ issueListInflight.delete(input.requestKey.key);+ }+ decrementIssueListActorClientInflight(actorClientKey);+ }+}++function estimatedJsonBytes(value: unknown): number {+ return Buffer.byteLength(JSON.stringify(value), "utf8");+}++function logIssueListRequest(input: {+ req: Request;+ res: Response;+ companyId: string;+ requestKey: ReturnType<typeof issueListRequestKey>;+ startedAt: number;+ cacheStatus: IssueListCacheStatus;+ bodyBytes: number;+ etagOutcome: "none" | "fresh" | "not_modified";+ identicalInFlightCount: number;+}) {+ input.res.once("finish", () => {+ const contentEncoding = input.res.getHeader("content-encoding");+ const contentLength = Number(input.res.getHeader("content-length"));+ logger.debug({+ event: "safe_get_request_observed",+ route: input.requestKey.route,+ companyId: input.companyId,+ actorType: input.requestKey.actor.actorType,+ actorIdentityHash: input.requestKey.actor.hash,+ clientHash: input.requestKey.client.hash,+ cacheKeyHash: input.requestKey.keyHash,+ queryKeys: input.requestKey.queryKeys,+ requestCount: input.identicalInFlightCount,+ durationMs: Date.now() - input.startedAt,+ statusCode: input.res.statusCode,+ responseBytes: input.bodyBytes,+ compressedBytes: contentEncoding && Number.isFinite(contentLength) ? contentLength : null,+ contentEncoding: contentEncoding ? String(contentEncoding) : null,+ cacheStatus: input.cacheStatus,+ etagOutcome: input.etagOutcome,+ referer: safeRefererPath(input.req),+ visibilityHint: input.req.header("x-paperclip-tab-visible") ?? null,+ }, "safe authenticated GET observed");+ });+}+export function issueRoutes(db: Db,storage: StorageService,@@ -2027,6 +2443,7 @@ export function issueRoutes(searchRateLimiter?: CompanySearchRateLimiter;pluginWorkerManager?: PluginWorkerManager;taskWatchdogEnqueueWakeup?: TaskWatchdogServiceDeps["enqueueWakeup"] | null;+ issueListDiagnostics?: IssueListDiagnostics;} = {},) {const router = Router();@@ -4032,6 +4449,7 @@ export function issueRoutes(});router.get("/companies/:companyId/issues", async (req, res) => {+ const startedAt = Date.now();const companyId = req.params.companyId as string;assertCompanyAccess(req, companyId);if (isTaskBridgeKeyActor(req)) {@@ -4070,6 +4488,8 @@ export function issueRoutes(const attention = req.query.attention as string | undefined;const sortField = req.query.sortField as string | undefined;const sortDir = req.query.sortDir as string | undefined;+ const view = req.query.view as string | undefined;+ const compactView = view === "compact";const hasPlanDocument = parseOptionalBooleanQuery(req.query.hasPlanDocument);const includeLiveDescendantSummary = parseOptionalBooleanQuery(req.query.includeLiveDescendantSummary);const assigneeAgentFilterRaw = req.query.assigneeAgentId;@@ -4095,6 +4515,10 @@ export function issueRoutes(res.status(400).json({ error: "attention must be 'blocked' when provided" });return;}+ if (view !== undefined && view !== "compact") {+ res.status(400).json({ error: "view must be 'compact' when provided" });+ return;+ }if (rawLimit !== undefined && (parsedLimit === null || !Number.isInteger(parsedLimit) || parsedLimit <= 0)) {res.status(400).json({ error: `limit must be a positive integer up to ${ISSUE_LIST_MAX_LIMIT}` });return;@@ -4138,7 +4562,7 @@ export function issueRoutes(}const offset = parsedOffset ?? 0;- const rawResult = await svc.list(companyId, {+ const listFilters: IssueFilters = {attention: attention === "blocked" ? "blocked" : undefined,status: req.query.status as string | string[] | undefined,assigneeAgentId,@@ -4172,33 +4596,143 @@ export function issueRoutes(offset,sortField: sortField === "updated" ? "updated" : undefined,sortDir: sortDir === "asc" || sortDir === "desc" ? sortDir : undefined,+ };+ const requestKey = issueListRequestKey({+ req,+ companyId,+ normalizedQuery: {+ ...listFilters,+ view: compactView ? "compact" : undefined,+ },});- const result = await actorCanReadCompanyScope(req, companyId)- ? rawResult- : await filterIssuesForActor(req, rawResult);- const issueIds = result.map((issue) => issue.id);- const [handoffStates, recoveryActionByIssue] = await Promise.all([- listSuccessfulRunHandoffStates(db, companyId, issueIds),- recoveryActionsSvc.listActiveForIssues(companyId, issueIds),- ]);- const actor = getActorInfo(req);- await Promise.all(result.map(async (issue) => {- const activeRecoveryAction = recoveryActionByIssue.get(issue.id) ?? null;- if (!activeRecoveryAction) return;- const revalidated = await revalidateActiveSourceRecoveryForRead({- issue,- trigger: "read_projection",- actor,- activeRecoveryAction,+ const coordinated = await coordinateIssueListGet({+ req,+ companyId,+ requestKey,+ allowTtlCache: compactView,+ diagnostics: opts.issueListDiagnostics,+ compute: async () => {+ const rawResult = await svc.list(companyId, listFilters);+ const result = await actorCanReadCompanyScope(req, companyId)+ ? rawResult+ : await filterIssuesForActor(req, rawResult);+ const issueIds = result.map((issue) => issue.id);+ if (compactView) {+ const [handoffStates, recoveryActionByIssue] = await Promise.all([+ listSuccessfulRunHandoffStates(db, companyId, issueIds),+ recoveryActionsSvc.listActiveForIssues(companyId, issueIds),+ ]);+ const actor = getActorInfo(req);+ await Promise.all(result.map(async (issue) => {+ const activeRecoveryAction = recoveryActionByIssue.get(issue.id) ?? null;+ if (!activeRecoveryAction) return;+ const revalidated = await revalidateActiveSourceRecoveryForRead({+ issue,+ trigger: "read_projection",+ actor,+ activeRecoveryAction,+ });+ if (revalidated) recoveryActionByIssue.set(issue.id, revalidated);+ else recoveryActionByIssue.delete(issue.id);+ }));+ const compactResult = result.map((issue) =>+ toCompactIssue({+ ...issue,+ activeRecoveryAction: recoveryActionByIssue.get(issue.id) ?? null,+ successfulRunHandoff: handoffStates.get(issue.id) ?? null,+ }));+ return {+ kind: "compact",+ body: compactResult,+ etag: compactIssueListEtag(compactResult),+ cacheControl: "private, must-revalidate",+ };+ }+ const [handoffStates, recoveryActionByIssue] = await Promise.all([+ listSuccessfulRunHandoffStates(db, companyId, issueIds),+ recoveryActionsSvc.listActiveForIssues(companyId, issueIds),+ ]);+ const actor = getActorInfo(req);+ await Promise.all(result.map(async (issue) => {+ const activeRecoveryAction = recoveryActionByIssue.get(issue.id) ?? null;+ if (!activeRecoveryAction) return;+ const revalidated = await revalidateActiveSourceRecoveryForRead({+ issue,+ trigger: "read_projection",+ actor,+ activeRecoveryAction,+ });+ if (revalidated) recoveryActionByIssue.set(issue.id, revalidated);+ else recoveryActionByIssue.delete(issue.id);+ }));+ return {+ kind: "full",+ body: result.map((issue) => ({+ ...issue,+ successfulRunHandoff: handoffStates.get(issue.id) ?? null,+ activeRecoveryAction: recoveryActionByIssue.get(issue.id) ?? null,+ })),+ };+ },+ });++ res.setHeader("X-Paperclip-Request-Cache", coordinated.cacheStatus);+ if (!coordinated.response) {+ const body = {+ error: "Too many concurrent issue-list requests for this actor/client",+ retryAfterSeconds: coordinated.retryAfterSeconds ?? 1,+ };+ res.setHeader("Retry-After", String(body.retryAfterSeconds));+ logIssueListRequest({+ req,+ res,+ companyId,+ requestKey,+ startedAt,+ cacheStatus: "retry",+ bodyBytes: estimatedJsonBytes(body),+ etagOutcome: "none",+ identicalInFlightCount: coordinated.identicalInFlightCount,});- if (revalidated) recoveryActionByIssue.set(issue.id, revalidated);- else recoveryActionByIssue.delete(issue.id);- }));- res.json(result.map((issue) => ({- ...issue,- successfulRunHandoff: handoffStates.get(issue.id) ?? null,- activeRecoveryAction: recoveryActionByIssue.get(issue.id) ?? null,- })));+ res.status(429).json(body);+ return;+ }++ if (coordinated.response.kind === "compact") {+ res.setHeader("Cache-Control", coordinated.response.cacheControl);+ res.setHeader("ETag", coordinated.response.etag);+ const etagMatched = requestMatchesEtag(req.header("if-none-match"), coordinated.response.etag);+ logIssueListRequest({+ req,+ res,+ companyId,+ requestKey,+ startedAt,+ cacheStatus: coordinated.cacheStatus,+ bodyBytes: etagMatched ? 0 : estimatedJsonBytes(coordinated.response.body),+ etagOutcome: etagMatched ? "not_modified" : "fresh",+ identicalInFlightCount: coordinated.identicalInFlightCount,+ });+ if (etagMatched) {+ res.status(304).end();+ return;+ }+ res.json(coordinated.response.body);+ return;+ }++ logIssueListRequest({+ req,+ res,+ companyId,+ requestKey,+ startedAt,+ cacheStatus: coordinated.cacheStatus,+ bodyBytes: estimatedJsonBytes(coordinated.response.body),+ etagOutcome: "none",+ identicalInFlightCount: coordinated.identicalInFlightCount,+ });+ res.json(coordinated.response.body);});router.get("/companies/:companyId/issues/count", async (req, res) => {diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.tsindex 91710f71d7..5f897a14f8 100644--- a/server/src/routes/openapi.ts+++ b/server/src/routes/openapi.ts@@ -1637,8 +1637,12 @@ registry.registerPath({path: "/api/companies/{companyId}/issues",tags: ["issues"],summary: "List issues in a company",- request: { params: z.object({ companyId: z.string() }) },- responses: { 200: r.ok(), 401: r.unauthorized },+ description: "Use `view=compact` for the board issue-list row contract. The default response remains the broad compatibility contract.",+ request: {+ params: z.object({ companyId: z.string() }),+ query: z.object({ view: z.enum(["compact"]).optional() }).passthrough(),+ },+ responses: { 200: r.ok(), 304: { description: "Not Modified" }, 401: r.unauthorized },});registry.registerPath({diff --git a/ui/src/api/activity.ts b/ui/src/api/activity.tsindex b86f683d80..30698b12ff 100644--- a/ui/src/api/activity.ts+++ b/ui/src/api/activity.ts@@ -1,5 +1,5 @@import type { ActivityEvent, RunLivenessState } from "@paperclipai/shared";-import { api } from "./client";+import { api, type RequestOptions } from "./client";export type { RunLivenessState } from "@paperclipai/shared";@@ -57,14 +57,18 @@ export interface IssueForRun {}export const activityApi = {- list: (companyId: string, filters?: { entityType?: string; entityId?: string; agentId?: string; limit?: number }) => {+ list: (+ companyId: string,+ filters?: { entityType?: string; entityId?: string; agentId?: string; limit?: number },+ options?: RequestOptions,+ ) => {const params = new URLSearchParams();if (filters?.entityType) params.set("entityType", filters.entityType);if (filters?.entityId) params.set("entityId", filters.entityId);if (filters?.agentId) params.set("agentId", filters.agentId);if (filters?.limit) params.set("limit", String(filters.limit));const qs = params.toString();- return api.get<ActivityEvent[]>(`/companies/${companyId}/activity${qs ? `?${qs}` : ""}`);+ return api.get<ActivityEvent[]>(`/companies/${companyId}/activity${qs ? `?${qs}` : ""}`, options);},forIssue: (issueId: string) => api.get<ActivityEvent[]>(`/issues/${issueId}/activity`),runsForIssue: (issueId: string) => api.get<RunForIssue[]>(`/issues/${issueId}/runs`),diff --git a/ui/src/api/client.test.ts b/ui/src/api/client.test.tsnew file mode 100644index 0000000000..d21ec06181--- /dev/null+++ b/ui/src/api/client.test.ts@@ -0,0 +1,132 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { __inflightGetCount, api } from "./client";++interface Deferred<T> {+ promise: Promise<T>;+ resolve: (value: T) => void;+ reject: (reason?: unknown) => void;+}++function deferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++function jsonResponse(body: unknown) {+ return { ok: true, status: 200, json: async () => body } as unknown as Response;+}++const fetchMock = vi.fn();++beforeEach(() => {+ fetchMock.mockReset();+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("in-tab GET coalescing", () => {+ it("shares one underlying fetch for identical in-flight GETs", async () => {+ const d = deferred<Response>();+ fetchMock.mockReturnValue(d.promise);++ const p1 = api.get("/coalesce-a");+ const p2 = api.get("/coalesce-a");+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(__inflightGetCount()).toBe(1);++ d.resolve(jsonResponse({ value: 1 }));+ expect(await p1).toEqual({ value: 1 });+ expect(await p2).toEqual({ value: 1 });+ // Entry cleared once settled.+ expect(__inflightGetCount()).toBe(0);+ });++ it("issues a fresh fetch after the previous one settles", async () => {+ fetchMock.mockResolvedValue(jsonResponse({ value: "x" }));+ await api.get("/coalesce-b");+ await api.get("/coalesce-b");+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("does not coalesce different paths", async () => {+ fetchMock.mockReturnValue(deferred<Response>().promise);+ const c1 = new AbortController();+ const c2 = new AbortController();+ const p1 = api.get("/path-1", { signal: c1.signal });+ const p2 = api.get("/path-2", { signal: c2.signal });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ // Clean up the never-settling shared entries so the module map does not leak.+ c1.abort();+ c2.abort();+ await expect(p1).rejects.toMatchObject({ name: "AbortError" });+ await expect(p2).rejects.toMatchObject({ name: "AbortError" });+ });++ it("never coalesces mutations", async () => {+ fetchMock.mockResolvedValue(jsonResponse({ ok: true }));+ await Promise.all([api.post("/mutate", { a: 1 }), api.post("/mutate", { a: 1 })]);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+});++describe("per-caller abort semantics", () => {+ it("aborting one caller rejects only that caller, not the shared fetch", async () => {+ const d = deferred<Response>();+ let sharedSignal: AbortSignal | undefined;+ fetchMock.mockImplementation((_url: string, init: RequestInit) => {+ sharedSignal = init.signal ?? undefined;+ return d.promise;+ });++ const c1 = new AbortController();+ const c2 = new AbortController();+ const p1 = api.get("/abort-a", { signal: c1.signal });+ const p2 = api.get("/abort-a", { signal: c2.signal });++ c1.abort();+ await expect(p1).rejects.toMatchObject({ name: "AbortError" });+ // The shared fetch is still alive because caller 2 has not aborted.+ expect(sharedSignal?.aborted).toBe(false);++ d.resolve(jsonResponse({ value: 2 }));+ expect(await p2).toEqual({ value: 2 });+ });++ it("aborts the shared fetch once every caller has aborted", async () => {+ const d = deferred<Response>();+ let sharedSignal: AbortSignal | undefined;+ fetchMock.mockImplementation((_url: string, init: RequestInit) => {+ sharedSignal = init.signal ?? undefined;+ return d.promise;+ });++ const c1 = new AbortController();+ const c2 = new AbortController();+ const p1 = api.get("/abort-b", { signal: c1.signal });+ const p2 = api.get("/abort-b", { signal: c2.signal });++ c1.abort();+ c2.abort();+ await expect(p1).rejects.toMatchObject({ name: "AbortError" });+ await expect(p2).rejects.toMatchObject({ name: "AbortError" });+ expect(sharedSignal?.aborted).toBe(true);+ expect(__inflightGetCount()).toBe(0);+ });++ it("rejects immediately if the caller signal is already aborted", async () => {+ const controller = new AbortController();+ controller.abort();+ await expect(api.get("/already-aborted", { signal: controller.signal })).rejects.toMatchObject({+ name: "AbortError",+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/api/client.ts b/ui/src/api/client.tsindex 69b51b6470..2a27addedf 100644--- a/ui/src/api/client.ts+++ b/ui/src/api/client.ts@@ -1,3 +1,5 @@+import { getPageVisibility, getVisibilityHeaderValue } from "@/lib/page-visibility";+const BASE = "/api";export class ApiError extends Error {@@ -12,12 +14,35 @@ export class ApiError extends Error {}}+export interface RequestOptions {+ /** Abort signal wired through to `fetch` and coalescing (per-caller). */+ signal?: AbortSignal;+}++function abortError(): DOMException {+ return new DOMException("The operation was aborted.", "AbortError");+}++/**+ * Non-authoritative observability hints (PAP-12556 / Phase 1). The server treats+ * these as scheduling/telemetry only and never as security signals.+ */+function applyObservabilityHeaders(headers: Headers) {+ if (headers.has("X-Paperclip-Tab-Visible")) return; // caller override wins+ const visibility = getPageVisibility();+ headers.set("X-Paperclip-Tab-Visible", getVisibilityHeaderValue(visibility));+ if (typeof window !== "undefined" && window.location) {+ headers.set("X-Paperclip-Route", window.location.pathname);+ }+}+async function request<T>(path: string, init?: RequestInit): Promise<T> {const headers = new Headers(init?.headers ?? undefined);const body = init?.body;if (!(body instanceof FormData) && !headers.has("Content-Type")) {headers.set("Content-Type", "application/json");}+ applyObservabilityHeaders(headers);const res = await fetch(`${BASE}${path}`, {headers,@@ -36,17 +61,96 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {return res.json();}+// --- In-tab request coalescing for identical safe GETs -----------------------+//+// Multiple callers issuing the same GET while one is in flight share a single+// underlying fetch. Each caller keeps its own abort semantics: aborting one+// caller only cancels the shared fetch when *every* caller has aborted.+// Mutations are never coalesced.++interface InflightGet {+ promise: Promise<unknown>;+ controller: AbortController;+ refs: Set<symbol>;+}++const inflightGets = new Map<string, InflightGet>();++function coalescedGet<T>(path: string, options?: RequestOptions): Promise<T> {+ const signal = options?.signal;+ if (signal?.aborted) return Promise.reject(abortError());++ let entry = inflightGets.get(path);+ if (!entry) {+ const controller = new AbortController();+ const promise = request<T>(path, { method: "GET", signal: controller.signal });+ const created: InflightGet = { promise, controller, refs: new Set() };+ // Clear the shared entry once settled so later calls issue a fresh request.+ promise.then(+ () => {+ if (inflightGets.get(path) === created) inflightGets.delete(path);+ },+ () => {+ if (inflightGets.get(path) === created) inflightGets.delete(path);+ },+ );+ inflightGets.set(path, created);+ entry = created;+ }++ const activeEntry = entry;+ const ref = Symbol("caller");+ activeEntry.refs.add(ref);++ const releaseRef = () => {+ if (!activeEntry.refs.delete(ref)) return;+ // Last caller gone before the fetch settled → abort the shared request.+ if (activeEntry.refs.size === 0 && inflightGets.get(path) === activeEntry) {+ inflightGets.delete(path);+ activeEntry.controller.abort();+ }+ };++ return new Promise<T>((resolve, reject) => {+ const onAbort = () => {+ signal?.removeEventListener("abort", onAbort);+ releaseRef();+ reject(abortError());+ };+ if (signal) signal.addEventListener("abort", onAbort);++ activeEntry.promise.then(+ (value) => {+ signal?.removeEventListener("abort", onAbort);+ activeEntry.refs.delete(ref);+ resolve(value as T);+ },+ (err) => {+ signal?.removeEventListener("abort", onAbort);+ activeEntry.refs.delete(ref);+ reject(err);+ },+ );+ });+}++/** Test-only: number of in-flight coalesced GET keys. */+export function __inflightGetCount(): number {+ return inflightGets.size;+}+export const api = {- get: <T>(path: string) => request<T>(path),- post: <T>(path: string, body: unknown) =>- request<T>(path, { method: "POST", body: JSON.stringify(body) }),- postForm: <T>(path: string, body: FormData) =>- request<T>(path, { method: "POST", body }),- put: <T>(path: string, body: unknown) =>- request<T>(path, { method: "PUT", body: JSON.stringify(body) }),- patch: <T>(path: string, body: unknown) =>- request<T>(path, { method: "PATCH", body: JSON.stringify(body) }),- delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),- deleteWithBody: <T>(path: string, body: unknown) =>- request<T>(path, { method: "DELETE", body: JSON.stringify(body) }),+ get: <T>(path: string, options?: RequestOptions) => coalescedGet<T>(path, options),+ post: <T>(path: string, body: unknown, options?: RequestOptions) =>+ request<T>(path, { method: "POST", body: JSON.stringify(body), signal: options?.signal }),+ postForm: <T>(path: string, body: FormData, options?: RequestOptions) =>+ request<T>(path, { method: "POST", body, signal: options?.signal }),+ put: <T>(path: string, body: unknown, options?: RequestOptions) =>+ request<T>(path, { method: "PUT", body: JSON.stringify(body), signal: options?.signal }),+ patch: <T>(path: string, body: unknown, options?: RequestOptions) =>+ request<T>(path, { method: "PATCH", body: JSON.stringify(body), signal: options?.signal }),+ delete: <T>(path: string, options?: RequestOptions) =>+ request<T>(path, { method: "DELETE", signal: options?.signal }),+ deleteWithBody: <T>(path: string, body: unknown, options?: RequestOptions) =>+ request<T>(path, { method: "DELETE", body: JSON.stringify(body), signal: options?.signal }),};diff --git a/ui/src/api/issues.test.ts b/ui/src/api/issues.test.tsindex 24f4794bcf..83ee4e927a 100644--- a/ui/src/api/issues.test.ts+++ b/ui/src/api/issues.test.ts@@ -63,6 +63,20 @@ describe("issuesApi.list", () => {);});+ it("requests the compact issue list view explicitly", async () => {+ await issuesApi.listCompact("company-1", {+ touchedByUserId: "me",+ includeLiveDescendantSummary: true,+ limit: 100,+ sortField: "updated",+ sortDir: "desc",+ });++ expect(mockApi.get).toHaveBeenCalledWith(+ "/companies/company-1/issues?touchedByUserId=me&includeLiveDescendantSummary=true&limit=100&sortField=updated&sortDir=desc&view=compact",+ );+ });+it("passes plan document filters through to the company issues endpoint", async () => {await issuesApi.list("company-1", { hasPlanDocument: false, limit: 25 });diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.tsindex 1ecb12afa0..2fd1d1cebb 100644--- a/ui/src/api/issues.ts+++ b/ui/src/api/issues.ts@@ -2,6 +2,7 @@ import type {AcceptedPlanDecompositionSummary,AskUserQuestionsAnswer,Approval,+ CompactIssue,CreateIssueTreeHold,DocumentRevision,FeedbackTargetType,@@ -25,7 +26,7 @@ import type {UpsertIssueWatchdog,UpsertIssueDocument,} from "@paperclipai/shared";-import { api } from "./client";+import { api, type RequestOptions } from "./client";export type IssueUpdateResponse = Issue & {comment?: IssueComment | null;@@ -36,71 +37,86 @@ export type ResolveRecoveryActionResponse = {recoveryAction: IssueRecoveryAction;};+export type IssueListFilters = {+ attention?: "blocked";+ status?: string;+ projectId?: string;+ parentId?: string;+ assigneeAgentId?: string;+ participantAgentId?: string;+ assigneeUserId?: string;+ touchedByUserId?: string;+ inboxArchivedByUserId?: string;+ unreadForUserId?: string;+ labelId?: string;+ workspaceId?: string;+ executionWorkspaceId?: string;+ originKind?: string;+ originKindPrefix?: string;+ originId?: string;+ descendantOf?: string;+ includeRoutineExecutions?: boolean;+ includeBlockedBy?: boolean;+ includeBlockedInboxAttention?: boolean;+ includeLiveDescendantSummary?: boolean;+ hasPlanDocument?: boolean;+ q?: string;+ limit?: number;+ offset?: number;+ sortField?: "updated";+ sortDir?: "asc" | "desc";+};++function issueListSearchParams(filters?: IssueListFilters) {+ const params = new URLSearchParams();+ if (filters?.attention) params.set("attention", filters.attention);+ if (filters?.status) params.set("status", filters.status);+ if (filters?.projectId) params.set("projectId", filters.projectId);+ if (filters?.parentId) params.set("parentId", filters.parentId);+ if (filters?.assigneeAgentId) params.set("assigneeAgentId", filters.assigneeAgentId);+ if (filters?.participantAgentId) params.set("participantAgentId", filters.participantAgentId);+ if (filters?.assigneeUserId) params.set("assigneeUserId", filters.assigneeUserId);+ if (filters?.touchedByUserId) params.set("touchedByUserId", filters.touchedByUserId);+ if (filters?.inboxArchivedByUserId) params.set("inboxArchivedByUserId", filters.inboxArchivedByUserId);+ if (filters?.unreadForUserId) params.set("unreadForUserId", filters.unreadForUserId);+ if (filters?.labelId) params.set("labelId", filters.labelId);+ if (filters?.workspaceId) params.set("workspaceId", filters.workspaceId);+ if (filters?.executionWorkspaceId) params.set("executionWorkspaceId", filters.executionWorkspaceId);+ if (filters?.originKind) params.set("originKind", filters.originKind);+ if (filters?.originKindPrefix) params.set("originKindPrefix", filters.originKindPrefix);+ if (filters?.originId) params.set("originId", filters.originId);+ if (filters?.descendantOf) params.set("descendantOf", filters.descendantOf);+ if (filters?.includeRoutineExecutions) params.set("includeRoutineExecutions", "true");+ if (filters?.includeBlockedBy) params.set("includeBlockedBy", "true");+ if (filters?.includeBlockedInboxAttention) params.set("includeBlockedInboxAttention", "true");+ if (filters?.includeLiveDescendantSummary) params.set("includeLiveDescendantSummary", "true");+ if (filters?.hasPlanDocument !== undefined) {+ params.set("hasPlanDocument", filters.hasPlanDocument ? "true" : "false");+ }+ if (filters?.q) params.set("q", filters.q);+ if (filters?.limit) params.set("limit", String(filters.limit));+ if (filters?.offset !== undefined) params.set("offset", String(filters.offset));+ if (filters?.sortField) params.set("sortField", filters.sortField);+ if (filters?.sortDir) params.set("sortDir", filters.sortDir);+ return params;+}+export const issuesApi = {list: (companyId: string,- filters?: {- attention?: "blocked";- status?: string;- projectId?: string;- parentId?: string;- assigneeAgentId?: string;- participantAgentId?: string;- assigneeUserId?: string;- touchedByUserId?: string;- inboxArchivedByUserId?: string;- unreadForUserId?: string;- labelId?: string;- workspaceId?: string;- executionWorkspaceId?: string;- originKind?: string;- originKindPrefix?: string;- originId?: string;- descendantOf?: string;- includeRoutineExecutions?: boolean;- includeBlockedBy?: boolean;- includeBlockedInboxAttention?: boolean;- includeLiveDescendantSummary?: boolean;- hasPlanDocument?: boolean;- q?: string;- limit?: number;- offset?: number;- sortField?: "updated";- sortDir?: "asc" | "desc";- },+ filters?: IssueListFilters,+ options?: RequestOptions,) => {- const params = new URLSearchParams();- if (filters?.attention) params.set("attention", filters.attention);- if (filters?.status) params.set("status", filters.status);- if (filters?.projectId) params.set("projectId", filters.projectId);- if (filters?.parentId) params.set("parentId", filters.parentId);- if (filters?.assigneeAgentId) params.set("assigneeAgentId", filters.assigneeAgentId);- if (filters?.participantAgentId) params.set("participantAgentId", filters.participantAgentId);- if (filters?.assigneeUserId) params.set("assigneeUserId", filters.assigneeUserId);- if (filters?.touchedByUserId) params.set("touchedByUserId", filters.touchedByUserId);- if (filters?.inboxArchivedByUserId) params.set("inboxArchivedByUserId", filters.inboxArchivedByUserId);- if (filters?.unreadForUserId) params.set("unreadForUserId", filters.unreadForUserId);- if (filters?.labelId) params.set("labelId", filters.labelId);- if (filters?.workspaceId) params.set("workspaceId", filters.workspaceId);- if (filters?.executionWorkspaceId) params.set("executionWorkspaceId", filters.executionWorkspaceId);- if (filters?.originKind) params.set("originKind", filters.originKind);- if (filters?.originKindPrefix) params.set("originKindPrefix", filters.originKindPrefix);- if (filters?.originId) params.set("originId", filters.originId);- if (filters?.descendantOf) params.set("descendantOf", filters.descendantOf);- if (filters?.includeRoutineExecutions) params.set("includeRoutineExecutions", "true");- if (filters?.includeBlockedBy) params.set("includeBlockedBy", "true");- if (filters?.includeBlockedInboxAttention) params.set("includeBlockedInboxAttention", "true");- if (filters?.includeLiveDescendantSummary) params.set("includeLiveDescendantSummary", "true");- if (filters?.hasPlanDocument !== undefined) {- params.set("hasPlanDocument", filters.hasPlanDocument ? "true" : "false");- }- if (filters?.q) params.set("q", filters.q);- if (filters?.limit) params.set("limit", String(filters.limit));- if (filters?.offset !== undefined) params.set("offset", String(filters.offset));- if (filters?.sortField) params.set("sortField", filters.sortField);- if (filters?.sortDir) params.set("sortDir", filters.sortDir);+ const params = issueListSearchParams(filters);const qs = params.toString();- return api.get<Issue[]>(`/companies/${companyId}/issues${qs ? `?${qs}` : ""}`);+ const path = `/companies/${companyId}/issues${qs ? `?${qs}` : ""}`;+ return options ? api.get<Issue[]>(path, options) : api.get<Issue[]>(path);+ },+ listCompact: (companyId: string, filters?: IssueListFilters, options?: RequestOptions) => {+ const params = issueListSearchParams(filters);+ params.set("view", "compact");+ const path = `/companies/${companyId}/issues?${params.toString()}`;+ return options ? api.get<CompactIssue[]>(path, options) : api.get<CompactIssue[]>(path);},count: (companyId: string,@@ -128,7 +144,9 @@ export const issuesApi = {createLabel: (companyId: string, data: { name: string; color: string }) =>api.post<IssueLabel>(`/companies/${companyId}/labels`, data),deleteLabel: (id: string) => api.delete<IssueLabel>(`/labels/${id}`),- get: (id: string) => api.get<Issue>(`/issues/${id}`),+ get: (id: string, options?: RequestOptions) => options+ ? api.get<Issue>(`/issues/${id}`, options)+ : api.get<Issue>(`/issues/${id}`),getWatchdog: (id: string) => api.get<IssueWatchdog | null>(`/issues/${id}/watchdog`),upsertWatchdog: (id: string, data: UpsertIssueWatchdog) =>api.put<IssueWatchdog>(`/issues/${id}/watchdog`, data),diff --git a/ui/src/components/ActiveAgentsPanel.tsx b/ui/src/components/ActiveAgentsPanel.tsxindex 02326a278f..e7b9d42be9 100644--- a/ui/src/components/ActiveAgentsPanel.tsx+++ b/ui/src/components/ActiveAgentsPanel.tsx@@ -15,6 +15,7 @@ import { ExternalLink } from "lucide-react";import { Identity } from "./Identity";import { RunChatSurface } from "./RunChatSurface";import { useLiveRunTranscripts } from "./transcript/useLiveRunTranscripts";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";import { Badge } from "@/components/ui/badge";function RunCardRecoveryChip({ action }: { action: IssueRecoveryAction }) {@@ -76,10 +77,20 @@ export function ActiveAgentsPanel({queryScope = "dashboard",showMoreLink = true,}: ActiveAgentsPanelProps) {- const { data: liveRuns } = useQuery({- queryKey: [...queryKeys.liveRuns(companyId), queryScope, { minRunCount, fetchLimit }],+ const liveRunsQueryKey = [...queryKeys.liveRuns(companyId), queryScope, { minRunCount, fetchLimit }] as const;+ const sharedLiveRuns = useSharedPollingQuery({+ companyId,+ resourceKey: `live-runs:${queryScope}:${minRunCount}:${fetchLimit ?? "default"}`,+ queryKey: liveRunsQueryKey,+ enabled: !!companyId,+ leaderOnly: true,+ });+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,queryFn: () => heartbeatsApi.liveRunsForCompany(companyId, { minCount: minRunCount, limit: fetchLimit }),+ enabled: sharedLiveRuns.enabled,});+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const runs = liveRuns ?? [];const visibleRuns = useMemo(() => runs.slice(0, cardLimit), [cardLimit, runs]);diff --git a/ui/src/components/ActivityFeed.tsx b/ui/src/components/ActivityFeed.tsxindex 15cd08cb73..90263a7c65 100644--- a/ui/src/components/ActivityFeed.tsx+++ b/ui/src/components/ActivityFeed.tsx@@ -1,5 +1,7 @@import { useMemo, useState, useRef, useCallback, useEffect } from "react";import { useQuery } from "@tanstack/react-query";+import { useVisibilityRefetchInterval } from "@/lib/polling";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";import type { ActivityEvent, Agent } from "@paperclipai/shared";import { activityApi } from "../api/activity";import { agentsApi } from "../api/agents";@@ -338,13 +340,25 @@ export function ActivityFeed({ className }: ActivityFeedProps) {document.head.appendChild(style);}, []);- // Fetch company-level activity, poll every 5s- const { data: activity } = useQuery({- queryKey: queryKeys.activity(selectedCompanyId ?? ""),- queryFn: () => activityApi.list(selectedCompanyId!),+ // Fetch company-level activity. Poll ~5s when the tab is focused; slow/stop in the+ // background so restored tabs don't storm the activity endpoint (PAP-12556).+ const activityRefetchInterval = useVisibilityRefetchInterval({ visibleMs: 5000 });+ const activityQueryKey = queryKeys.activity(selectedCompanyId ?? "");+ const sharedActivity = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "activity",+ queryKey: activityQueryKey,enabled: !!selectedCompanyId,- refetchInterval: 5000,+ refetchInterval: activityRefetchInterval,+ leaderOnly: true,});+ const { data: activity, dataUpdatedAt: activityUpdatedAt } = useQuery({+ queryKey: activityQueryKey,+ queryFn: ({ signal }) => activityApi.list(selectedCompanyId!, undefined, { signal }),+ enabled: sharedActivity.enabled,+ refetchInterval: sharedActivity.refetchInterval,+ });+ usePublishSharedQueryData(sharedActivity, activity, activityUpdatedAt);// Fetch agents for name resolution + empty stateconst { data: agents } = useQuery({diff --git a/ui/src/components/IssuesList.test.tsx b/ui/src/components/IssuesList.test.tsxindex f04a618e4d..9965f62aee 100644--- a/ui/src/components/IssuesList.test.tsx+++ b/ui/src/components/IssuesList.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdom-import { act } from "react";import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";import type { AnchorHTMLAttributes, ReactNode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { Issue, Project } from "@paperclipai/shared";@@ -73,7 +73,10 @@ vi.mock("@/lib/router", () => ({}));vi.mock("../api/issues", () => ({- issuesApi: mockIssuesApi,+ issuesApi: {+ ...mockIssuesApi,+ listCompact: mockIssuesApi.list,+ },}));vi.mock("../api/auth", () => ({@@ -84,6 +87,10 @@ vi.mock("../api/access", () => ({accessApi: mockAccessApi,}));+vi.mock("@/api/access", () => ({+ accessApi: mockAccessApi,+}));+vi.mock("../api/execution-workspaces", () => ({executionWorkspacesApi: mockExecutionWorkspacesApi,}));@@ -96,6 +103,17 @@ vi.mock("../api/externalObjects", () => ({externalObjectsApi: mockExternalObjectsApi,}));+// eslint-disable-next-line @typescript-eslint/no-explicit-any+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;++async function act(callback: () => void | Promise<void>) {+ let result: void | Promise<void> = undefined;+ flushSync(() => {+ result = callback();+ });+ await result;+}+vi.mock("./IssueRow", () => ({IssueRow: ({issue,@@ -214,6 +232,13 @@ async function flush() {});}+async function flushAnimationFrame() {+ await act(async () => {+ await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));+ await Promise.resolve();+ });+}+async function waitForAssertion(assertion: () => void, attempts = 20) {let lastError: unknown;@@ -470,7 +495,7 @@ describe("IssuesList", () => {q: "server",projectId: undefined,limit: 200,- });+ }, { signal: expect.any(AbortSignal) });expect(container.textContent).toContain("Server result");expect(container.textContent).not.toContain("Local issue");});@@ -505,7 +530,7 @@ describe("IssuesList", () => {projectId: undefined,parentId: "parent-1",limit: 200,- });+ }, { signal: expect.any(AbortSignal) });expect(container.textContent).toContain("Server result");expect(container.textContent).not.toContain("Local issue");});@@ -1089,7 +1114,7 @@ describe("IssuesList", () => {container,);- await waitForMicrotaskAssertion(() => {+ await waitForAssertion(() => {expect(container.textContent).toContain("Showing up to 200 matches. Refine the search to narrow further.");});@@ -1143,12 +1168,12 @@ describe("IssuesList", () => {status: "backlog",limit: 200,includeRoutineExecutions: true,- }));+ }), { signal: expect.any(AbortSignal) });expect(mockIssuesApi.list).toHaveBeenCalledWith("company-1", expect.objectContaining({status: "done",limit: 200,includeRoutineExecutions: true,- }));+ }), { signal: expect.any(AbortSignal) });expect(mockKanbanBoard).toHaveBeenLastCalledWith(expect.objectContaining({issues: expect.arrayContaining([expect.objectContaining({ id: "issue-backlog" }),@@ -1363,10 +1388,13 @@ describe("IssuesList", () => {expect(container.querySelectorAll('[data-testid="issue-row"]')).toHaveLength(100);});+ await flush();+act(() => {setDocumentScrollMetrics({ innerHeight: 600, scrollY: 1500, scrollHeight: 2000 });window.dispatchEvent(new Event("scroll"));});+ await flushAnimationFrame();await waitForAssertion(() => {expect(container.querySelectorAll('[data-testid="issue-row"]')).toHaveLength(250);@@ -1419,6 +1447,7 @@ describe("IssuesList", () => {main.scrollTop = 1500;main.dispatchEvent(new Event("scroll"));});+ await flushAnimationFrame();await waitForAssertion(() => {expect(container.querySelectorAll('[data-testid="issue-row"]').length).toBeGreaterThan(100);@@ -1466,6 +1495,7 @@ describe("IssuesList", () => {setDocumentScrollMetrics({ innerHeight: 600, scrollY: 1500, scrollHeight: 2000 });window.dispatchEvent(new Event("scroll"));});+ await flushAnimationFrame();await waitForAssertion(() => {expect(onLoadMoreIssues).toHaveBeenCalledTimes(2);diff --git a/ui/src/components/IssuesList.tsx b/ui/src/components/IssuesList.tsxindex 2a127b8b89..c8fa629326 100644--- a/ui/src/components/IssuesList.tsx+++ b/ui/src/components/IssuesList.tsx@@ -1,5 +1,6 @@import { startTransition, useDeferredValue, useEffect, useMemo, useState, useCallback, useRef } from "react";import { useQueries, useQuery } from "@tanstack/react-query";+import { useVisibilityRefetchInterval } from "@/lib/polling";import { accessApi } from "../api/access";import { useDialogActions } from "../context/DialogContext";import { useCompany } from "../context/CompanyContext";@@ -522,11 +523,12 @@ function SubIssueProgressSummaryStrip({// Refresh fast enough that the runtime ticks up while a sub-issue is still// running, but slow enough not to hammer the recursive CTE on idle trees.const hasInProgress = summary.inProgressCount > 0;+ const costRefetchInterval = useVisibilityRefetchInterval({ visibleMs: 5_000 });const { data: costSummary } = useQuery({queryKey: queryKeys.issues.costSummary(parentIssueIdForCostSummary ?? "pending", { excludeRoot: true }),queryFn: () => issuesApi.getCostSummary(parentIssueIdForCostSummary!, { excludeRoot: true }),enabled: !!parentIssueIdForCostSummary,- refetchInterval: hasInProgress ? 5_000 : false,+ refetchInterval: hasInProgress ? costRefetchInterval : false,});const totalTokens = costSummary@@ -767,17 +769,18 @@ export function IssuesList({queryKey: [...queryKeys.issues.search(selectedCompanyId!, normalizedIssueSearch, projectId),searchFilters ?? {},+ "compact",ISSUE_SEARCH_RESULT_LIMIT,enableRoutineVisibilityFilter ? "with-routine-executions" : "without-routine-executions",],- queryFn: () =>- issuesApi.list(selectedCompanyId!, {+ queryFn: ({ signal }) =>+ issuesApi.listCompact(selectedCompanyId!, {q: normalizedIssueSearch,projectId,limit: ISSUE_SEARCH_RESULT_LIMIT,...searchFilters,...(enableRoutineVisibilityFilter ? { includeRoutineExecutions: true } : {}),- }),+ }, { signal }).then((rows) => rows as Issue[]),enabled: !!selectedCompanyId && normalizedIssueSearch.length > 0 && !searchWithinLoadedIssues,placeholderData: (previousData) => previousData,});@@ -790,18 +793,19 @@ export function IssuesList({normalizedIssueSearch,projectId ?? "__all-projects__",searchFilters ?? {},+ "compact",ISSUE_BOARD_COLUMN_RESULT_LIMIT,enableRoutineVisibilityFilter ? "with-routine-executions" : "without-routine-executions",],- queryFn: () =>- issuesApi.list(selectedCompanyId!, {+ queryFn: ({ signal }: { signal: AbortSignal }) =>+ issuesApi.listCompact(selectedCompanyId!, {...searchFilters,...(normalizedIssueSearch.length > 0 ? { q: normalizedIssueSearch } : {}),projectId,status,limit: ISSUE_BOARD_COLUMN_RESULT_LIMIT,...(enableRoutineVisibilityFilter ? { includeRoutineExecutions: true } : {}),- }),+ }, { signal }).then((rows) => rows as Issue[]),enabled: !!selectedCompanyId && viewState.viewMode === "board" && !searchWithinLoadedIssues,placeholderData: (previousData: Issue[] | undefined) => previousData,})),@@ -1443,9 +1447,7 @@ export function IssuesList({const loadMoreIssueRows = useCallback(() => {if (viewState.viewMode !== "list") return;if (hasMoreRenderedRows) {- startTransition(() => {- setRenderedIssueRowLimit((current) => Math.min(filtered.length, current + ISSUE_ROW_RENDER_BATCH_SIZE));- });+ setRenderedIssueRowLimit((current) => Math.min(filtered.length, current + ISSUE_ROW_RENDER_BATCH_SIZE));return;}if (hasMoreIssues && !isLoadingMoreIssues) {diff --git a/ui/src/components/LiveRunWidget.tsx b/ui/src/components/LiveRunWidget.tsxindex 027c74e37a..51bfcef469 100644--- a/ui/src/components/LiveRunWidget.tsx+++ b/ui/src/components/LiveRunWidget.tsx@@ -1,6 +1,7 @@import { useMemo, useState } from "react";import { Link } from "@/lib/router";import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useVisibilityRefetchInterval } from "@/lib/polling";import { heartbeatsApi, type LiveRunForIssue } from "../api/heartbeats";import { queryKeys } from "../lib/queryKeys";import { formatDateTime } from "../lib/utils";@@ -28,18 +29,22 @@ export function LiveRunWidget({ issueId, companyId }: LiveRunWidgetProps) {const queryClient = useQueryClient();const [cancellingRunIds, setCancellingRunIds] = useState(new Set<string>());+ // Live-run polling slows/stops for hidden tabs so a restored window doesn't+ // hammer the live-run endpoints (PAP-12556).+ const liveRunRefetchInterval = useVisibilityRefetchInterval({ visibleMs: 3000 });+const { data: liveRuns } = useQuery({queryKey: queryKeys.issues.liveRuns(issueId),queryFn: () => heartbeatsApi.liveRunsForIssue(issueId),enabled: !!issueId,- refetchInterval: 3000,+ refetchInterval: liveRunRefetchInterval,});const { data: activeRun } = useQuery({queryKey: queryKeys.issues.activeRun(issueId),queryFn: () => heartbeatsApi.activeRunForIssue(issueId),enabled: !!issueId,- refetchInterval: 3000,+ refetchInterval: liveRunRefetchInterval,});const runs = useMemo(() => {diff --git a/ui/src/components/Sidebar.tsx b/ui/src/components/Sidebar.tsxindex cc5e9b2610..23667bb6cc 100644--- a/ui/src/components/Sidebar.tsx+++ b/ui/src/components/Sidebar.tsx@@ -35,6 +35,7 @@ import { heartbeatsApi } from "../api/heartbeats";import { instanceSettingsApi } from "../api/instanceSettings";import { queryKeys } from "../lib/queryKeys";import { useInboxBadge } from "../hooks/useInboxBadge";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";import { Button } from "@/components/ui/button";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";@@ -56,12 +57,22 @@ export function Sidebar() {queryKey: queryKeys.instance.experimentalSettings,queryFn: () => instanceSettingsApi.getExperimental(),});- const { data: liveRuns } = useQuery({- queryKey: queryKeys.liveRuns(selectedCompanyId!),- queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,enabled: !!selectedCompanyId,refetchInterval: 10_000,+ leaderOnly: true,+ });+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ enabled: sharedLiveRuns.enabled,+ refetchInterval: sharedLiveRuns.refetchInterval,});+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const liveRunCount = liveRuns?.length ?? 0;const showWorkspacesLink = experimentalSettings?.enableIsolatedWorkspaces === true;const showPipelines = experimentalSettings?.enablePipelines === true;diff --git a/ui/src/components/SidebarAccountMenu.test.tsx b/ui/src/components/SidebarAccountMenu.test.tsxindex 12484b5aa3..317d174319 100644--- a/ui/src/components/SidebarAccountMenu.test.tsx+++ b/ui/src/components/SidebarAccountMenu.test.tsx@@ -13,6 +13,9 @@ const mockAuthApi = vi.hoisted(() => ({updateProfile: vi.fn(),signOut: vi.fn(),}));+const mockInstanceSettingsApi = vi.hoisted(() => ({+ getExperimental: vi.fn(),+}));const mockToggleTheme = vi.hoisted(() => vi.fn());const mockSetSidebarOpen = vi.hoisted(() => vi.fn());@@ -20,6 +23,14 @@ vi.mock("@/api/auth", () => ({authApi: mockAuthApi,}));+vi.mock("@/api/instanceSettings", () => ({+ instanceSettingsApi: mockInstanceSettingsApi,+}));++vi.mock("../api/instanceSettings", () => ({+ instanceSettingsApi: mockInstanceSettingsApi,+}));+vi.mock("@/lib/router", () => ({Link: ({ children, to, ...props }: { children: React.ReactNode; to: string }) => (<a href={to} {...props}>{children}</a>@@ -71,6 +82,9 @@ describe("SidebarAccountMenu", () => {image: "https://example.com/jane.png",},});+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({+ enableIsolatedWorkspaces: false,+ });});afterEach(() => {diff --git a/ui/src/components/SidebarAgents.tsx b/ui/src/components/SidebarAgents.tsxindex f1f4b2dc8f..7e681da39b 100644--- a/ui/src/components/SidebarAgents.tsx+++ b/ui/src/components/SidebarAgents.tsx@@ -33,6 +33,7 @@ import {useResourceMembershipMutation,useResourceMemberships,} from "../hooks/useResourceMemberships";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";import {AGENT_SORT_MODE_UPDATED_EVENT,getAgentSortModeStorageKey,@@ -329,12 +330,22 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }const membershipsQuery = useResourceMemberships(selectedCompanyId);const membershipMutation = useResourceMembershipMutation(selectedCompanyId);- const { data: liveRuns } = useQuery({- queryKey: queryKeys.liveRuns(selectedCompanyId!),- queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,enabled: !!selectedCompanyId,refetchInterval: 10_000,+ leaderOnly: true,+ });+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ enabled: sharedLiveRuns.enabled,+ refetchInterval: sharedLiveRuns.refetchInterval,});+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const liveCountByAgent = useMemo(() => {const counts = new Map<string, number>();diff --git a/ui/src/components/SidebarProjects.test.tsx b/ui/src/components/SidebarProjects.test.tsxindex 6d8759348e..0289a14349 100644--- a/ui/src/components/SidebarProjects.test.tsx+++ b/ui/src/components/SidebarProjects.test.tsx@@ -21,6 +21,9 @@ const mockResourceMembershipsApi = vi.hoisted(() => ({listMine: vi.fn(),updateProject: vi.fn(),}));+const mockInstanceSettingsApi = vi.hoisted(() => ({+ getExperimental: vi.fn(),+}));const mockOpenNewProject = vi.hoisted(() => vi.fn());const mockPushToast = vi.hoisted(() => vi.fn());@@ -89,6 +92,14 @@ vi.mock("../api/projects", () => ({projectsApi: mockProjectsApi,}));+vi.mock("../api/instanceSettings", () => ({+ instanceSettingsApi: mockInstanceSettingsApi,+}));++vi.mock("@/api/instanceSettings", () => ({+ instanceSettingsApi: mockInstanceSettingsApi,+}));+vi.mock("../api/auth", () => ({authApi: mockAuthApi,}));@@ -280,6 +291,9 @@ describe("SidebarProjects", () => {session: { id: "session-1", userId: "user-1" },user: { id: "user-1" },});+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({+ enableIsolatedWorkspaces: false,+ });memberships = {projectMemberships: {},agentMemberships: {},diff --git a/ui/src/hooks/useInboxBadge.ts b/ui/src/hooks/useInboxBadge.tsindex 22aaacf855..a2aac8a992 100644--- a/ui/src/hooks/useInboxBadge.ts+++ b/ui/src/hooks/useInboxBadge.ts@@ -9,6 +9,7 @@ import { dashboardApi } from "../api/dashboard";import { heartbeatsApi } from "../api/heartbeats";import { issuesApi } from "../api/issues";import { queryKeys } from "../lib/queryKeys";+import { usePublishSharedQueryData, useSharedPollingQuery } from "./useSharedPolling";import {buildInboxDismissedAtByKey,computeInboxBadgeData,@@ -169,14 +170,29 @@ export function useInboxBadge(companyId: string | null | undefined) {retry: false,});- const { data: dashboard } = useQuery({- queryKey: queryKeys.dashboard(companyId!),+ const dashboardQueryKey = queryKeys.dashboard(companyId!);+ const sharedDashboard = useSharedPollingQuery({+ companyId,+ resourceKey: "dashboard",+ queryKey: dashboardQueryKey,+ enabled: !!companyId,+ });+ const { data: dashboard, dataUpdatedAt: dashboardUpdatedAt } = useQuery({+ queryKey: dashboardQueryKey,queryFn: () => dashboardApi.summary(companyId!),enabled: !!companyId,});+ usePublishSharedQueryData(sharedDashboard, dashboard, dashboardUpdatedAt);- const { data: mineIssuesRaw = [] } = useQuery({- queryKey: queryKeys.issues.listMineByMe(companyId!),+ const mineIssuesQueryKey = queryKeys.issues.listMineByMe(companyId!);+ const sharedMineIssues = useSharedPollingQuery({+ companyId,+ resourceKey: "inbox-badge:mine-issues",+ queryKey: mineIssuesQueryKey,+ enabled: !!companyId,+ });+ const { data: mineIssuesRaw = [], dataUpdatedAt: mineIssuesUpdatedAt } = useQuery({+ queryKey: mineIssuesQueryKey,queryFn: () =>issuesApi.list(companyId!, {touchedByUserId: "me",@@ -188,6 +204,7 @@ export function useInboxBadge(companyId: string | null | undefined) {refetchOnWindowFocus: false,staleTime: INBOX_BADGE_HOT_PATH_STALE_MS,});+ usePublishSharedQueryData(sharedMineIssues, mineIssuesRaw, mineIssuesUpdatedAt);const mineIssues = useMemo(() => getRecentTouchedIssues(mineIssuesRaw), [mineIssuesRaw]);const currentUserId = session?.user.id ?? session?.session.userId ?? null;diff --git a/ui/src/hooks/useSharedPolling.ts b/ui/src/hooks/useSharedPolling.tsnew file mode 100644index 0000000000..1fc2ea674e--- /dev/null+++ b/ui/src/hooks/useSharedPolling.ts@@ -0,0 +1,134 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { type QueryKey, useQueryClient } from "@tanstack/react-query";+import {+ SharedPollingCoordinator,+ type SharedPollingSnapshot,+} from "../lib/cross-tab-poll";++type RefetchInterval = number | false;++export interface SharedPollingQueryOptions {+ companyId: string | null | undefined;+ resourceKey: string;+ queryKey: QueryKey;+ enabled?: boolean;+ refetchInterval?: RefetchInterval;+ /**+ * When true, non-leader tabs disable their active polling/query fetch for this+ * resource and render from broadcast/cache data. Use for interval-polled hot+ * endpoints. Leave false for one-shot reads where blank first paint is worse+ * than a duplicated initial fetch.+ */+ leaderOnly?: boolean;+}++export interface SharedPollingQueryState<TData> {+ isLeader: boolean;+ enabled: boolean;+ refetchInterval: RefetchInterval;+ publish: (data: TData | undefined) => void;+}++type RegistryEntry = {+ coordinator: SharedPollingCoordinator;+ refs: number;+};++const coordinators = new Map<string, RegistryEntry>();++function acquireCoordinator(companyId: string): SharedPollingCoordinator {+ const existing = coordinators.get(companyId);+ if (existing) {+ existing.refs += 1;+ return existing.coordinator;+ }+ const coordinator = new SharedPollingCoordinator(companyId);+ coordinator.start();+ coordinators.set(companyId, { coordinator, refs: 1 });+ return coordinator;+}++function releaseCoordinator(companyId: string): void {+ const existing = coordinators.get(companyId);+ if (!existing) return;+ existing.refs -= 1;+ if (existing.refs > 0) return;+ existing.coordinator.stop();+ coordinators.delete(companyId);+}++function resourceKey(companyId: string, key: string, queryKeyHash: string): string {+ return `${companyId}:${key}:${queryKeyHash}`;+}++export function useSharedPollingQuery<TData>({+ companyId,+ resourceKey: rawResourceKey,+ queryKey,+ enabled = true,+ refetchInterval = false,+ leaderOnly = false,+}: SharedPollingQueryOptions): SharedPollingQueryState<TData> {+ const queryClient = useQueryClient();+ const activeCompanyId = enabled && companyId ? companyId : null;+ const queryKeyHash = useMemo(() => JSON.stringify(queryKey), [queryKey]);+ const fullResourceKey = activeCompanyId ? resourceKey(activeCompanyId, rawResourceKey, queryKeyHash) : null;+ const queryKeyRef = useRef(queryKey);+ const [snapshot, setSnapshot] = useState<SharedPollingSnapshot>({ isLeader: true });++ useEffect(() => {+ queryKeyRef.current = queryKey;+ }, [queryKey, queryKeyHash]);++ useEffect(() => {+ if (!activeCompanyId || !fullResourceKey) {+ setSnapshot({ isLeader: true });+ return;+ }++ const coordinator = acquireCoordinator(activeCompanyId);+ const unsubscribeState = coordinator.subscribe(setSnapshot);+ const unsubscribeResource = coordinator.subscribeResource(fullResourceKey, (message) => {+ if (message.type !== "result") return;+ queryClient.setQueryData(queryKeyRef.current, message.data as TData);+ });+ coordinator.request(fullResourceKey);++ return () => {+ unsubscribeResource();+ unsubscribeState();+ releaseCoordinator(activeCompanyId);+ };+ }, [activeCompanyId, fullResourceKey, leaderOnly, queryClient, queryKeyHash]);++ const isLeader = !leaderOnly || snapshot.isLeader;+ const queryEnabled = enabled && (!leaderOnly || snapshot.isLeader);+ const coordinatedInterval = leaderOnly && !snapshot.isLeader ? false : refetchInterval;++ const publish = useCallback((data: TData | undefined) => {+ if (!activeCompanyId || !fullResourceKey || data === undefined) return;+ const entry = coordinators.get(activeCompanyId);+ entry?.coordinator.publish(fullResourceKey, data);+ }, [activeCompanyId, fullResourceKey]);++ return useMemo(+ () => ({+ isLeader,+ enabled: queryEnabled,+ refetchInterval: coordinatedInterval,+ publish,+ }),+ [coordinatedInterval, isLeader, publish, queryEnabled],+ );+}++export function usePublishSharedQueryData<TData>(+ shared: Pick<SharedPollingQueryState<TData>, "publish" | "isLeader">,+ data: TData | undefined,+ dataUpdatedAt: number,+): void {+ useEffect(() => {+ if (!shared.isLeader || dataUpdatedAt <= 0) return;+ shared.publish(data);+ }, [data, dataUpdatedAt, shared]);+}diff --git a/ui/src/lib/cross-tab-poll.test.ts b/ui/src/lib/cross-tab-poll.test.tsnew file mode 100644index 0000000000..d2a831b245--- /dev/null+++ b/ui/src/lib/cross-tab-poll.test.ts@@ -0,0 +1,159 @@+import { describe, expect, it, vi } from "vitest";+import {+ LeaderElection,+ createLeaseStore,+ createStorageRelayShared,+ type LeaseStore,+ type SharedMessage,+} from "./cross-tab-poll";++class MemoryLeaseStore implements LeaseStore {+ record: ReturnType<LeaseStore["read"]> = null;++ read() {+ return this.record;+ }++ write(record: NonNullable<ReturnType<LeaseStore["read"]>>) {+ this.record = { ...record };+ }++ clear() {+ this.record = null;+ }+}++describe("LeaderElection", () => {+ it("elects one visible leader and keeps the second visible tab as follower", () => {+ let now = 1_000;+ const store = new MemoryLeaseStore();+ const a = new LeaderElection({ now: () => now, store, random: () => 0 }, {+ tabId: "a",+ leaseTtlMs: 5_000,+ });+ const b = new LeaderElection({ now: () => now, store, random: () => 0 }, {+ tabId: "b",+ leaseTtlMs: 5_000,+ });++ expect(a.step(true)).toBe("leader");+ expect(b.step(true)).toBe("follower");+ expect(store.read()?.leader).toBe("a");++ now += 1_000;+ expect(a.step(true)).toBe("leader");+ expect(b.step(true)).toBe("follower");+ expect(store.read()).toMatchObject({ leader: "a", visible: true });+ });++ it("keeps hidden tabs from claiming an empty lease until their grace expires", () => {+ let now = 10_000;+ const store = new MemoryLeaseStore();+ const hidden = new LeaderElection({ now: () => now, store, random: () => 0 }, {+ tabId: "hidden",+ hiddenGraceMs: 2_000,+ hiddenGraceJitterMs: 0,+ leaseTtlMs: 5_000,+ });++ expect(hidden.step(false)).toBe("follower");+ expect(store.read()).toBeNull();++ now += 1_999;+ expect(hidden.step(false)).toBe("follower");+ expect(store.read()).toBeNull();++ now += 1;+ expect(hidden.step(false)).toBe("leader");+ expect(store.read()).toMatchObject({ leader: "hidden", visible: false });+ });++ it("recovers leadership after the old leader lease expires", () => {+ let now = 50_000;+ const store = new MemoryLeaseStore();+ const leader = new LeaderElection({ now: () => now, store, random: () => 0 }, {+ tabId: "leader",+ leaseTtlMs: 1_000,+ });+ const follower = new LeaderElection({ now: () => now, store, random: () => 0 }, {+ tabId: "follower",+ leaseTtlMs: 1_000,+ });++ expect(leader.step(true)).toBe("leader");+ expect(follower.step(true)).toBe("follower");++ now += 1_001;+ expect(follower.step(true)).toBe("leader");+ expect(store.read()).toMatchObject({ leader: "follower" });+ });++ it("lets a visible tab preempt a hidden leader lease", () => {+ let now = 100_000;+ const store = new MemoryLeaseStore();+ const hidden = new LeaderElection({ now: () => now, store, random: () => 0 }, {+ tabId: "hidden",+ hiddenGraceMs: 0,+ hiddenGraceJitterMs: 0,+ leaseTtlMs: 5_000,+ });+ const visible = new LeaderElection({ now: () => now, store, random: () => 0 }, {+ tabId: "visible",+ leaseTtlMs: 5_000,+ });++ expect(hidden.step(false)).toBe("leader");+ expect(visible.step(true)).toBe("leader");+ expect(store.read()).toMatchObject({ leader: "visible", visible: true });+ });++ it("ignores corrupt lease storage so a visible tab can recover", () => {+ let raw = "{not-json";+ const storage = {+ getItem: vi.fn(() => raw),+ setItem: vi.fn((_key: string, value: string) => {+ raw = value;+ }),+ removeItem: vi.fn(() => {+ raw = "";+ }),+ };+ const store = createLeaseStore(storage, "lease");+ const election = new LeaderElection({ now: () => 1, store, random: () => 0 }, {+ tabId: "a",+ leaseTtlMs: 100,+ });++ expect(election.step(true)).toBe("leader");+ expect(JSON.parse(raw)).toMatchObject({ leader: "a" });+ });+});++describe("createStorageRelayShared", () => {+ it("delivers result messages through the localStorage relay fallback", () => {+ let storageListener: ((key: string | null, newValue: string | null) => void) | null = null;+ const seen: SharedMessage[] = [];+ const channel = createStorageRelayShared("relay", {+ storage: {+ setItem(key, value) {+ storageListener?.(key, value);+ },+ },+ onStorage(cb) {+ storageListener = cb;+ return () => {+ storageListener = null;+ };+ },+ nextNonce: () => "nonce-1",+ });++ const unsubscribe = channel.subscribe((message) => seen.push(message));+ channel.post({ type: "result", key: "company:live-runs", from: "leader", at: 123, data: [{ id: "run-1" }] });++ expect(seen).toEqual([+ { type: "result", key: "company:live-runs", from: "leader", at: 123, data: [{ id: "run-1" }] },+ ]);+ unsubscribe();+ });+});diff --git a/ui/src/lib/cross-tab-poll.ts b/ui/src/lib/cross-tab-poll.tsnew file mode 100644index 0000000000..3569a00f5b--- /dev/null+++ b/ui/src/lib/cross-tab-poll.ts@@ -0,0 +1,583 @@+/**+ * Cross-tab shared polling coordination (PAP-12557 / Phase 2 of PAP-12542).+ *+ * Goal: when a user restores many Paperclip tabs at once, we do not want every+ * tab independently polling the same company-scoped hot endpoints (live-runs,+ * dashboard, inbox list, activity). Instead we elect ONE visible leader tab per+ * company to poll, and the leader broadcasts fresh results to the other tabs.+ *+ * Two independent primitives make this robust:+ *+ * 1. `LeaderElection` — a localStorage-lease election that is the source of+ * truth for "who polls". It works with nothing but a Storage-like object+ * and a clock, so it survives even when `BroadcastChannel` is unavailable,+ * and it is fully unit-testable with injected fakes (no DOM required).+ *+ * 2. `SharedChannel` — a best-effort message bus for sharing poll results.+ * Prefers `BroadcastChannel`; falls back to a `localStorage` + `storage`+ * event relay when it is not available.+ *+ * The lease is authoritative; the channel is an optimisation. If the channel is+ * missing, followers still stop polling (lease) and rely on their react-query+ * cache / a slow safety poll, so we never regress to worse than a single tab.+ *+ * Design rules (from the approved plan, Phase 2 acceptance):+ * - At most one active leader per company under normal browser conditions.+ * - Hidden tabs do NOT become leader while a visible tab exists.+ * - Leader failover happens within ~one poll interval + lease grace when the+ * leader closes or crashes (its lease expires and a follower reclaims it).+ */++// ---------------------------------------------------------------------------+// Leader election (pure, injectable — the tested core)+// ---------------------------------------------------------------------------++export interface LeaseRecord {+ /** Tab id of the current leader. */+ leader: string;+ /** Epoch ms after which the lease is considered dead. */+ expiresAt: number;+ /** Whether the leader tab was visible at its last renewal. */+ visible: boolean;+}++export type LeaderRole = "leader" | "follower";++/** Minimal persistence contract — a single JSON slot keyed by resource. */+export interface LeaseStore {+ /** Parsed record, or null if absent/corrupt. Callers check expiry themselves. */+ read(): LeaseRecord | null;+ write(record: LeaseRecord): void;+ clear(): void;+}++export interface LeaderElectionEnv {+ now: () => number;+ store: LeaseStore;+ /** Injectable RNG in [0,1) for grace jitter. Defaults to Math.random. */+ random?: () => number;+}++export interface LeaderElectionOptions {+ /** Stable, unique id for this tab. */+ tabId: string;+ /** How long a claimed lease is valid (ms). Default 8000. */+ leaseTtlMs?: number;+ /**+ * Base delay a *hidden* tab waits, after first observing an empty/expired+ * lease, before it will claim leadership. Gives any visible tab (which claims+ * immediately) a chance to win first. Default 4000.+ */+ hiddenGraceMs?: number;+ /** Random extra grace added once per instance to de-sync hidden tabs. Default 4000. */+ hiddenGraceJitterMs?: number;+}++export const DEFAULT_LEASE_TTL_MS = 8_000;++/**+ * localStorage-lease leader election. Call `step(visible)` on a regular tick+ * (and on visibility changes); it returns this tab's current role and, as a+ * side effect, claims/renews/releases the lease.+ *+ * The election is deliberately last-writer-wins with a read-back confirm: after+ * writing a claim we re-read the slot and only consider ourselves leader if the+ * slot still names us. In real browsers localStorage writes are synchronous, so+ * two tabs racing to claim resolve to a single winner within a tick or two.+ */+export class LeaderElection {+ private readonly tabId: string;+ private readonly ttl: number;+ private readonly hiddenGrace: number;+ private readonly env: LeaderElectionEnv;+ private role: LeaderRole = "follower";+ /** When (ms) this hidden tab first saw an empty lease; null once non-empty. */+ private hiddenEmptySince: number | null = null;++ constructor(env: LeaderElectionEnv, options: LeaderElectionOptions) {+ this.env = env;+ this.tabId = options.tabId;+ this.ttl = options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS;+ const base = options.hiddenGraceMs ?? 4_000;+ const jitterMax = options.hiddenGraceJitterMs ?? 4_000;+ const rng = env.random ?? Math.random;+ this.hiddenGrace = base + Math.round(Math.min(Math.max(rng(), 0), 0.999999) * jitterMax);+ }++ get id(): string {+ return this.tabId;+ }++ isLeader(): boolean {+ return this.role === "leader";+ }++ getRole(): LeaderRole {+ return this.role;+ }++ /** Advance the election given the current visibility. Returns the new role. */+ step(visible: boolean): LeaderRole {+ const now = this.env.now();+ const lease = this.env.store.read();+ const valid = lease != null && lease.expiresAt > now;++ if (valid && lease!.leader === this.tabId) {+ // We already hold a valid lease — renew it (and refresh our visibility).+ this.hiddenEmptySince = null;+ this.writeClaim(visible, now);+ this.role = "leader";+ return this.role;+ }++ if (valid) {+ // Someone else holds a valid lease.+ this.hiddenEmptySince = null;+ // A visible tab may preempt a hidden leader so the active window polls.+ if (visible && lease!.visible === false) {+ return this.tryClaim(visible, now);+ }+ this.role = "follower";+ return this.role;+ }++ // No valid lease (absent or expired) — up for grabs.+ if (visible) {+ this.hiddenEmptySince = null;+ return this.tryClaim(visible, now);+ }++ // Hidden tab: defer claiming so a visible tab can win the empty lease first.+ if (this.hiddenEmptySince == null) this.hiddenEmptySince = now;+ if (now - this.hiddenEmptySince >= this.hiddenGrace) {+ return this.tryClaim(visible, now);+ }+ this.role = "follower";+ return this.role;+ }++ /** Voluntarily give up leadership (call on unmount/close). */+ release(): void {+ if (this.role === "leader") {+ const lease = this.env.store.read();+ if (lease?.leader === this.tabId) this.env.store.clear();+ }+ this.role = "follower";+ this.hiddenEmptySince = null;+ }++ private writeClaim(visible: boolean, now: number): void {+ this.env.store.write({ leader: this.tabId, expiresAt: now + this.ttl, visible });+ }++ private tryClaim(visible: boolean, now: number): LeaderRole {+ this.writeClaim(visible, now);+ // Read-back confirm resolves races: only the last writer keeps leadership.+ const after = this.env.store.read();+ if (after != null && after.leader === this.tabId) {+ this.hiddenEmptySince = null;+ this.role = "leader";+ } else {+ this.role = "follower";+ }+ return this.role;+ }+}++/** Build a `LeaseStore` backed by a Storage-like object under one key. */+export function createLeaseStore(+ storage: Pick<Storage, "getItem" | "setItem" | "removeItem">,+ key: string,+): LeaseStore {+ return {+ read() {+ let raw: string | null;+ try {+ raw = storage.getItem(key);+ } catch {+ return null;+ }+ if (!raw) return null;+ try {+ const parsed = JSON.parse(raw) as Partial<LeaseRecord>;+ if (+ typeof parsed?.leader === "string" &&+ typeof parsed?.expiresAt === "number" &&+ typeof parsed?.visible === "boolean"+ ) {+ return parsed as LeaseRecord;+ }+ return null;+ } catch {+ return null;+ }+ },+ write(record) {+ try {+ storage.setItem(key, JSON.stringify(record));+ } catch {+ /* storage full / disabled — degrade to no lease */+ }+ },+ clear() {+ try {+ storage.removeItem(key);+ } catch {+ /* ignore */+ }+ },+ };+}++// ---------------------------------------------------------------------------+// Shared result channel (best-effort broadcast, with a storage fallback)+// ---------------------------------------------------------------------------++export interface SharedMessage {+ /** `result`: leader is publishing fresh data. `request`: a joiner wants the latest. */+ type: "result" | "request";+ /** Resource key, e.g. `live-runs:<companyId>`. */+ key: string;+ /** Sender tab id (so tabs ignore their own echoes). */+ from: string;+ /** Epoch ms the payload was produced. */+ at: number;+ /** Present on `result` messages. */+ data?: unknown;+}++export interface SharedChannel {+ post(message: SharedMessage): void;+ subscribe(handler: (message: SharedMessage) => void): () => void;+ close(): void;+}++/** No-op channel used when neither BroadcastChannel nor storage relay is usable. */+export function createNoopChannel(): SharedChannel {+ return {+ post() {},+ subscribe() {+ return () => {};+ },+ close() {},+ };+}++/** BroadcastChannel-backed shared channel. */+export function createBroadcastChannelShared(name: string): SharedChannel {+ const bc = new BroadcastChannel(name);+ return {+ post(message) {+ bc.postMessage(message);+ },+ subscribe(handler) {+ const listener = (ev: MessageEvent) => handler(ev.data as SharedMessage);+ bc.addEventListener("message", listener);+ return () => bc.removeEventListener("message", listener);+ },+ close() {+ bc.close();+ },+ };+}++export interface StorageRelayDeps {+ storage: Pick<Storage, "setItem">;+ /** Subscribe to cross-tab storage writes; returns an unsubscribe fn. */+ onStorage: (cb: (key: string | null, newValue: string | null) => void) => () => void;+ /** Monotonic nonce so repeated identical messages still trigger a `storage` event. */+ nextNonce: () => string;+}++/**+ * localStorage-relay shared channel used when `BroadcastChannel` is missing.+ * A post writes `{ n, msg }` to a storage key; other tabs receive the write via+ * the `storage` event. Note: `storage` events do not fire in the writing tab, so+ * the sender never receives its own message (which is what we want anyway).+ */+export function createStorageRelayShared(key: string, deps: StorageRelayDeps): SharedChannel {+ return {+ post(message) {+ try {+ deps.storage.setItem(key, JSON.stringify({ n: deps.nextNonce(), msg: message }));+ } catch {+ /* ignore */+ }+ },+ subscribe(handler) {+ return deps.onStorage((k, newValue) => {+ if (k !== key || !newValue) return;+ try {+ const parsed = JSON.parse(newValue) as { msg?: SharedMessage };+ if (parsed?.msg) handler(parsed.msg);+ } catch {+ /* ignore malformed relay payloads */+ }+ });+ },+ close() {},+ };+}++/**+ * Pick the best available shared channel for the current environment:+ * BroadcastChannel → localStorage relay → no-op.+ */+export function createSharedChannel(name: string): SharedChannel {+ if (typeof BroadcastChannel !== "undefined") {+ try {+ return createBroadcastChannelShared(name);+ } catch {+ /* fall through */+ }+ }+ if (typeof window !== "undefined" && typeof localStorage !== "undefined") {+ let counter = 0;+ const relayKey = `${name}:relay`;+ return createStorageRelayShared(relayKey, {+ storage: localStorage,+ onStorage(cb) {+ const listener = (ev: StorageEvent) => cb(ev.key, ev.newValue);+ window.addEventListener("storage", listener);+ return () => window.removeEventListener("storage", listener);+ },+ nextNonce: () => `${Date.now()}-${counter++}`,+ });+ }+ return createNoopChannel();+}++// ---------------------------------------------------------------------------+// Browser coordinator (one leader lease + one channel per company)+// ---------------------------------------------------------------------------++export interface SharedPollingSnapshot {+ isLeader: boolean;+}++export type SharedPollingListener = (snapshot: SharedPollingSnapshot) => void;+export type SharedPollingResourceListener = (message: SharedMessage) => void;++export interface SharedPollingCoordinatorOptions {+ tabId?: string;+ channel?: SharedChannel;+ election?: LeaderElection;+ leaseTtlMs?: number;+ tickMs?: number;+ now?: () => number;+ getVisible?: () => boolean;+}++const DEFAULT_COORDINATOR_TICK_MS = 1_000;+const TAB_ID_STORAGE_KEY = "paperclip:shared-poll:tab-id";++function sanitizeCompanyId(companyId: string): string {+ return encodeURIComponent(companyId);+}++export function sharedPollingLeaseKey(companyId: string): string {+ return `paperclip:shared-poll:${sanitizeCompanyId(companyId)}:leader`;+}++export function sharedPollingChannelName(companyId: string): string {+ return `paperclip:shared-poll:${sanitizeCompanyId(companyId)}`;+}++export function getSharedPollingTabId(): string {+ if (typeof sessionStorage !== "undefined") {+ try {+ const existing = sessionStorage.getItem(TAB_ID_STORAGE_KEY);+ if (existing) return existing;+ const next = createRandomId();+ sessionStorage.setItem(TAB_ID_STORAGE_KEY, next);+ return next;+ } catch {+ /* fall through */+ }+ }+ return createRandomId();+}++function createRandomId(): string {+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {+ return crypto.randomUUID();+ }+ return `tab-${Date.now()}-${Math.random().toString(36).slice(2)}`;+}++function getBrowserVisible(): boolean {+ if (typeof document === "undefined") return true;+ return document.visibilityState === "visible";+}++function createBrowserLeaseStore(companyId: string): LeaseStore | null {+ if (typeof localStorage === "undefined") return null;+ try {+ const probeKey = `paperclip:shared-poll:${sanitizeCompanyId(companyId)}:probe`;+ localStorage.setItem(probeKey, "1");+ localStorage.removeItem(probeKey);+ } catch {+ return null;+ }+ return createLeaseStore(localStorage, sharedPollingLeaseKey(companyId));+}++/**+ * Per-company coordinator that owns one lease election and one result channel.+ * Multiple query hooks in the same tab share the same coordinator via a registry+ * in `useSharedPolling`, so unmounting one component does not release leadership+ * while another shared query is still active in the tab.+ */+export class SharedPollingCoordinator {+ readonly tabId: string;+ private readonly channel: SharedChannel;+ private readonly election: LeaderElection;+ private readonly localOnlyFallback: boolean;+ private readonly tickMs: number;+ private readonly getVisible: () => boolean;+ private readonly listeners = new Set<SharedPollingListener>();+ private readonly resourceListeners = new Map<string, Set<SharedPollingResourceListener>>();+ private readonly latestResults = new Map<string, SharedMessage>();+ private unsubscribeChannel: (() => void) | null = null;+ private intervalId: ReturnType<typeof setInterval> | null = null;+ private releaseListeners: Array<() => void> = [];+ private snapshot: SharedPollingSnapshot = { isLeader: false };++ constructor(companyId: string, options: SharedPollingCoordinatorOptions = {}) {+ this.tabId = options.tabId ?? getSharedPollingTabId();+ this.channel = options.channel ?? createSharedChannel(sharedPollingChannelName(companyId));+ this.tickMs = options.tickMs ?? DEFAULT_COORDINATOR_TICK_MS;+ this.getVisible = options.getVisible ?? getBrowserVisible;+ const leaseStore = createBrowserLeaseStore(companyId);+ this.localOnlyFallback = !options.election && !leaseStore;+ this.election = options.election ?? new LeaderElection(+ {+ now: options.now ?? (() => Date.now()),+ store: leaseStore ?? {+ read: () => null,+ write: () => {},+ clear: () => {},+ },+ },+ {+ tabId: this.tabId,+ leaseTtlMs: options.leaseTtlMs,+ },+ );+ }++ getSnapshot(): SharedPollingSnapshot {+ return this.snapshot;+ }++ start(): void {+ if (this.intervalId != null) return;+ this.unsubscribeChannel = this.channel.subscribe((message) => this.handleMessage(message));+ this.tick();+ this.intervalId = setInterval(() => this.tick(), this.tickMs);+ this.attachReleaseListeners();+ }++ stop(): void {+ if (this.intervalId != null) {+ clearInterval(this.intervalId);+ this.intervalId = null;+ }+ this.unsubscribeChannel?.();+ this.unsubscribeChannel = null;+ for (const release of this.releaseListeners) release();+ this.releaseListeners = [];+ this.election.release();+ this.channel.close();+ this.setSnapshot({ isLeader: false });+ }++ subscribe(listener: SharedPollingListener): () => void {+ this.listeners.add(listener);+ listener(this.snapshot);+ return () => {+ this.listeners.delete(listener);+ };+ }++ subscribeResource(key: string, listener: SharedPollingResourceListener): () => void {+ let listeners = this.resourceListeners.get(key);+ if (!listeners) {+ listeners = new Set();+ this.resourceListeners.set(key, listeners);+ }+ listeners.add(listener);+ const latest = this.latestResults.get(key);+ if (latest) listener(latest);+ return () => {+ listeners?.delete(listener);+ if (listeners?.size === 0) this.resourceListeners.delete(key);+ };+ }++ request(key: string): void {+ this.channel.post({+ type: "request",+ key,+ from: this.tabId,+ at: Date.now(),+ });+ }++ publish(key: string, data: unknown): void {+ if (!this.snapshot.isLeader) return;+ const message: SharedMessage = {+ type: "result",+ key,+ from: this.tabId,+ at: Date.now(),+ data,+ };+ this.latestResults.set(key, message);+ this.channel.post(message);+ }++ private tick(): void {+ if (this.localOnlyFallback) {+ this.setSnapshot({ isLeader: this.getVisible() });+ return;+ }+ const role = this.election.step(this.getVisible());+ this.setSnapshot({ isLeader: role === "leader" });+ }++ private handleMessage(message: SharedMessage): void {+ if (message.from === this.tabId) return;+ if (message.type === "request") {+ if (!this.snapshot.isLeader) return;+ const latest = this.latestResults.get(message.key);+ if (latest) this.channel.post({ ...latest, from: this.tabId, at: Date.now() });+ return;+ }++ this.latestResults.set(message.key, message);+ const listeners = this.resourceListeners.get(message.key);+ if (!listeners) return;+ for (const listener of listeners) listener(message);+ }++ private setSnapshot(snapshot: SharedPollingSnapshot): void {+ if (snapshot.isLeader === this.snapshot.isLeader) return;+ this.snapshot = snapshot;+ for (const listener of this.listeners) listener(snapshot);+ }++ private attachReleaseListeners(): void {+ if (typeof window === "undefined" || this.releaseListeners.length > 0) return;+ const release = () => this.election.release();+ const visibilityChanged = () => this.tick();+ window.addEventListener("pagehide", release);+ window.addEventListener("beforeunload", release);+ window.addEventListener("visibilitychange", visibilityChanged);+ this.releaseListeners = [+ () => window.removeEventListener("pagehide", release),+ () => window.removeEventListener("beforeunload", release),+ () => window.removeEventListener("visibilitychange", visibilityChanged),+ ];+ }+}diff --git a/ui/src/lib/issueDetailCache.ts b/ui/src/lib/issueDetailCache.tsindex 696657c8e2..482fee82c5 100644--- a/ui/src/lib/issueDetailCache.ts+++ b/ui/src/lib/issueDetailCache.ts@@ -107,8 +107,9 @@ export function seedIssueDetailCache(export async function fetchIssueDetail(queryClient: QueryClient,issueRef: string,+ options?: { signal?: AbortSignal },): Promise<Issue> {- const issue = await issuesApi.get(issueRef);+ const issue = options ? await issuesApi.get(issueRef, options) : await issuesApi.get(issueRef);return seedIssueDetailCache(queryClient, issue, { issueRef });}@@ -121,7 +122,7 @@ export function getIssueDetailQueryOptions() {return {queryKey: queryKeys.issues.detail(issueRef),- queryFn: () => fetchIssueDetail(queryClient, issueRef),+ queryFn: ({ signal }: { signal?: AbortSignal }) => fetchIssueDetail(queryClient, issueRef, { signal }),placeholderData: getCachedIssueDetail(queryClient, issueRef, options?.placeholderIssue ?? undefined),};}diff --git a/ui/src/lib/issueDetailQuery.test.tsx b/ui/src/lib/issueDetailQuery.test.tsxindex 0f70f5bc6c..7442ee7c4e 100644--- a/ui/src/lib/issueDetailQuery.test.tsx+++ b/ui/src/lib/issueDetailQuery.test.tsx@@ -119,7 +119,9 @@ describe("getIssueDetailQueryOptions", () => {await flush();- expect(issuesApi.get).toHaveBeenCalledWith("PAP-1442");+ expect(issuesApi.get).toHaveBeenCalledWith("PAP-1442", {+ signal: expect.any(AbortSignal),+ });expect(container.textContent).toContain("GitHub Security Advisory body");await act(async () => {diff --git a/ui/src/lib/page-visibility.test.ts b/ui/src/lib/page-visibility.test.tsnew file mode 100644index 0000000000..0abd9ce984--- /dev/null+++ b/ui/src/lib/page-visibility.test.ts@@ -0,0 +1,84 @@+// @vitest-environment jsdom++import { afterEach, describe, expect, it, vi } from "vitest";+import {+ getPageVisibility,+ getVisibilityHeaderValue,+ subscribePageVisibility,+} from "./page-visibility";++function setVisibility(state: "visible" | "hidden") {+ Object.defineProperty(document, "visibilityState", {+ configurable: true,+ get: () => state,+ });+}++function setFocused(focused: boolean) {+ vi.spyOn(document, "hasFocus").mockReturnValue(focused);+}++afterEach(() => {+ vi.restoreAllMocks();+ setVisibility("visible");+});++describe("getPageVisibility", () => {+ it("reports hidden when the document is not visible", () => {+ setVisibility("hidden");+ expect(getPageVisibility()).toEqual({ visible: false, focused: false });+ });++ it("reports visible but unfocused when on-screen without focus", () => {+ setVisibility("visible");+ setFocused(false);+ expect(getPageVisibility()).toEqual({ visible: true, focused: false });+ });++ it("reports focused when visible and focused", () => {+ setVisibility("visible");+ setFocused(true);+ expect(getPageVisibility()).toEqual({ visible: true, focused: true });+ });+});++describe("getVisibilityHeaderValue", () => {+ it("maps states to non-authoritative header hints", () => {+ expect(getVisibilityHeaderValue({ visible: false, focused: false })).toBe("hidden");+ expect(getVisibilityHeaderValue({ visible: true, focused: false })).toBe("visible");+ expect(getVisibilityHeaderValue({ visible: true, focused: true })).toBe("focused");+ });+});++describe("subscribePageVisibility", () => {+ it("notifies subscribers on visibility transitions and cleans up", () => {+ setVisibility("visible");+ setFocused(true);+ const listener = vi.fn();+ const unsubscribe = subscribePageVisibility(listener);++ setVisibility("hidden");+ document.dispatchEvent(new Event("visibilitychange"));+ expect(listener).toHaveBeenCalledTimes(1);++ setVisibility("visible");+ document.dispatchEvent(new Event("visibilitychange"));+ expect(listener).toHaveBeenCalledTimes(2);++ unsubscribe();+ setVisibility("hidden");+ document.dispatchEvent(new Event("visibilitychange"));+ expect(listener).toHaveBeenCalledTimes(2);+ });++ it("does not notify when the state is unchanged", () => {+ setVisibility("visible");+ setFocused(true);+ const listener = vi.fn();+ const unsubscribe = subscribePageVisibility(listener);+ // Same state → no notification.+ document.dispatchEvent(new Event("visibilitychange"));+ expect(listener).not.toHaveBeenCalled();+ unsubscribe();+ });+});diff --git a/ui/src/lib/page-visibility.ts b/ui/src/lib/page-visibility.tsnew file mode 100644index 0000000000..d81beea654--- /dev/null+++ b/ui/src/lib/page-visibility.ts@@ -0,0 +1,105 @@+import { useSyncExternalStore } from "react";++/**+ * Page-visibility helpers for restore-storm mitigation (PAP-12556 / Phase 1).+ *+ * A tab can be in one of three practical states that matter for polling:+ * - hidden: `document.visibilityState !== "visible"` — the user is not looking at it.+ * - visible: on screen but not the focused window (e.g. split-screen, another window on top).+ * - focused: visible AND `document.hasFocus()` — the tab the user is actively using.+ *+ * The distinction matters because the UX guidance (PAP-12552 §6, "active-tab exemption")+ * requires the focused tab to keep near-normal cadence and minimal jitter, while merely+ * restored/background tabs may slow down and jitter widely. Header value is a+ * non-authoritative observability hint only — never a security signal.+ */++export interface PageVisibility {+ /** `document.visibilityState === "visible"`. */+ visible: boolean;+ /** Visible AND the document currently has focus. */+ focused: boolean;+}++const HIDDEN: PageVisibility = { visible: false, focused: false };++export function getPageVisibility(): PageVisibility {+ if (typeof document === "undefined") {+ // SSR / non-browser: treat as focused so data loads normally.+ return { visible: true, focused: true };+ }+ const visible = document.visibilityState === "visible";+ if (!visible) return HIDDEN;+ const focused = typeof document.hasFocus === "function" ? document.hasFocus() : true;+ return { visible: true, focused };+}++/** Stable header value for `X-Paperclip-Tab-Visible`: "focused" | "visible" | "hidden". */+export function getVisibilityHeaderValue(state: PageVisibility = getPageVisibility()): string {+ if (!state.visible) return "hidden";+ return state.focused ? "focused" : "visible";+}++// --- Shared subscription (single set of DOM listeners for all consumers) ---++const listeners = new Set<() => void>();+let cached: PageVisibility = getPageVisibility();+let attached = false;++function sameState(a: PageVisibility, b: PageVisibility): boolean {+ return a.visible === b.visible && a.focused === b.focused;+}++function recompute() {+ const next = getPageVisibility();+ if (sameState(next, cached)) return;+ cached = next;+ for (const listener of listeners) listener();+}++function attach() {+ if (attached || typeof document === "undefined") return;+ attached = true;+ document.addEventListener("visibilitychange", recompute);+ window.addEventListener("focus", recompute);+ window.addEventListener("blur", recompute);+ window.addEventListener("pageshow", recompute);+}++function detach() {+ if (!attached || typeof document === "undefined") return;+ attached = false;+ document.removeEventListener("visibilitychange", recompute);+ window.removeEventListener("focus", recompute);+ window.removeEventListener("blur", recompute);+ window.removeEventListener("pageshow", recompute);+}++/** Subscribe to visibility/focus transitions. Returns an unsubscribe fn. */+export function subscribePageVisibility(listener: () => void): () => void {+ listeners.add(listener);+ attach();+ // Re-sync in case state changed between last recompute and subscription.+ cached = getPageVisibility();+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0) detach();+ };+}++/** Snapshot for `useSyncExternalStore` — returns a referentially-stable object between changes. */+export function getPageVisibilitySnapshot(): PageVisibility {+ return cached;+}++function getServerSnapshot(): PageVisibility {+ return { visible: true, focused: true };+}++/**+ * React hook returning the current `{ visible, focused }` state, re-rendering on transitions.+ * Backed by a single shared set of DOM listeners regardless of how many components subscribe.+ */+export function usePageVisibility(): PageVisibility {+ return useSyncExternalStore(subscribePageVisibility, getPageVisibilitySnapshot, getServerSnapshot);+}diff --git a/ui/src/lib/polling.test.ts b/ui/src/lib/polling.test.tsnew file mode 100644index 0000000000..d483dc2608--- /dev/null+++ b/ui/src/lib/polling.test.ts@@ -0,0 +1,104 @@+import { describe, expect, it } from "vitest";+import {+ BACKGROUND_JITTER_MAX_MS,+ FOCUSED_JITTER_MAX_MS,+ computeStartupJitterMs,+ jitterBoundForVisibility,+ resolvePollingInterval,+} from "./polling";++describe("resolvePollingInterval", () => {+ it("polls at the visible cadence when focused", () => {+ expect(+ resolvePollingInterval({ visible: true, focused: true }, { visibleMs: 5000 }),+ ).toBe(5000);+ });++ it("falls back to visibleMs when visible but unfocused and no unfocusedMs given", () => {+ expect(+ resolvePollingInterval({ visible: true, focused: false }, { visibleMs: 5000 }),+ ).toBe(5000);+ });++ it("uses unfocusedMs for a visible-but-unfocused tab when provided", () => {+ expect(+ resolvePollingInterval(+ { visible: true, focused: false },+ { visibleMs: 5000, unfocusedMs: 15000 },+ ),+ ).toBe(15000);+ });++ it("stops polling when hidden by default", () => {+ expect(+ resolvePollingInterval({ visible: false, focused: false }, { visibleMs: 5000 }),+ ).toBe(false);+ });++ it("slows polling when hidden if hiddenMs is provided", () => {+ expect(+ resolvePollingInterval(+ { visible: false, focused: false },+ { visibleMs: 5000, hiddenMs: 60000 },+ ),+ ).toBe(60000);+ });+});++describe("computeStartupJitterMs", () => {+ it("returns 0 when maxMs <= 0", () => {+ expect(computeStartupJitterMs(0, () => 0.5)).toBe(0);+ expect(computeStartupJitterMs(-100, () => 0.5)).toBe(0);+ });++ it("scales the rng value into [0, maxMs]", () => {+ expect(computeStartupJitterMs(1000, () => 0)).toBe(0);+ expect(computeStartupJitterMs(1000, () => 0.25)).toBe(250);+ expect(computeStartupJitterMs(1000, () => 0.999999)).toBe(1000);+ });++ it("clamps rng values outside [0, 1)", () => {+ expect(computeStartupJitterMs(1000, () => -1)).toBe(0);+ expect(computeStartupJitterMs(1000, () => 5)).toBe(1000);+ });++ it("never exceeds the bound for a focused tab", () => {+ for (const r of [0, 0.3, 0.7, 0.9999]) {+ const jitter = computeStartupJitterMs(FOCUSED_JITTER_MAX_MS, () => r);+ expect(jitter).toBeGreaterThanOrEqual(0);+ expect(jitter).toBeLessThanOrEqual(FOCUSED_JITTER_MAX_MS);+ }+ });+});++describe("jitterBoundForVisibility", () => {+ it("uses the small focused bound for a focused tab", () => {+ expect(jitterBoundForVisibility({ visible: true, focused: true })).toBe(+ FOCUSED_JITTER_MAX_MS,+ );+ });++ it("uses the wider background bound for a hidden or unfocused tab", () => {+ expect(jitterBoundForVisibility({ visible: false, focused: false })).toBe(+ BACKGROUND_JITTER_MAX_MS,+ );+ expect(jitterBoundForVisibility({ visible: true, focused: false })).toBe(+ BACKGROUND_JITTER_MAX_MS,+ );+ });++ it("respects custom bounds", () => {+ expect(+ jitterBoundForVisibility(+ { visible: true, focused: true },+ { focusedMaxMs: 100, backgroundMaxMs: 9000 },+ ),+ ).toBe(100);+ expect(+ jitterBoundForVisibility(+ { visible: false, focused: false },+ { focusedMaxMs: 100, backgroundMaxMs: 9000 },+ ),+ ).toBe(9000);+ });+});diff --git a/ui/src/lib/polling.ts b/ui/src/lib/polling.tsnew file mode 100644index 0000000000..80ad1c0629--- /dev/null+++ b/ui/src/lib/polling.ts@@ -0,0 +1,135 @@+import { useMemo, useRef } from "react";+import { getPageVisibility, usePageVisibility, type PageVisibility } from "./page-visibility";++/**+ * Polling-cadence and startup-jitter helpers for restore-storm mitigation+ * (PAP-12556 / Phase 1). See PAP-12552 UX guidance §2/§6.+ *+ * Goals:+ * - Visible+focused tabs poll at their normal cadence (active-tab exemption).+ * - Merely-visible-but-unfocused tabs may poll a little slower.+ * - Hidden tabs poll slowly or not at all.+ * - Restored tabs add a small, bounded, randomized jitter so a whole restored+ * window doesn't fire every poller on the same millisecond.+ *+ * Jitter is a herd-breaking tool, not a user-facing delay: content is already on+ * screen from cache (stale-while-revalidate), so jitter never gates first paint.+ */++/** Default bound for jitter added to a focused tab's first poll (ms). */+export const FOCUSED_JITTER_MAX_MS = 250;+/** Default bound for jitter added on background / restored tabs (ms). */+export const BACKGROUND_JITTER_MAX_MS = 3_000;++export interface PollingIntervalOptions {+ /** Interval when the tab is visible AND focused. Required. */+ visibleMs: number;+ /**+ * Interval when visible but not focused. Defaults to `visibleMs`+ * (keep near-normal cadence for on-screen tabs).+ */+ unfocusedMs?: number;+ /**+ * Interval when hidden. `false` (default) stops polling entirely while hidden;+ * react-query also pauses interval timers for hidden tabs, so this is defence in depth.+ */+ hiddenMs?: number | false;+}++/**+ * Pure resolver: given a visibility state and cadence options, return the react-query+ * `refetchInterval` value (`number` to poll, `false` to pause).+ */+export function resolvePollingInterval(+ state: PageVisibility,+ options: PollingIntervalOptions,+): number | false {+ if (!state.visible) return options.hiddenMs ?? false;+ if (state.focused) return options.visibleMs;+ return options.unfocusedMs ?? options.visibleMs;+}++/**+ * Pure jitter calculator. `rng` returns a float in [0, 1) (injectable for tests).+ * Result is clamped to `[0, maxMs]` and rounded to an integer number of ms.+ */+export function computeStartupJitterMs(maxMs: number, rng: () => number): number {+ if (maxMs <= 0) return 0;+ const clamped = Math.min(Math.max(rng(), 0), 0.999999);+ return Math.round(clamped * maxMs);+}++/**+ * Pick the appropriate jitter bound for the current visibility: small for a focused+ * tab (don't make active use feel laggy), wider for background/restored tabs.+ */+export function jitterBoundForVisibility(+ state: PageVisibility,+ opts?: { focusedMaxMs?: number; backgroundMaxMs?: number },+): number {+ const focusedMax = opts?.focusedMaxMs ?? FOCUSED_JITTER_MAX_MS;+ const backgroundMax = opts?.backgroundMaxMs ?? BACKGROUND_JITTER_MAX_MS;+ return state.focused ? focusedMax : backgroundMax;+}++export interface VisibilityRefetchOptions extends PollingIntervalOptions {+ /**+ * Add a small, stable, per-mount jitter to the active interval so a window full of+ * restored tabs doesn't fire the same poller on the same millisecond. Defaults to+ * true. The jitter is computed once at mount (so react-query is not rescheduled on+ * every render) and is bounded to `min(jitterMaxMs, visibleMs * 0.2)`.+ */+ jitter?: boolean;+ /** Upper bound for the polling jitter (ms). Default 1000. */+ jitterMaxMs?: number;+}++/**+ * React hook: a visibility-aware `refetchInterval` value for react-query.+ * Re-renders (and thus reschedules the query) when visibility/focus changes, but the+ * de-phasing jitter is fixed per mount so the scheduler is not thrashed.+ *+ * Usage:+ * const refetchInterval = useVisibilityRefetchInterval({ visibleMs: 5000 });+ * useQuery({ ..., refetchInterval });+ */+export function useVisibilityRefetchInterval(options: VisibilityRefetchOptions): number | false {+ const state = usePageVisibility();+ const jitterRef = useRef<number | null>(null);+ if (jitterRef.current === null) {+ if (options.jitter === false) {+ jitterRef.current = 0;+ } else {+ const bound = Math.min(options.jitterMaxMs ?? 1_000, Math.round(options.visibleMs * 0.2));+ jitterRef.current = computeStartupJitterMs(bound, Math.random);+ }+ }+ const jitter = jitterRef.current;+ return useMemo(() => {+ const base = resolvePollingInterval(state, options);+ return base === false ? false : base + jitter;+ // Options are typically inline literals; depend on their primitive fields.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [state, options.visibleMs, options.unfocusedMs, options.hiddenMs, jitter]);+}++/**+ * React hook returning a stable, bounded startup-jitter delay (ms), computed once+ * per mount from the visibility state at mount time. Use to stagger a non-critical+ * refresh after restore, e.g. gate an `enabled` flag or delay an initial refetch.+ *+ * The value is memoised so it does not change on every render (which would defeat+ * the purpose and thrash timers).+ */+export function useStartupJitterMs(opts?: {+ focusedMaxMs?: number;+ backgroundMaxMs?: number;+}): number {+ const ref = useRef<number | null>(null);+ if (ref.current === null) {+ const state = getPageVisibility();+ const bound = jitterBoundForVisibility(state, opts);+ ref.current = computeStartupJitterMs(bound, Math.random);+ }+ return ref.current;+}diff --git a/ui/src/pages/Agents.tsx b/ui/src/pages/Agents.tsxindex 558076ec50..1c49314fcd 100644--- a/ui/src/pages/Agents.tsx+++ b/ui/src/pages/Agents.tsx@@ -31,6 +31,7 @@ import {useResourceMembershipMutation,useResourceMemberships,} from "../hooks/useResourceMemberships";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";import { getAdapterLabel } from "../adapters/adapter-display-registry";@@ -251,12 +252,22 @@ export function Agents() {enabled: !!selectedCompanyId && environmentsEnabled,});- const { data: runs } = useQuery({- queryKey: [...queryKeys.liveRuns(selectedCompanyId!), "agents-page"],- queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ const runsQueryKey = [...queryKeys.liveRuns(selectedCompanyId!), "agents-page"] as const;+ const sharedRuns = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "live-runs:agents-page",+ queryKey: runsQueryKey,enabled: !!selectedCompanyId,refetchInterval: 15_000,+ leaderOnly: true,+ });+ const { data: runs, dataUpdatedAt: runsUpdatedAt } = useQuery({+ queryKey: runsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ enabled: sharedRuns.enabled,+ refetchInterval: sharedRuns.refetchInterval,});+ usePublishSharedQueryData(sharedRuns, runs, runsUpdatedAt);const membershipsQuery = useResourceMemberships(selectedCompanyId);const membershipMutation = useResourceMembershipMutation(selectedCompanyId);diff --git a/ui/src/pages/Dashboard.tsx b/ui/src/pages/Dashboard.tsxindex 577f8aac10..8f6533a50f 100644--- a/ui/src/pages/Dashboard.tsx+++ b/ui/src/pages/Dashboard.tsx@@ -15,6 +15,7 @@ import { queryKeys } from "../lib/queryKeys";import { MetricCard } from "../components/MetricCard";import { EmptyState } from "../components/EmptyState";import { StatusIcon } from "../components/StatusIcon";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";import { ActivityRow } from "../components/ActivityRow";import { Identity } from "../components/Identity";@@ -54,17 +55,33 @@ export function Dashboard() {setBreadcrumbs([{ label: "Dashboard" }]);}, [setBreadcrumbs]);- const { data, isLoading, error } = useQuery({- queryKey: queryKeys.dashboard(selectedCompanyId!),+ const dashboardQueryKey = queryKeys.dashboard(selectedCompanyId!);+ const sharedDashboard = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "dashboard",+ queryKey: dashboardQueryKey,+ enabled: !!selectedCompanyId,+ });+ const { data, isLoading, error, dataUpdatedAt: dashboardUpdatedAt } = useQuery({+ queryKey: dashboardQueryKey,queryFn: () => dashboardApi.summary(selectedCompanyId!),enabled: !!selectedCompanyId,});+ usePublishSharedQueryData(sharedDashboard, data, dashboardUpdatedAt);- const { data: activity } = useQuery({- queryKey: [...queryKeys.activity(selectedCompanyId!), { limit: DASHBOARD_ACTIVITY_LIMIT }],+ const activityQueryKey = [...queryKeys.activity(selectedCompanyId!), { limit: DASHBOARD_ACTIVITY_LIMIT }] as const;+ const sharedActivity = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: `activity:limit:${DASHBOARD_ACTIVITY_LIMIT}`,+ queryKey: activityQueryKey,+ enabled: !!selectedCompanyId,+ });+ const { data: activity, dataUpdatedAt: activityUpdatedAt } = useQuery({+ queryKey: activityQueryKey,queryFn: () => activityApi.list(selectedCompanyId!, { limit: DASHBOARD_ACTIVITY_LIMIT }),enabled: !!selectedCompanyId,});+ usePublishSharedQueryData(sharedActivity, activity, activityUpdatedAt);const { data: issues } = useQuery({queryKey: queryKeys.issues.list(selectedCompanyId!),diff --git a/ui/src/pages/ExecutionWorkspaceDetail.tsx b/ui/src/pages/ExecutionWorkspaceDetail.tsxindex 3e6445f7ef..7c01d66526 100644--- a/ui/src/pages/ExecutionWorkspaceDetail.tsx+++ b/ui/src/pages/ExecutionWorkspaceDetail.tsx@@ -20,6 +20,7 @@ import { projectsApi } from "../api/projects";import { routinesApi } from "../api/routines";import { IssuesList } from "../components/IssuesList";import { PageTabBar } from "../components/PageTabBar";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";import { PluginSlotMount, PluginSlotOutlet, usePluginSlots } from "@/plugins/slots";import {RoutineRunVariablesDialog,@@ -341,12 +342,22 @@ function ExecutionWorkspaceIssuesList({enabled: !!companyId,});- const { data: liveRuns } = useQuery({- queryKey: queryKeys.liveRuns(companyId),- queryFn: () => heartbeatsApi.liveRunsForCompany(companyId),+ const liveRunsQueryKey = queryKeys.liveRuns(companyId);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,enabled: !!companyId,refetchInterval: 5000,+ leaderOnly: true,+ });+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(companyId),+ enabled: sharedLiveRuns.enabled,+ refetchInterval: sharedLiveRuns.refetchInterval,});+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns), [liveRuns]);diff --git a/ui/src/pages/Inbox.test.tsx b/ui/src/pages/Inbox.test.tsxindex 1bcbb4958d..43f17f7be9 100644--- a/ui/src/pages/Inbox.test.tsx+++ b/ui/src/pages/Inbox.test.tsx@@ -62,6 +62,7 @@ vi.mock("../api/execution-workspaces", () => ({vi.mock("../api/issues", () => ({issuesApi: {list: apiMocks.issuesList,+ listCompact: apiMocks.issuesList,count: apiMocks.issuesCount,listLabels: apiMocks.issueLabels,markRead: vi.fn(),@@ -376,6 +377,11 @@ describe("Inbox toolbar", () => {true,true,]);+ expect(apiMocks.issuesList.mock.calls.map((call) => call[1]?.limit)).toEqual([+ 500,+ 500,+ 500,+ ]);act(() => {root.unmount();diff --git a/ui/src/pages/Inbox.tsx b/ui/src/pages/Inbox.tsxindex eea754d8bc..7fee7da241 100644--- a/ui/src/pages/Inbox.tsx+++ b/ui/src/pages/Inbox.tsx@@ -2,6 +2,8 @@ import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } froimport { Link, useLocation, useNavigate } from "@/lib/router";import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { deriveOriginatingActor, INBOX_MINE_ISSUE_STATUS_FILTER } from "@paperclipai/shared";+import { useVisibilityRefetchInterval } from "@/lib/polling";+import { usePublishSharedQueryData, useSharedPollingQuery } from "@/hooks/useSharedPolling";import { approvalsApi } from "../api/approvals";import { accessApi } from "../api/access";import { authApi } from "../api/auth";@@ -809,59 +811,93 @@ export function Inbox() {retry: false,});- const { data: dashboard, isLoading: isDashboardLoading } = useQuery({- queryKey: queryKeys.dashboard(selectedCompanyId!),+ const dashboardQueryKey = queryKeys.dashboard(selectedCompanyId!);+ const sharedDashboard = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "dashboard",+ queryKey: dashboardQueryKey,+ enabled: !!selectedCompanyId,+ });+ const { data: dashboard, isLoading: isDashboardLoading, dataUpdatedAt: dashboardUpdatedAt } = useQuery({+ queryKey: dashboardQueryKey,queryFn: () => dashboardApi.summary(selectedCompanyId!),enabled: !!selectedCompanyId,});+ usePublishSharedQueryData(sharedDashboard, dashboard, dashboardUpdatedAt);- const { data: issues, isLoading: isIssuesLoading } = useQuery({- queryKey: [...queryKeys.issues.list(selectedCompanyId!), "with-routine-executions", "live-descendant-summary"],+ const inboxIssuesQueryKey = [...queryKeys.issues.list(selectedCompanyId!), "compact", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT] as const;+ const sharedInboxIssues = useSharedPollingQuery<Issue[]>({+ companyId: selectedCompanyId,+ resourceKey: "inbox:issues",+ queryKey: inboxIssuesQueryKey,+ enabled: !!selectedCompanyId,+ });+ const { data: issues, isLoading: isIssuesLoading, dataUpdatedAt: issuesUpdatedAt } = useQuery({+ queryKey: inboxIssuesQueryKey,queryFn: () =>- issuesApi.list(selectedCompanyId!, {+ issuesApi.listCompact(selectedCompanyId!, {includeRoutineExecutions: true,includeLiveDescendantSummary: true,limit: INBOX_ISSUE_LIST_LIMIT,- }),+ }).then((rows) => rows as Issue[]),enabled: !!selectedCompanyId,refetchOnWindowFocus: false,staleTime: INBOX_HOT_PATH_STALE_MS,});+ usePublishSharedQueryData(sharedInboxIssues, issues, issuesUpdatedAt);const {data: mineIssuesRaw = [],isLoading: isMineIssuesLoading,+ dataUpdatedAt: mineIssuesUpdatedAt,} = useQuery({- queryKey: [...queryKeys.issues.listMineByMe(selectedCompanyId!), "with-routine-executions", "live-descendant-summary"],+ queryKey: [...queryKeys.issues.listMineByMe(selectedCompanyId!), "compact", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT] as const,queryFn: () =>- issuesApi.list(selectedCompanyId!, {+ issuesApi.listCompact(selectedCompanyId!, {touchedByUserId: "me",inboxArchivedByUserId: "me",status: INBOX_MINE_ISSUE_STATUS_FILTER,includeRoutineExecutions: true,includeLiveDescendantSummary: true,limit: INBOX_ISSUE_LIST_LIMIT,- }),+ }).then((rows) => rows as Issue[]),enabled: !!selectedCompanyId,refetchOnWindowFocus: false,staleTime: INBOX_HOT_PATH_STALE_MS,});+ const mineIssuesQueryKey = [...queryKeys.issues.listMineByMe(selectedCompanyId!), "compact", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT] as const;+ const sharedMineIssues = useSharedPollingQuery<Issue[]>({+ companyId: selectedCompanyId,+ resourceKey: "inbox:mine-issues",+ queryKey: mineIssuesQueryKey,+ enabled: !!selectedCompanyId,+ });+ usePublishSharedQueryData(sharedMineIssues, mineIssuesRaw, mineIssuesUpdatedAt);const {data: touchedIssuesRaw = [],isLoading: isTouchedIssuesLoading,+ dataUpdatedAt: touchedIssuesUpdatedAt,} = useQuery({- queryKey: [...queryKeys.issues.listTouchedByMe(selectedCompanyId!), "with-routine-executions", "live-descendant-summary"],+ queryKey: [...queryKeys.issues.listTouchedByMe(selectedCompanyId!), "compact", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT] as const,queryFn: () =>- issuesApi.list(selectedCompanyId!, {+ issuesApi.listCompact(selectedCompanyId!, {touchedByUserId: "me",status: INBOX_MINE_ISSUE_STATUS_FILTER,includeRoutineExecutions: true,includeLiveDescendantSummary: true,limit: INBOX_ISSUE_LIST_LIMIT,- }),+ }).then((rows) => rows as Issue[]),enabled: !!selectedCompanyId,refetchOnWindowFocus: false,staleTime: INBOX_HOT_PATH_STALE_MS,});+ const touchedIssuesQueryKey = [...queryKeys.issues.listTouchedByMe(selectedCompanyId!), "compact", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT] as const;+ const sharedTouchedIssues = useSharedPollingQuery<Issue[]>({+ companyId: selectedCompanyId,+ resourceKey: "inbox:touched-issues",+ queryKey: touchedIssuesQueryKey,+ enabled: !!selectedCompanyId,+ });+ usePublishSharedQueryData(sharedTouchedIssues, touchedIssuesRaw, touchedIssuesUpdatedAt);const { data: heartbeatRuns, isLoading: isRunsLoading } = useQuery({queryKey: [...queryKeys.heartbeats(selectedCompanyId!), "limit", INBOX_HEARTBEAT_RUN_LIMIT],@@ -870,12 +906,23 @@ export function Inbox() {refetchOnWindowFocus: false,staleTime: INBOX_HOT_PATH_STALE_MS,});- const { data: liveRuns } = useQuery({- queryKey: queryKeys.liveRuns(selectedCompanyId!),- queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ const liveRunsRefetchInterval = useVisibilityRefetchInterval({ visibleMs: 5000 });+ const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,enabled: !!selectedCompanyId,- refetchInterval: 5000,+ refetchInterval: liveRunsRefetchInterval,+ leaderOnly: true,});+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ enabled: sharedLiveRuns.enabled,+ refetchInterval: sharedLiveRuns.refetchInterval,+ });+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns), [liveRuns]);const { data: companyMembers } = useQuery({queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),@@ -901,16 +948,17 @@ export function Inbox() {const { data: remoteIssueSearchResults = [] } = useQuery({queryKey: [...queryKeys.issues.search(selectedCompanyId!, normalizedSearchQuery, undefined, 25),+ "compact","inbox-supplement","live-descendant-summary",],queryFn: () =>- issuesApi.list(selectedCompanyId!, {+ issuesApi.listCompact(selectedCompanyId!, {q: normalizedSearchQuery,limit: 25,includeRoutineExecutions: true,includeLiveDescendantSummary: true,- }),+ }).then((rows) => rows as Issue[]),enabled: shouldUseIssueSearchSupplement,placeholderData: (previousData) => previousData,});diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsxindex fa016b4278..4c6be5c085 100644--- a/ui/src/pages/IssueDetail.tsx+++ b/ui/src/pages/IssueDetail.tsx@@ -2,6 +2,8 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState, type ChangeEveimport { pickTextColorForPillBg } from "@/lib/color-contrast";import { Link, useLocation, useNavigate, useNavigationType, useParams } from "@/lib/router";import { useInfiniteQuery, useQuery, useMutation, useQueryClient, type InfiniteData, type QueryClient } from "@tanstack/react-query";+import { useVisibilityRefetchInterval } from "@/lib/polling";+import { usePublishSharedQueryData, useSharedPollingQuery } from "@/hooks/useSharedPolling";import { ApiError } from "../api/client";import { issuesApi } from "../api/issues";import { approvalsApi } from "../api/approvals";@@ -1708,13 +1710,24 @@ export function IssueDetail() {queryFn: () => issuesApi.list(resolvedCompanyId!, { parentId: issue!.parentId!, includeBlockedBy: true }),enabled: !!resolvedCompanyId && !!issue?.parentId,});- const { data: companyLiveRuns } = useQuery({- queryKey: resolvedCompanyId ? queryKeys.liveRuns(resolvedCompanyId) : ["live-runs", "pending"],- queryFn: () => heartbeatsApi.liveRunsForCompany(resolvedCompanyId!),+ const companyLiveRunsRefetchInterval = useVisibilityRefetchInterval({ visibleMs: 5000 });+ const companyLiveRunsQueryKey = resolvedCompanyId ? queryKeys.liveRuns(resolvedCompanyId) : ["live-runs", "pending"] as const;+ const sharedCompanyLiveRuns = useSharedPollingQuery<LiveRunForIssue[]>({+ companyId: resolvedCompanyId,+ resourceKey: "live-runs",+ queryKey: companyLiveRunsQueryKey,enabled: !!resolvedCompanyId,- refetchInterval: 5000,+ refetchInterval: companyLiveRunsRefetchInterval,+ leaderOnly: true,+ });+ const { data: companyLiveRuns, dataUpdatedAt: companyLiveRunsUpdatedAt } = useQuery({+ queryKey: companyLiveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(resolvedCompanyId!),+ enabled: sharedCompanyLiveRuns.enabled,+ refetchInterval: sharedCompanyLiveRuns.refetchInterval,placeholderData: keepPreviousDataForSameQueryTail<LiveRunForIssue[]>(resolvedCompanyId ?? "pending"),});+ usePublishSharedQueryData(sharedCompanyLiveRuns, companyLiveRuns, companyLiveRunsUpdatedAt);const { data: agents } = useQuery({queryKey: queryKeys.agents.list(selectedCompanyId!),diff --git a/ui/src/pages/Issues.test.tsx b/ui/src/pages/Issues.test.tsxindex b959c86951..576a03b765 100644--- a/ui/src/pages/Issues.test.tsx+++ b/ui/src/pages/Issues.test.tsx@@ -22,13 +22,13 @@ describe("buildIssuesSearchUrl", () => {describe("issues page pagination helpers", () => {it("advances to the next offset when the current page is full", () => {- expect(getNextIssuesPageOffset(500, 0)).toBe(500);- expect(getNextIssuesPageOffset(500, 500)).toBe(1000);+ expect(getNextIssuesPageOffset(100, 0)).toBe(100);+ expect(getNextIssuesPageOffset(100, 100)).toBe(200);expect(getNextIssuesPageOffset(1000, 2000, 1000)).toBe(3000);});it("stops requesting issue pages when the current page is partial", () => {- expect(getNextIssuesPageOffset(499, 0)).toBeUndefined();+ expect(getNextIssuesPageOffset(99, 0)).toBeUndefined();expect(getNextIssuesPageOffset(999, 2000, 1000)).toBeUndefined();});diff --git a/ui/src/pages/Issues.tsx b/ui/src/pages/Issues.tsxindex d0be7d1d55..c523e6edfa 100644--- a/ui/src/pages/Issues.tsx+++ b/ui/src/pages/Issues.tsx@@ -8,6 +8,8 @@ import { heartbeatsApi } from "../api/heartbeats";import { useCompany } from "../context/CompanyContext";import { useBreadcrumbs } from "../context/BreadcrumbContext";import { collectLiveIssueIds } from "../lib/liveIssueIds";+import { useVisibilityRefetchInterval } from "@/lib/polling";+import { usePublishSharedQueryData, useSharedPollingQuery } from "@/hooks/useSharedPolling";import { queryKeys } from "../lib/queryKeys";import { createIssueDetailLocationState } from "../lib/issueDetailBreadcrumb";import { EmptyState } from "../components/EmptyState";@@ -16,7 +18,7 @@ import { CircleDot } from "lucide-react";import type { Issue } from "@paperclipai/shared";const WORKSPACE_FILTER_ISSUE_LIMIT = 1000;-const ISSUES_PAGE_SIZE = 500;+const ISSUES_PAGE_SIZE = 100;export function getNextIssuesPageOffset(loadedPageSize: number,@@ -26,9 +28,9 @@ export function getNextIssuesPageOffset(return loadedPageSize >= pageSize ? currentOffset + pageSize : undefined;}-export function mergeIssuePagesStable(pages: Issue[][]): Issue[] {+export function mergeIssuePagesStable<T extends { id: string }>(pages: T[][]): T[] {const seenIssueIds = new Set<string>();- const merged: Issue[] = [];+ const merged: T[] = [];for (const page of pages) {for (const issue of page) {@@ -96,12 +98,23 @@ export function Issues() {enabled: !!selectedCompanyId,});- const { data: liveRuns } = useQuery({- queryKey: queryKeys.liveRuns(selectedCompanyId!),- queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ const liveRunsRefetchInterval = useVisibilityRefetchInterval({ visibleMs: 5000 });+ const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,enabled: !!selectedCompanyId,- refetchInterval: 5000,+ refetchInterval: liveRunsRefetchInterval,+ leaderOnly: true,+ });+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ enabled: sharedLiveRuns.enabled,+ refetchInterval: sharedLiveRuns.refetchInterval,});+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns), [liveRuns]);@@ -135,11 +148,12 @@ export function Issues() {participantAgentId ?? "__all__","workspace",workspaceIdFilter ?? "__all__",+ "compact","with-routine-executions","infinite",issuePageSize,],- queryFn: ({ pageParam }) => issuesApi.list(selectedCompanyId!, {+ queryFn: ({ pageParam, signal }) => issuesApi.listCompact(selectedCompanyId!, {participantAgentId,workspaceId: workspaceIdFilter,includeRoutineExecutions: true,@@ -147,7 +161,7 @@ export function Issues() {offset: pageParam,sortField: "updated",sortDir: "desc",- }),+ }, { signal }),initialPageParam: 0,getNextPageParam: (lastPage, _allPages, lastPageParam) =>getNextIssuesPageOffset(lastPage.length, lastPageParam, issuePageSize),@@ -155,7 +169,7 @@ export function Issues() {placeholderData: (previousData) => previousData,});- const issues = useMemo(() => mergeIssuePagesStable(issuePages?.pages ?? []), [issuePages]);+ const issues = useMemo(() => mergeIssuePagesStable(issuePages?.pages ?? []) as Issue[], [issuePages]);const hasMoreServerIssues = syncedSearch.trim().length === 0&& hasNextPage === true;const loadMoreServerIssues = useCallback(() => {diff --git a/ui/src/pages/ProjectDetail.tsx b/ui/src/pages/ProjectDetail.tsxindex b9265a52fe..1c9b881bfd 100644--- a/ui/src/pages/ProjectDetail.tsx+++ b/ui/src/pages/ProjectDetail.tsx@@ -30,6 +30,7 @@ import { buildProjectWorkspaceSummaries } from "../lib/project-workspaces-tab";import { collectLiveIssueIds } from "../lib/liveIssueIds";import { projectRouteRef } from "../lib/utils";import { PROJECT_ICONS } from "../lib/project-icons";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";@@ -234,12 +235,22 @@ function ProjectIssuesList({ projectId, companyId }: { projectId: string; companenabled: !!companyId,});- const { data: liveRuns } = useQuery({- queryKey: queryKeys.liveRuns(companyId),- queryFn: () => heartbeatsApi.liveRunsForCompany(companyId),+ const liveRunsQueryKey = queryKeys.liveRuns(companyId);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,enabled: !!companyId,refetchInterval: 5000,+ leaderOnly: true,+ });+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(companyId),+ enabled: sharedLiveRuns.enabled,+ refetchInterval: sharedLiveRuns.refetchInterval,});+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const { data: projects } = useQuery({queryKey: queryKeys.projects.list(companyId),queryFn: () => projectsApi.list(companyId),@@ -300,12 +311,22 @@ function ProjectPluginOperationsList({queryFn: () => projectsApi.list(companyId),enabled: !!companyId,});- const { data: liveRuns } = useQuery({- queryKey: queryKeys.liveRuns(companyId),- queryFn: () => heartbeatsApi.liveRunsForCompany(companyId),+ const liveRunsQueryKey = queryKeys.liveRuns(companyId);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,enabled: !!companyId,refetchInterval: 5000,+ leaderOnly: true,+ });+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(companyId),+ enabled: sharedLiveRuns.enabled,+ refetchInterval: sharedLiveRuns.refetchInterval,});+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns), [liveRuns]);const { data: issues, isLoading, error } = useQuery({diff --git a/ui/src/pages/Routines.tsx b/ui/src/pages/Routines.tsxindex c57bb13fe3..837b6aac4f 100644--- a/ui/src/pages/Routines.tsx+++ b/ui/src/pages/Routines.tsx@@ -18,6 +18,7 @@ import { createIssueDetailLocationState } from "../lib/issueDetailBreadcrumb";import { collectLiveIssueIds } from "../lib/liveIssueIds";import { getRecentAssigneeIds, sortAgentsByRecency, trackRecentAssignee } from "../lib/recent-assignees";import { getRecentProjectIds, trackRecentProject } from "../lib/recent-projects";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";import { EmptyState } from "../components/EmptyState";import { IssuesList } from "../components/IssuesList";import { PageSkeleton } from "../components/PageSkeleton";@@ -335,12 +336,22 @@ export function Routines() {queryFn: () => issuesApi.list(selectedCompanyId!, { originKind: "routine_execution" }),enabled: !!selectedCompanyId && activeTab === "runs",});- const { data: liveRuns } = useQuery({- queryKey: queryKeys.liveRuns(selectedCompanyId!),- queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,enabled: !!selectedCompanyId && activeTab === "runs",refetchInterval: 5000,+ leaderOnly: true,+ });+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),+ enabled: sharedLiveRuns.enabled,+ refetchInterval: sharedLiveRuns.refetchInterval,});+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);useEffect(() => {autoResizeTextarea(titleInputRef.current);diff --git a/ui/src/plugins/bridge-init.ts b/ui/src/plugins/bridge-init.tsindex 0b46439c42..a279c5e0bd 100644--- a/ui/src/plugins/bridge-init.ts+++ b/ui/src/plugins/bridge-init.ts@@ -44,6 +44,7 @@ import {} from "@/lib/company-members";import { collectLiveIssueIds } from "@/lib/liveIssueIds";import { useProjectOrder } from "@/hooks/useProjectOrder";+import { usePublishSharedQueryData, useSharedPollingQuery } from "@/hooks/useSharedPolling";import {assigneeValueFromSelection,currentUserAssigneeOption,@@ -270,12 +271,22 @@ function PluginSdkIssuesList({queryFn: () => projectsApi.list(companyId!),enabled: !!companyId,});- const { data: liveRuns } = useQuery({- queryKey: queryKeys.liveRuns(companyId ?? "__no-company__"),- queryFn: () => heartbeatsApi.liveRunsForCompany(companyId!),+ const liveRunsQueryKey = queryKeys.liveRuns(companyId ?? "__no-company__");+ const sharedLiveRuns = useSharedPollingQuery({+ companyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,enabled: !!companyId,refetchInterval: 5000,+ leaderOnly: true,+ });+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({+ queryKey: liveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(companyId!),+ enabled: sharedLiveRuns.enabled,+ refetchInterval: sharedLiveRuns.refetchInterval,});+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns), [liveRuns]);const { data: issues, isLoading, error } = useQuery({