mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The agent sign-in panel reads the user's active sign-in session before it starts a new one > - When that active session belongs to another computer or AI connection, the panel throws an error and shows "Another sign-in attempt is active" > - This is an expected state that the user must resolve. But the error has no status, so the query client classifies it as an unknown failure > - Because of that, the query retries it two times and then sends it to Sentry as an unexpected error > - This pull request marks this state as a conflict (409). The query does not retry it and does not report it. The panel shows the same message > - The benefit is that Sentry shows real failures only, and the user sees the conflict at once, not after about 3 seconds of retries ## Linked Issues or Issue Description No public issue exists. The issue is below. It follows the bug template. **What happened?** A user opened the agent sign-in panel while a different sign-in for the same owner was active on another computer or AI connection. The panel showed "Another sign-in attempt is active…". The browser also sent a handled `Error` to Sentry from the active-session query (`query_kind=adapter-login-active-session`). This happens in the displayed-code panel (Codex and similar adapters) and in the Claude setup-token panel. Both throw the same kind of error. **Expected behavior** The panel shows the conflict and the "Cancel previous sign-in and retry" action. The app does not retry the read. The app does not report the conflict to Sentry, because it is a known user state and not a failure. **Steps to reproduce** 1. Start a sign-in for an agent on computer A. Do not complete it. 2. Open the sign-in panel for an agent on computer B, as the same user. 3. The active-session read finds the session for computer A. The query retries two times, then the panel shows the conflict, and Sentry gets an event. **Paperclip version or commit** `master` at66a8aa7f7e. Sentry saw it on hosted releases91e9365d59and earlier. **Relevant logs or output** `Error: Another sign-in attempt is active. Finish or cancel that attempt before starting a new sign-in.` (mechanism generic, handled, culprit `queryFn`). A similar group has the message "Finish or cancel it in its original account setup before starting this one." from the Claude setup-token panel. ## What Changed - `ui/src/lib/query-client.ts`: Add `QueryStateConflictError`. It carries `status = 409`, so `classifyError` returns `conflict`. Because of that, `shouldRetryRequest` does not retry it, `shouldReportQueryError` does not send it to Sentry, and `describeError` still shows its message. - `ui/src/components/AgentConfigForm.tsx`: `AdapterLoginConflictError` (displayed-code panel) now extends `QueryStateConflictError`. The Claude setup-token panel now throws `QueryStateConflictError` and not a plain `Error`. - Tests: A render test for each panel (`codex_local` and `claude_local`) uses the real `createAppQueryClient`. It checks that the panel shows the conflict, reads the active session one time, does not start a new sign-in, and does not report an error. The unit tests in `query-client.test.ts` check the retry and report rules for the new error. ## Verification - Red: With the original `AgentConfigForm.tsx`, both new render tests fail: `expected "vi.fn()" to be called 1 times, but got 3 times` (two retries). - Green: `cd ui && npx vitest run src/components/AgentConfigForm.render.test.tsx src/lib/query-client.test.ts src/api/errors src/components/AgentConfigForm.test src/components/new-agent` passes: 6 files, 118 tests. - `pnpm verify` selected a broad set because `query-client.ts` is imported widely. I stopped the local run and used full CI on head4267d070e7for broad coverage. CI ran the full suite, and both changed test files passed there (`AgentConfigForm.render.test.tsx` 8 tests, `query-client.test.ts` 27 tests). - `tsc --noEmit -p ui/tsconfig.json` shows no errors in the changed files. ## Risks - Low risk. The change touches only the two client-side conflict errors. API errors and other query errors keep their current classification. - The panel no longer retries the conflict read. A retry reads the same server state, so this does not remove a recovery path. The "Cancel previous sign-in and retry" action refetches the read. > 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 - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, test runs). ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
270 lines
10 KiB
TypeScript
270 lines
10 KiB
TypeScript
/**
|
|
* The app's React Query client and its outage-aware defaults.
|
|
*
|
|
* - Queries retry transient errors with backoff for about 30 seconds and never
|
|
* retry a 4xx. `networkMode: "online"` plus `bindConnectivity` means a
|
|
* confirmed outage pauses queries instead of failing them.
|
|
* - Mutations fail fast by default (`networkMode: "always"`, no retry). A
|
|
* mutation that is safe to send twice opts in with
|
|
* `meta: { replay: "idempotent" }`: it pauses while the server is
|
|
* unreachable, retries transient errors, and resumes on reconnect.
|
|
* - `QueryCache`/`MutationCache` events feed the connectivity store; final
|
|
* query errors go to Sentry unless they are transient or client errors.
|
|
* - A mutation with `meta: { errorToast: true }` and no `onError` of its own
|
|
* gets a readable toast when it fails. Transient failures skip the toast
|
|
* while the connection banner covers them.
|
|
*/
|
|
|
|
import {
|
|
MutationCache,
|
|
QueryCache,
|
|
QueryClient,
|
|
onlineManager,
|
|
type DefaultError,
|
|
type Mutation,
|
|
type MutationOptions,
|
|
type QueryClientConfig,
|
|
type QueryKey,
|
|
type RefetchOptions,
|
|
type RefetchQueryFilters,
|
|
} from "@tanstack/react-query";
|
|
import { classifyError, describeError, errorRetryAfterMs, isTransientError } from "@/api/errors";
|
|
import { MAX_PROBE_DELAY_MS, PROBE_BACKOFF_MS, type ConnectivityStore } from "./connectivity";
|
|
|
|
export interface AppMutationMeta extends Record<string, unknown> {
|
|
/**
|
|
* `"idempotent"`: sending this mutation twice has the same effect as once
|
|
* (an absolute-value PATCH, a POST with an idempotency key). It may pause
|
|
* across an outage and resend on reconnect.
|
|
*/
|
|
replay?: "idempotent";
|
|
/**
|
|
* `true` shows the global readable error toast when this mutation has no
|
|
* `onError` of its own. Opt-in because many surfaces already render
|
|
* `mutation.error` inline, and a default toast would say it twice.
|
|
*/
|
|
errorToast?: true;
|
|
}
|
|
|
|
declare module "@tanstack/react-query" {
|
|
interface Register {
|
|
mutationMeta: AppMutationMeta;
|
|
}
|
|
}
|
|
|
|
/** Delay before each transient retry; together roughly 30 seconds. */
|
|
export const TRANSIENT_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000] as const;
|
|
/** Unexpected failures (5xx other than gateway errors, parse errors) retry briefly. */
|
|
export const UNKNOWN_RETRY_LIMIT = 2;
|
|
|
|
/** Retry policy shared by queries and replayable mutations. */
|
|
export function shouldRetryRequest(failureCount: number, error: unknown): boolean {
|
|
const kind = classifyError(error);
|
|
if (kind === "transient") return failureCount < TRANSIENT_RETRY_DELAYS_MS.length;
|
|
if (kind === "unknown") return failureCount < UNKNOWN_RETRY_LIMIT;
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Backoff for `shouldRetryRequest`; a longer server `Retry-After` wins. It is
|
|
* not shortened: retrying before the server's window ends only fails again.
|
|
* `parseRetryAfter` already bounds it.
|
|
*/
|
|
export function retryDelayFor(failureCount: number, error: unknown): number {
|
|
const base = TRANSIENT_RETRY_DELAYS_MS[Math.min(failureCount, TRANSIENT_RETRY_DELAYS_MS.length - 1)];
|
|
const retryAfterMs = errorRetryAfterMs(error);
|
|
return retryAfterMs === null ? base : Math.max(base, retryAfterMs);
|
|
}
|
|
|
|
/**
|
|
* For reads the app cannot open without (the access gate): retry transient
|
|
* errors without limit, never anything else. Retries pause while the
|
|
* connectivity store reports an outage, so this does not poll a down server.
|
|
*/
|
|
export function retryWhileTransient(_failureCount: number, error: unknown): boolean {
|
|
return isTransientError(error);
|
|
}
|
|
|
|
/**
|
|
* For the few reads that must fail fast: retry a transient error at most
|
|
* `limit` times (`0` never retries) and never anything else. Prefer this over
|
|
* `retry: false` so the call site says why it opts out of the default policy.
|
|
*/
|
|
export function retryTransientOnly(limit: number): (failureCount: number, error: unknown) => boolean {
|
|
return (failureCount, error) => isTransientError(error) && failureCount < limit;
|
|
}
|
|
|
|
/** Backoff for `retryWhileTransient`: the connectivity probe schedule, capped at 15s. */
|
|
export function reconnectDelayFor(failureCount: number, error: unknown): number {
|
|
const base = PROBE_BACKOFF_MS[Math.min(failureCount, PROBE_BACKOFF_MS.length - 1)];
|
|
const retryAfterMs = errorRetryAfterMs(error);
|
|
return retryAfterMs === null ? base : Math.min(Math.max(base, retryAfterMs), MAX_PROBE_DELAY_MS);
|
|
}
|
|
|
|
/** A successful response whose expected state has not arrived yet. */
|
|
export class QueryNotReadyError extends Error {}
|
|
|
|
/**
|
|
* A successful read that found a state the user must resolve, such as another
|
|
* active sign-in. It carries status 409, so it classifies as a conflict: the
|
|
* page shows its message, a retry would read the same state, and it is not a
|
|
* Sentry event.
|
|
*/
|
|
export class QueryStateConflictError extends Error {
|
|
readonly status = 409;
|
|
}
|
|
|
|
/** Query errors worth a Sentry event: not outages, not denials or missing items. */
|
|
export function shouldReportQueryError(error: unknown): boolean {
|
|
return !(error instanceof QueryNotReadyError) && classifyError(error) === "unknown";
|
|
}
|
|
|
|
export interface MutationErrorToast {
|
|
title: string;
|
|
body: string;
|
|
}
|
|
|
|
export interface AppQueryClientDeps {
|
|
connectivity: Pick<ConnectivityStore, "reportError" | "getSnapshot">;
|
|
/** Report a final query error. The key lets the reporter group by query name. */
|
|
reportError?: (error: unknown, queryKey: QueryKey) => void;
|
|
/** Show a toast for a failed opted-in mutation that has no handler of its own. */
|
|
notifyMutationError?: (toast: MutationErrorToast) => void;
|
|
}
|
|
|
|
/**
|
|
* Whether the global handler should toast for this failed mutation. A
|
|
* transient failure is skipped only while the connection banner covers it; a
|
|
* 429 or one route's worker being down leaves the app online, and the write is
|
|
* still lost.
|
|
*/
|
|
export function shouldToastMutationError(
|
|
error: unknown,
|
|
mutation: Pick<Mutation<unknown, DefaultError, unknown, unknown>, "options" | "meta">,
|
|
connectionDown: boolean,
|
|
): boolean {
|
|
if (mutation.options.onError) return false;
|
|
if (mutation.meta?.errorToast !== true) return false;
|
|
const kind = classifyError(error);
|
|
if (kind === "aborted") return false;
|
|
return kind !== "transient" || !connectionDown;
|
|
}
|
|
|
|
class AppQueryClient extends QueryClient {
|
|
override defaultMutationOptions<T extends MutationOptions<any, any, any, any>>(options?: T): T {
|
|
const defaulted = super.defaultMutationOptions(options);
|
|
if (options?._defaulted || defaulted.meta?.replay !== "idempotent") return defaulted;
|
|
return {
|
|
...defaulted,
|
|
networkMode: options?.networkMode ?? "online",
|
|
retry: options?.retry ?? shouldRetryRequest,
|
|
retryDelay: options?.retryDelay ?? retryDelayFor,
|
|
};
|
|
}
|
|
|
|
override refetchQueries<TTaggedQueryKey extends QueryKey = QueryKey>(
|
|
filters?: RefetchQueryFilters<TTaggedQueryKey>,
|
|
options?: RefetchOptions,
|
|
): Promise<void> {
|
|
const predicate = filters?.predicate;
|
|
return super.refetchQueries(
|
|
{
|
|
...filters,
|
|
predicate: (query) => query.options.queryFn !== undefined && (predicate?.(query) ?? true),
|
|
},
|
|
options,
|
|
);
|
|
}
|
|
}
|
|
|
|
/** A polling query that keeps failing reports once per window, not on every poll. */
|
|
const QUERY_ERROR_REPORT_WINDOW_MS = 10 * 60_000;
|
|
|
|
export function createAppQueryClient(deps: AppQueryClientDeps, config: QueryClientConfig = {}): QueryClient {
|
|
const lastReportedAt = new Map<string, number>();
|
|
const queryCache = new QueryCache({
|
|
onError: (error, query) => {
|
|
if (!deps.reportError || !shouldReportQueryError(error)) return;
|
|
const now = Date.now();
|
|
const last = lastReportedAt.get(query.queryHash);
|
|
if (last !== undefined && now - last < QUERY_ERROR_REPORT_WINDOW_MS) return;
|
|
lastReportedAt.set(query.queryHash, now);
|
|
deps.reportError(error, query.queryKey);
|
|
},
|
|
});
|
|
const mutationCache = new MutationCache({
|
|
onError: (error, _variables, _context, mutation) => {
|
|
const connectionDown = deps.connectivity.getSnapshot().status !== "online";
|
|
if (!deps.notifyMutationError || !shouldToastMutationError(error, mutation, connectionDown)) return;
|
|
const { title, body } = describeError(error);
|
|
deps.notifyMutationError({ title, body });
|
|
},
|
|
});
|
|
|
|
// Retry failures are only visible as cache events, and connectivity needs
|
|
// the first failure, not the last one.
|
|
queryCache.subscribe((event) => {
|
|
if (event.type !== "updated") return;
|
|
if (event.action.type === "failed" || event.action.type === "error") deps.connectivity.reportError(event.action.error);
|
|
// Queries can read other services or return local data. Only the health
|
|
// probe and the server WebSocket can prove that Paperclip recovered.
|
|
});
|
|
mutationCache.subscribe((event) => {
|
|
if (event.type !== "updated") return;
|
|
if (event.action.type === "failed" || event.action.type === "error") deps.connectivity.reportError(event.action.error);
|
|
});
|
|
|
|
return new AppQueryClient({
|
|
...config,
|
|
queryCache,
|
|
mutationCache,
|
|
defaultOptions: {
|
|
...config.defaultOptions,
|
|
queries: {
|
|
retry: shouldRetryRequest,
|
|
retryDelay: retryDelayFor,
|
|
networkMode: "online",
|
|
...config.defaultOptions?.queries,
|
|
},
|
|
mutations: {
|
|
networkMode: "always",
|
|
retry: 0,
|
|
...config.defaultOptions?.mutations,
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
/** `setPendingWrites` source for replayable mutations paused by an outage. */
|
|
export const PAUSED_MUTATIONS_SOURCE = "paused-mutations";
|
|
|
|
/**
|
|
* Drive React Query's `onlineManager` from the connectivity store, refresh
|
|
* live queries once when the server comes back, and count paused replayable
|
|
* mutations as pending writes. Returns a cleanup.
|
|
*/
|
|
export function bindConnectivity(queryClient: QueryClient, store: ConnectivityStore): () => void {
|
|
const isOnline = () => store.getSnapshot().status === "online";
|
|
onlineManager.setEventListener((setOnline) => {
|
|
setOnline(isOnline());
|
|
return store.subscribe(() => setOnline(isOnline()));
|
|
});
|
|
const stopRecover = store.onRecover(() => {
|
|
void queryClient.invalidateQueries({ type: "active" }, { cancelRefetch: false });
|
|
});
|
|
const mutationCache = queryClient.getMutationCache();
|
|
const reportPausedMutations = () => {
|
|
const paused = mutationCache.findAll({ predicate: (mutation) => mutation.state.isPaused }).length;
|
|
store.setPendingWrites(PAUSED_MUTATIONS_SOURCE, paused);
|
|
};
|
|
reportPausedMutations();
|
|
const stopMutationCount = mutationCache.subscribe(reportPausedMutations);
|
|
const stopBrowserEvents = store.start();
|
|
return () => {
|
|
stopRecover();
|
|
stopMutationCount();
|
|
store.setPendingWrites(PAUSED_MUTATIONS_SOURCE, 0);
|
|
stopBrowserEvents();
|
|
};
|
|
}
|