mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-01 06:42:06 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The board UI includes an agents sidebar so operators can see which agents are currently active. > - That sidebar depends on live-run polling, heartbeat events, and cross-tab cache sharing to stay current without overloading the API. > - The sidebar was visually churning because agents could leave the live section immediately after a run ended, while progress events and cross-tab broadcasts kept forcing hot query updates. > - This pull request stabilizes live sidebar membership and makes shared polling broadcasts monotonic/deduplicated. > - The benefit is a calmer operator sidebar that still reflects real live state without flashing between stale and fresh snapshots. ## Linked Issues or Issue Description No public GitHub issue exists for this operator-facing bug. Bug summary: - What happened: the agents sidebar could flash or reshuffle around active agents while live-run and heartbeat data was updating. - Expected behavior: active and recently-active agents should remain visually stable, and cross-tab cache sharing should not overwrite fresher data with older snapshots. - Reproduction context: run Paperclip with multiple tabs or rapid live-run/progress updates and watch the agents sidebar while agents enter/leave live execution. - Deployment mode: local/operator board UI. Related PR: - Supersedes #9357, which carried the same fixes on a branch/title/body that were not suitable for public contribution hygiene. ## What Changed - Restored the maintainer-only warning wording in the developer skill guide so the existing server skill-utils CI gate passes on current master. - Added a 120-second linger window for streamlined sidebar agent rows so an agent does not immediately disappear from the live section as soon as its last run ends. - Deferred the recent-agent fallback until there are no live or lingering agents, while keeping the live badge tied only to actually-live runs. - Stopped broad live-runs/heartbeats/agents-list invalidation on every run progress event, while preserving targeted agent-detail invalidation. - Added producer timestamps to cross-tab shared polling result messages so older-or-equal snapshots are dropped before `setQueryData`. - Added per-resource broadcast dedupe/rate limiting so tabs do not rebroadcast equivalent cached data in a loop. - Added focused coverage for sidebar linger behavior, staggered multi-agent linger expiry, live update invalidation scope, shared polling timestamp handling, and cross-tab broadcast dedupe. ## Verification Run locally on the rebased PR branch: - `pnpm --filter @paperclipai/ui exec vitest run src/components/SidebarAgents.test.tsx src/context/LiveUpdatesProvider.test.ts` — 44 tests passed. - `pnpm --filter @paperclipai/ui exec vitest run src/lib/cross-tab-poll.test.ts src/hooks/useSharedPolling.test.ts` — 10 tests passed. - `pnpm --filter @paperclipai/ui typecheck` — exit code 0. ## Risks - Low migration risk: the sidebar/polling changes are UI/client cache behavior only, with no database or API contract changes. - Sidebar visibility now intentionally lingers for 120 seconds after the last live run; stale rows could remain briefly visible, but their live badge is removed when they are no longer actually live. - Cross-tab broadcasts are now more conservative; a missed publish should be corrected by the next normal poll or accepted newer timestamp. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI GPT-5 Codex via the Paperclip Codex coding-agent runtime; exact API model identifier and context-window size are not exposed in this environment. The agent used terminal/tool execution for repository inspection, focused tests, branch preparation, and PR creation. ## 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>
149 lines
4.9 KiB
TypeScript
149 lines
4.9 KiB
TypeScript
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import { type QueryClient, type QueryKey, useQueryClient } from "@tanstack/react-query";
|
|
import {
|
|
SharedPollingCoordinator,
|
|
type SharedMessage,
|
|
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, dataUpdatedAt: number) => 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 applySharedPollingResult<TData>(
|
|
queryClient: Pick<QueryClient, "getQueryState" | "setQueryData">,
|
|
queryKey: QueryKey,
|
|
message: SharedMessage,
|
|
): boolean {
|
|
if (message.type !== "result") return false;
|
|
const incomingUpdatedAt = message.dataUpdatedAt ?? message.at;
|
|
if (incomingUpdatedAt <= 0) return false;
|
|
const localUpdatedAt = queryClient.getQueryState(queryKey)?.dataUpdatedAt ?? 0;
|
|
if (localUpdatedAt >= incomingUpdatedAt) return false;
|
|
queryClient.setQueryData(queryKey, message.data as TData, { updatedAt: incomingUpdatedAt });
|
|
return true;
|
|
}
|
|
|
|
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) => {
|
|
applySharedPollingResult(queryClient, queryKeyRef.current, message);
|
|
});
|
|
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, dataUpdatedAt: number) => {
|
|
if (!activeCompanyId || !fullResourceKey || data === undefined) return;
|
|
const entry = coordinators.get(activeCompanyId);
|
|
entry?.coordinator.publish(fullResourceKey, data, dataUpdatedAt);
|
|
}, [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, dataUpdatedAt);
|
|
}, [data, dataUpdatedAt, shared]);
|
|
}
|