mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
fix(external-objects): refresh PR status labels (#10704)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The issue properties panel can show external objects such as GitHub pull requests. > - Those objects are resolved by external-object providers and then displayed as compact status labels. > - A GitHub pull request could remain in the fallback `unknown` state and appear as `Not yet resolved`. > - That label is confusing when the object is known but has not been refreshed yet. > - This pull request refreshes due external objects from the heartbeat scheduler and improves the unknown-status copy. > - The benefit is a properties panel that moves from pending refresh to the real pull request state without a manual refresh. ## Linked Issues or Issue Description No public GitHub issue exists for this bug. I searched for related public issues and pull requests using the terms `Not yet refreshed`, `external objects refresh`, and `external PR status`, and did not find a duplicate implementation. **What happened?** The issue properties panel could show a GitHub pull request as `Not yet resolved` even when the referenced pull request was valid. The object stayed stale unless a manual refresh path ran. **Expected behavior** A known external object should show pending-refresh copy while it waits for provider data. When the scheduler refreshes it, the properties panel should show the provider status such as open, merged, or closed. **Steps to reproduce** 1. Create or view an issue that references a GitHub pull request. 2. Open the issue properties panel. 3. Observe the external object row before a manual refresh has run. **Paperclip version or commit** Current `master` before this pull request. **Deployment mode** Local dev and self-hosted server. **Installation method** Built from source. **Agent adapter(s) involved** Not adapter-specific. **Database mode** Not database-related. **Access context** Board view. **Privacy checklist** I reviewed this description and did not include logs, credentials, private URLs, internal issue IDs, or PII. ## What Changed - Added a heartbeat scheduler tick that refreshes due external objects for active companies. - Kept manual external-object refresh behavior on the same service path. - Changed display copy so known provider objects use liveness labels such as `Not yet refreshed`, while fresh unknown provider statuses show `Status unavailable`. - Added server and UI tests for scheduled refresh and label behavior. ## Verification - `corepack pnpm install --frozen-lockfile` - `pnpm check:token-gates` - `pnpm exec vitest run server/src/__tests__/external-objects-service.test.ts server/src/__tests__/server-startup-feedback-export.test.ts ui/src/components/ExternalObjectPill.test.tsx ui/src/components/IssueProperties.test.tsx ui/src/lib/external-objects.test.ts` - `pnpm --filter @paperclipai/ui typecheck` - `pnpm --filter @paperclipai/server typecheck` - `pnpm --filter @paperclipai/server build` - `pnpm --filter @paperclipai/ui build` - `pnpm run typecheck:build-gaps` - GitHub PR checks passed on head `0e7fcd30` - Greptile reported 5/5 on head `0e7fcd30` with no unresolved review threads Notes: - I ran recursive typecheck and build first. Both hit container resource limits with exit 137 during concurrent package work, so I reran the affected server and UI targets separately. - An unrelated workspace-runtime auto-port test fails in this container with a PID ownership mismatch. It is outside the files changed here. ## Risks Low to medium risk. The scheduler does more periodic external-object work, so the main risk is extra provider refresh load. The implementation bounds the work to active companies, due non-terminal objects, and 50 objects per company per tick. The path also stays behind the external-objects experimental setting. ## Model Used OpenAI GPT-5 Codex in the Codex execution environment, with shell and GitHub CLI tool use. The runtime did not expose a more specific internal model ID or context window. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
7a3815eb9a
commit
185515c97b
18 files changed
+76692
-33
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { and, asc, eq, inArray, isNull, lte, sql } from "drizzle-orm";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, asc, eq, inArray, isNull, lte, or, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { documents, externalObjectMentions, externalObjects, issueComments, issueDocuments, issues, plugins } from "@paperclipai/db";
|
||||
import { companies, documents, externalObjectMentions, externalObjects, issueComments, issueDocuments, issues, plugins } from "@paperclipai/db";
|
||||
import {
|
||||
formatExternalObjectMentionSourceLabel,
|
||||
type ExternalObjectCanonicalUrl,
|
||||
@@ -91,6 +92,8 @@ type ExternalObjectMentionRecord = typeof externalObjectMentions.$inferSelect;
|
||||
|
||||
const DEFAULT_REFRESH_TTL_SECONDS = 300;
|
||||
const DEFAULT_RETRY_AFTER_SECONDS = 300;
|
||||
const DEFAULT_REFRESH_LEASE_SECONDS = 300;
|
||||
const REFRESH_LEASE_RENEW_INTERVAL_MS = 60_000;
|
||||
|
||||
function sourceWhere(input: ExternalObjectSourceContext) {
|
||||
const conditions = [
|
||||
@@ -601,8 +604,10 @@ export function externalObjectService(
|
||||
}
|
||||
|
||||
function toObjectPayload(object: ExternalObjectRecord, now = new Date()) {
|
||||
const { refreshToken, ...payload } = object;
|
||||
void refreshToken;
|
||||
return {
|
||||
...object,
|
||||
...payload,
|
||||
liveness: visibleLiveness(object, now),
|
||||
};
|
||||
}
|
||||
@@ -768,26 +773,37 @@ export function externalObjectService(
|
||||
return summarizeObjectPayloads(objects, 25);
|
||||
}
|
||||
|
||||
async function refreshObject(
|
||||
objectId: string,
|
||||
input: {
|
||||
companyId: string;
|
||||
actor?: Pick<LogActivityInput, "actorType" | "actorId" | "agentId" | "runId">;
|
||||
force?: boolean;
|
||||
now?: Date;
|
||||
},
|
||||
) {
|
||||
const now = input.now ?? new Date();
|
||||
const object = await db
|
||||
type RefreshObjectInput = {
|
||||
companyId: string;
|
||||
actor?: Pick<LogActivityInput, "actorType" | "actorId" | "agentId" | "runId">;
|
||||
force?: boolean;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
function refreshOwnerWhere(object: ExternalObjectRecord, refreshToken: string) {
|
||||
return and(
|
||||
eq(externalObjects.id, object.id),
|
||||
eq(externalObjects.companyId, object.companyId),
|
||||
eq(externalObjects.refreshToken, refreshToken),
|
||||
);
|
||||
}
|
||||
|
||||
async function refreshSupersededResult(object: ExternalObjectRecord, now: Date) {
|
||||
const latest = await db
|
||||
.select()
|
||||
.from(externalObjects)
|
||||
.where(and(eq(externalObjects.id, objectId), eq(externalObjects.companyId, input.companyId)))
|
||||
.where(and(eq(externalObjects.id, object.id), eq(externalObjects.companyId, object.companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!object) throw notFound("External object not found");
|
||||
if (!input.force && object.nextRefreshAt && object.nextRefreshAt > now) {
|
||||
return { object: toObjectPayload(object, now), refreshed: false, reason: "backoff" as const };
|
||||
}
|
||||
if (!latest) throw notFound("External object not found");
|
||||
return { object: toObjectPayload(latest, now), refreshed: false, reason: "refresh_superseded" as const };
|
||||
}
|
||||
|
||||
async function resolveObjectRefresh(
|
||||
object: ExternalObjectRecord,
|
||||
input: RefreshObjectInput,
|
||||
now: Date,
|
||||
refreshToken: string,
|
||||
) {
|
||||
const pluginResult = await resolveViaPluginProvider(db, opts.pluginWorkerManager, object);
|
||||
const resolver = pluginResult ? null : resolverRegistry.find(object);
|
||||
if (!pluginResult && !resolver) {
|
||||
@@ -796,10 +812,13 @@ export function externalObjectService(
|
||||
.set({
|
||||
liveness: visibleLiveness(object, now) === "fresh" ? "stale" : object.liveness,
|
||||
nextRefreshAt: addSeconds(now, DEFAULT_RETRY_AFTER_SECONDS),
|
||||
refreshStartedAt: null,
|
||||
refreshToken: null,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(eq(externalObjects.id, object.id), eq(externalObjects.companyId, object.companyId)))
|
||||
.where(refreshOwnerWhere(object, refreshToken))
|
||||
.returning();
|
||||
if (!updated) return refreshSupersededResult(object, now);
|
||||
return { object: toObjectPayload(updated ?? object, now), refreshed: false, reason: "no_resolver" as const };
|
||||
}
|
||||
|
||||
@@ -813,10 +832,13 @@ export function externalObjectService(
|
||||
lastErrorCode: result.errorCode,
|
||||
lastErrorMessage: sanitizeErrorMessage(result.errorMessage),
|
||||
nextRefreshAt: addSeconds(now, result.retryAfterSeconds ?? DEFAULT_RETRY_AFTER_SECONDS),
|
||||
refreshStartedAt: null,
|
||||
refreshToken: null,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(eq(externalObjects.id, object.id), eq(externalObjects.companyId, object.companyId)))
|
||||
.where(refreshOwnerWhere(object, refreshToken))
|
||||
.returning();
|
||||
if (!updated) return refreshSupersededResult(object, now);
|
||||
publishLiveEvent({
|
||||
companyId: object.companyId,
|
||||
type: "external_object.updated",
|
||||
@@ -845,16 +867,19 @@ export function externalObjectService(
|
||||
lastErrorCode: null,
|
||||
lastErrorMessage: null,
|
||||
nextRefreshAt: addSeconds(now, snapshot.ttlSeconds ?? DEFAULT_REFRESH_TTL_SECONDS),
|
||||
refreshStartedAt: null,
|
||||
refreshToken: null,
|
||||
updatedAt: now,
|
||||
};
|
||||
const [updated] = await db
|
||||
.update(externalObjects)
|
||||
.set({
|
||||
...patch,
|
||||
lastChangedAt: objectChanged(object, { ...object, ...patch }) ? now : object.lastChangedAt,
|
||||
})
|
||||
.where(and(eq(externalObjects.id, object.id), eq(externalObjects.companyId, object.companyId)))
|
||||
...patch,
|
||||
lastChangedAt: objectChanged(object, { ...object, ...patch }) ? now : object.lastChangedAt,
|
||||
})
|
||||
.where(refreshOwnerWhere(object, refreshToken))
|
||||
.returning();
|
||||
if (!updated) return refreshSupersededResult(object, now);
|
||||
const next = updated ?? object;
|
||||
if (objectChanged(object, next) && input.actor) {
|
||||
await logActivity(db, {
|
||||
@@ -886,6 +911,100 @@ export function externalObjectService(
|
||||
return { object: toObjectPayload(next, now), refreshed: true, reason: "resolved" as const };
|
||||
}
|
||||
|
||||
async function claimObjectRefresh(
|
||||
object: ExternalObjectRecord,
|
||||
input: RefreshObjectInput,
|
||||
now: Date,
|
||||
) {
|
||||
const staleRefreshStartedBefore = new Date(now.getTime() - DEFAULT_REFRESH_LEASE_SECONDS * 1000);
|
||||
const leaseAvailable = or(
|
||||
isNull(externalObjects.refreshStartedAt),
|
||||
lte(externalObjects.refreshStartedAt, staleRefreshStartedBefore),
|
||||
)!;
|
||||
const refreshToken = randomUUID();
|
||||
const dueOrForced = input.force
|
||||
? leaseAvailable
|
||||
: and(
|
||||
leaseAvailable,
|
||||
or(isNull(externalObjects.nextRefreshAt), lte(externalObjects.nextRefreshAt, now))!,
|
||||
)!;
|
||||
const [claimed] = await db
|
||||
.update(externalObjects)
|
||||
.set({
|
||||
refreshStartedAt: now,
|
||||
refreshToken,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(
|
||||
eq(externalObjects.id, object.id),
|
||||
eq(externalObjects.companyId, object.companyId),
|
||||
dueOrForced,
|
||||
))
|
||||
.returning();
|
||||
return claimed ?? null;
|
||||
}
|
||||
|
||||
function startRefreshLeaseRenewal(object: ExternalObjectRecord, refreshToken: string) {
|
||||
const interval = setInterval(() => {
|
||||
const renewedAt = new Date();
|
||||
void db
|
||||
.update(externalObjects)
|
||||
.set({ refreshStartedAt: renewedAt, updatedAt: renewedAt })
|
||||
.where(refreshOwnerWhere(object, refreshToken))
|
||||
.catch((err: unknown) => {
|
||||
logger.warn({ err, objectId: object.id }, "external object refresh lease renewal failed");
|
||||
});
|
||||
}, REFRESH_LEASE_RENEW_INTERVAL_MS);
|
||||
interval.unref?.();
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
};
|
||||
}
|
||||
|
||||
const objectRefreshesInFlight = new Map<string, Promise<Awaited<ReturnType<typeof resolveObjectRefresh>>>>();
|
||||
|
||||
async function refreshObject(
|
||||
objectId: string,
|
||||
input: RefreshObjectInput,
|
||||
) {
|
||||
const now = input.now ?? new Date();
|
||||
const object = await db
|
||||
.select()
|
||||
.from(externalObjects)
|
||||
.where(and(eq(externalObjects.id, objectId), eq(externalObjects.companyId, input.companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!object) throw notFound("External object not found");
|
||||
if (!input.force && object.nextRefreshAt && object.nextRefreshAt > now) {
|
||||
return { object: toObjectPayload(object, now), refreshed: false, reason: "backoff" as const };
|
||||
}
|
||||
|
||||
const refreshKey = `${object.companyId}:${object.id}`;
|
||||
const existingRefresh = objectRefreshesInFlight.get(refreshKey);
|
||||
if (existingRefresh) return existingRefresh;
|
||||
|
||||
const claimed = await claimObjectRefresh(object, input, now);
|
||||
if (!claimed) {
|
||||
const latest = await db
|
||||
.select()
|
||||
.from(externalObjects)
|
||||
.where(and(eq(externalObjects.id, object.id), eq(externalObjects.companyId, object.companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!latest) throw notFound("External object not found");
|
||||
return { object: toObjectPayload(latest, now), refreshed: false, reason: "refresh_in_progress" as const };
|
||||
}
|
||||
if (!claimed.refreshToken) {
|
||||
throw new Error("External object refresh claim did not return a refresh token");
|
||||
}
|
||||
|
||||
const stopRenewingRefreshLease = startRefreshLeaseRenewal(object, claimed.refreshToken);
|
||||
const refresh = resolveObjectRefresh(object, input, now, claimed.refreshToken).finally(() => {
|
||||
stopRenewingRefreshLease();
|
||||
objectRefreshesInFlight.delete(refreshKey);
|
||||
});
|
||||
objectRefreshesInFlight.set(refreshKey, refresh);
|
||||
return refresh;
|
||||
}
|
||||
|
||||
async function refreshIssueObjects(issueId: string, input: {
|
||||
companyId: string;
|
||||
objectIds?: string[];
|
||||
@@ -903,8 +1022,8 @@ export function externalObjectService(
|
||||
return results;
|
||||
}
|
||||
|
||||
async function refreshDueObjects(companyId: string, limit = 50, now = new Date()) {
|
||||
if (!(await isEnabled())) return [];
|
||||
async function refreshDueObjectsUnchecked(companyId: string, limit = 50, now = new Date()) {
|
||||
const staleRefreshStartedBefore = new Date(now.getTime() - DEFAULT_REFRESH_LEASE_SECONDS * 1000);
|
||||
const due = await db
|
||||
.select({ id: externalObjects.id })
|
||||
.from(externalObjects)
|
||||
@@ -913,6 +1032,10 @@ export function externalObjectService(
|
||||
eq(externalObjects.companyId, companyId),
|
||||
eq(externalObjects.isTerminal, false),
|
||||
lte(externalObjects.nextRefreshAt, now),
|
||||
or(
|
||||
isNull(externalObjects.refreshStartedAt),
|
||||
lte(externalObjects.refreshStartedAt, staleRefreshStartedBefore),
|
||||
),
|
||||
),
|
||||
)
|
||||
.limit(limit);
|
||||
@@ -927,6 +1050,27 @@ export function externalObjectService(
|
||||
return results;
|
||||
}
|
||||
|
||||
async function refreshDueObjects(companyId: string, limit = 50, now = new Date()) {
|
||||
if (!(await isEnabled())) return [];
|
||||
return refreshDueObjectsUnchecked(companyId, limit, now);
|
||||
}
|
||||
|
||||
async function refreshDueObjectsForActiveCompanies(limitPerCompany = 50, now = new Date()) {
|
||||
if (!(await isEnabled())) return { companies: 0, checked: 0, refreshed: 0 };
|
||||
const activeCompanies = await db
|
||||
.select({ id: companies.id })
|
||||
.from(companies)
|
||||
.where(eq(companies.status, "active"));
|
||||
let checked = 0;
|
||||
let refreshed = 0;
|
||||
for (const company of activeCompanies) {
|
||||
const results = await refreshDueObjectsUnchecked(company.id, limitPerCompany, now);
|
||||
checked += results.length;
|
||||
refreshed += results.filter((result) => result.refreshed).length;
|
||||
}
|
||||
return { companies: activeCompanies.length, checked, refreshed };
|
||||
}
|
||||
|
||||
return {
|
||||
syncIssue,
|
||||
syncComment,
|
||||
@@ -941,5 +1085,6 @@ export function externalObjectService(
|
||||
refreshObject,
|
||||
refreshIssueObjects,
|
||||
refreshDueObjects,
|
||||
refreshDueObjectsForActiveCompanies,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user