mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-07 07:55:47 +01:00
perf(inbox): combine startup reads and reduce refetch pressure (#18790)
## Thinking Path > - Paperclip helps people manage AI agents and their work. > - Mine shows the work and failures that need the viewing user's attention. > - A reload waits for account access, task rows, parent captions and failure state. > - Those reads form several browser request stages before useful rows appear. > - Live invalidations can also restart the same task-list request more than once. > - This change supplies startup data together and removes redundant refresh work. > - It preserves current authority, failure presentation, archive state and row stability. ## Linked Issues or Issue Description Refs #18645. Related: #18642. This change implements the read-receipt behavior independently on current master. It does not use that PR's branch or patch. **What happened?** Mine starts its primary request after the session, company and board-access reads. It then requests parent captions and rich failure context. Four observed loads spent another 0.45–0.70 seconds after the primary rows arrived. One slower load waited 1.71 seconds for parent context. The same run observed two HTTP 429 responses. These timings identify request waits; they do not attribute the delay to SQL or Node CPU. Read receipts also invalidate general task collections and dashboards. Overlapping parent and child invalidations can start two requests and abort the first. **Expected behavior** The initial page should use one account-safe startup projection and one complete Mine response. A read receipt should refresh the affected viewer's inbox state. Each invalidation batch should refresh a covered query once. Required captions and current failure state must be ready before first reveal. Existing rows should remain usable during a transient refresh error. **Steps to reproduce** 1. Open a populated Mine inbox with parent tasks outside the visible index and a current failed run. 2. Reload with browser HTTP cache retained and application query state empty. 3. Inspect the session, company, board access, task-index and context request sequence. 4. Open or mark a task read and inspect the unrelated collection refetches. **Paperclip version or commit** Baseline: `44a9a043b80c18314d8dd89556f444dae696d3d6`. **Deployment mode** Authenticated board UI. Local proof uses the real APIs and database with a synthetic session resolver. No hosted candidate deployment is claimed. ## What Changed - Add optional, same-user `boardBootstrap` data to the existing session response. Seed account-keyed company and board-access reads from it. Keep ordinary endpoint reads for fallback, retry and live reconciliation. A returning account cannot reuse revoked cached access. Cache collection and later real refetches remain effective. - Add the board-only Mine snapshot endpoint. Reuse the canonical issue selector, private-task filtering, run-read decisions, secret redaction and interruption/recovery presentation. Assemble the fixed 100-task page, parent captions and bounded 200-run failure window on the server. Start independent reads together. Optional source errors keep successful task rows usable. - Keep array-shaped source caches for archive and undo. Key Mine source, context and reveal state by account. Validate the response's user stamp before committing it. Remove array-only cross-tab Mine broadcasts, which cannot carry its paired failure context. The server retains authenticated in-flight coalescing. - Scope read-receipt invalidation to the affected viewer's inbox, badges and chat unread state. Keep company and task audit views fresh. Preserve genuine task mutations, run updates and subscription-gap reconciliation. - Remove covered scalar-prefix invalidations within a batch. Preserve predicates, exact matches and different query/refetch constraints. A later event can still refresh again. - Retire Mine in-flight reuse after local company activity or run lifecycle changes. A post-archive read starts fresh. Old work keeps its admission slot until it settles, even if every HTTP client aborts. The eight-compute limit stays in place. - Add API, component and browser regressions. Extend the production timing harness with matching API/UI artifact receipts, retained-cache reloads, request status counts, layout checks and optional controlled network latency. Update API and verification documentation. ## Verification - Full `pnpm -r typecheck` passes. - Full `pnpm build` passes. - Token gates, map checks and diff whitespace checks pass. - 72 Inbox component tests pass. Startup-specific checks pass, including account switching, revoked cached access, malformed/absent bootstrap data and cache collection. The canonical authenticated bootstrap route also passes against real PostgreSQL. - Six real PostgreSQL Mine route cases pass, including full equivalence with legacy authorized projections, privacy, fixed bounds, membership revocation, coalescing, archive freshness and aborted-client admission. Four focused legacy coordinator controls pass. Six assembly tests pass. - Refetch and invalidation regressions pass. Meaningful pre-fix tests observed two request starts and one abort for overlapping invalidations; the fix produces one start and no abort. The archive race test observed the post-archive GET joining the old body before the fix. - All 11 existing startup browser checks pass, including Tasks/Mine code loading, desktop/mobile bounds, non-streamlined Coordinator, task navigation, failed preloading and Back position. The nine focused startup, fallback, partial-source error, rate-limit recovery, archive/undo and geometry cases also pass. The 429 cases use the inherited retry window. Archive and keyboard undo are corroborated through the real API and reload. Authentication and failure fault injection in these cases are explicitly simulated. - Matched production before/after timings are complete. Full aggregate Vitest coverage is left to CI. At 15:15 UTC, the final-head runner gate and `review` workflow pass. The 45 build/test/policy jobs are queued; the Build job has no `ubuntu-latest` runner assigned and has executed no steps, so remote aggregate results remain unverified. Paperclip Review and Superagent Security Scan are in progress. Superseded runs for this PR were cancelled. No current-head check has reported a failure; the CI checklist remains open. The remaining step is runner allocation and completion of those external checks; persistent queueing needs the repository CI owner's attention. - Greptile completed on final head `ecde295565309275c4f2fae903caf6892f1eaafd` at 5/5. The map-scope finding is fixed and resolved; there are no open review threads. ### Matched browser timings Five alternating baseline/candidate pairs per network scenario, measured serially in headful Chrome 156.0.8078.80 on Apple silicon with Node 24.22.2 and a 1440×900 viewport. Both production UIs use their matching real API revision against one fixed disposable PostgreSQL fixture: 34 tasks, 31 visible task rows, one paused agent and one terminal failure. No active agent/provider work. HTTP cache is retained; each initial sample reloads the document and clears application query state. Warm navigation and Back retain query state. CPU and throughput are native. The 100ms scenario uses CDP minimum request-to-response-header latency without request interception. It is a controlled request-dependency experiment, not a staging reproduction. Values are median milliseconds with min–max in parentheses. Paired saving is baseline minus candidate for each alternating pair; its median differs from the difference of arm medians. Positive saving favors the candidate. | Network / journey | Baseline | Candidate | Median paired saving | | --- | ---: | ---: | ---: | | Native / initial rows | 187.6 (128.9–208.5) | 191.7 (130.3–210.9) | −23.3 | | Native / Recent → Mine | 100.17 (99.90–101.87) | 100.07 (99.88–101.37) | −0.16 | | Native / task → Back | 70.45 (56.63–72.02) | 66.64 (56.52–67.71) | +4.94 | | 100ms / initial rows | 930.3 (914.1–1015.7) | 799.0 (697.1–826.0) | +211.8 | | 100ms / Recent → Mine | 100.09 (97.73–100.16) | 100.18 (96.65–100.98) | −0.02 | | 100ms / task → Back | 74.97 (62.77–75.82) | 75.47 (61.51–76.19) | +0.35 | The controlled-latency initial pairs all improve, saving 108.3–217.0ms. Native initial pairs have mixed signs (−67.5 to +78.1ms), so they establish no reliable native page-speed improvement. Warm and Back timings are effectively unchanged. Median primary-request start is 110.4→135.2ms natively and 497.8→480.9ms with 100ms latency; these runs do not establish a large startup-only timing gain. API requests through the two-second post-reveal window fall from median 32 (32–37) to 27 (25–28) natively, and 37 (33–38) to 30 (25–32) with 100ms latency. All 20 samples preserve the same ordered 31 task links, first-row DOM identity and geometry. All recorded API responses are HTTP 200; zero unfinished requests, 429s or JavaScript errors. Lower 429 incidence on staging remains unproven. Measured source: baseline `44a9a043b80c18314d8dd89556f444dae696d3d6`, candidate `4c12b2ef0ecf0754676e99bd6b9399e84408646c`. Final head `ecde295565309275c4f2fae903caf6892f1eaafd` changes only two feature-map files and existing browser test expectations since that measured candidate; production executable inputs are identical to the measured candidate. Asset hashes, API health revision receipts and every raw sample were retained. These results do not claim hosted-page improvement or deployment of this PR. ## Risks - Startup enrichment adds work to the session read. Failure of this optional projection falls back to the ordinary company and access endpoints. It does not invalidate a valid session or replace per-request server authorization. - Account changes, stale cache entries and same-company navigation can expose old presentation data. Account keys, principal stamps, reveal scopes and canonical bootstrap replacement have dedicated negative cases. Permission failures hide cached task rows; transient network, 429 and 5xx failures preserve them. - Current failure state can differ from the historical failed run. The snapshot uses the existing canonical rich projection and verified missing-ID coverage. Partial context failures retain an explicit retry path. - Mutation retirement follows events delivered to the current server process. This adds no cross-replica invalidation protocol or distributed read-after-write guarantee. - New UI assets require the matching API. Older UI/session consumers retain their existing response and endpoint behavior. There is no database migration, provider call or deployment change. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, code execution, browser automation and delegated source review. The exact runtime model ID and context-window size are not exposed by this session. ## 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 - [ ] 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
5dee4993f1
commit
b40e6edaea
40 files changed
+2457
-350
No files matched your search
@@ -11,6 +11,26 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("authApi.getSession", () => {
|
||||
it("keeps a valid session when optional bootstrap is malformed or belongs to another account", async () => {
|
||||
const session = { session: { id: "session", userId: "one" },
|
||||
user: { id: "one", email: "one@example.com", name: "One", image: null }, sentryDsn: null };
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({ ...session, boardBootstrap: {
|
||||
userId: "two", companies: [], boardAccess: { userId: "two", isInstanceAdmin: true, companyIds: ["foreign"] },
|
||||
} }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
expect(await authApi.getSession()).toEqual(session);
|
||||
fetchMock.mockResolvedValue(Response.json({ ...session, boardBootstrap: { userId: "one", companies: "invalid" } }));
|
||||
expect(await authApi.getSession()).toEqual(session);
|
||||
});
|
||||
|
||||
it("retains a same-account bootstrap alongside the ordinary session", async () => {
|
||||
const session = { session: { id: "session", userId: "one" },
|
||||
user: { id: "one", email: "one@example.com", name: "One", image: null }, sentryDsn: null };
|
||||
const boardBootstrap = { userId: "one", companies: [], boardAccess: { userId: "one", isInstanceAdmin: false, companyIds: [] } };
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ ...session, boardBootstrap })));
|
||||
expect(await authApi.getSession()).toEqual({ ...session, boardBootstrap });
|
||||
});
|
||||
|
||||
it("returns null for an ordinary local 401", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: "unauthorized" }), {
|
||||
|
||||
+9
-6
@@ -1,7 +1,8 @@
|
||||
import {
|
||||
authSessionSchema,
|
||||
currentUserProfileSchema,
|
||||
type AuthSession,
|
||||
type BoardBootstrapSession,
|
||||
readBoardBootstrap,
|
||||
type CurrentUserProfile,
|
||||
type UpdateCurrentUserProfile,
|
||||
} from "@paperclipai/shared";
|
||||
@@ -38,13 +39,15 @@ export class AuthApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
function toSession(value: unknown): AuthSession | null {
|
||||
function toSession(value: unknown): BoardBootstrapSession | null {
|
||||
const direct = authSessionSchema.safeParse(value);
|
||||
if (direct.success) return direct.data;
|
||||
if (direct.success) {
|
||||
const boardBootstrap = readBoardBootstrap((value as Record<string, unknown>).boardBootstrap, direct.data.user.id);
|
||||
return boardBootstrap ? { ...direct.data, boardBootstrap } : direct.data;
|
||||
}
|
||||
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const nested = authSessionSchema.safeParse((value as Record<string, unknown>).data);
|
||||
return nested.success ? nested.data : null;
|
||||
return toSession((value as Record<string, unknown>).data);
|
||||
}
|
||||
|
||||
/** The server's own explanation on an auth error body, if it sent one. */
|
||||
@@ -160,7 +163,7 @@ async function authPatch<T>(path: string, body: Record<string, unknown>, parse:
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
getSession: async (): Promise<AuthSession | null> => {
|
||||
getSession: async (): Promise<BoardBootstrapSession | null> => {
|
||||
const res = await apiFetch("/api/auth/get-session", {
|
||||
credentials: "include",
|
||||
headers: { Accept: "application/json" },
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import type { BoardBootstrap } from "@paperclipai/shared";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { boardAccessQueryOptions } from "./board-access-query";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
|
||||
const readAccess = vi.hoisted(() => vi.fn());
|
||||
vi.mock("./access", () => ({ accessApi: { getCurrentBoardAccess: readAccess } }));
|
||||
afterEach(() => readAccess.mockReset());
|
||||
|
||||
const bootstrap = (userId: string): BoardBootstrap => ({
|
||||
userId, companies: [], boardAccess: { userId, isInstanceAdmin: false, companyIds: [`company-${userId}`] },
|
||||
});
|
||||
|
||||
describe("account-scoped board bootstrap", () => {
|
||||
it("opens from the session snapshot and uses the ordinary reader after invalidation", async () => {
|
||||
const client = new QueryClient();
|
||||
const options = boardAccessQueryOptions("one", bootstrap("one"), Date.now(), vi.fn());
|
||||
expect(await client.fetchQuery({ ...options, staleTime: 30_000 })).toEqual(bootstrap("one").boardAccess);
|
||||
expect(readAccess).not.toHaveBeenCalled();
|
||||
await client.invalidateQueries({ queryKey: queryKeys.access.currentBoardAccess });
|
||||
readAccess.mockResolvedValue({ userId: "one", isInstanceAdmin: false, companyIds: [] });
|
||||
expect(await client.fetchQuery(options)).toEqual({ userId: "one", isInstanceAdmin: false, companyIds: [] });
|
||||
expect(readAccess).toHaveBeenCalledTimes(1);
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it("cannot reuse another account's bootstrap or cache entry", async () => {
|
||||
const client = new QueryClient();
|
||||
const first = boardAccessQueryOptions("one", bootstrap("one"), Date.now(), vi.fn());
|
||||
await client.fetchQuery({ ...first, staleTime: Infinity });
|
||||
const second = boardAccessQueryOptions("two", bootstrap("one"), Date.now(), vi.fn());
|
||||
expect(second.initialData).toBeUndefined();
|
||||
expect(second.queryKey).not.toEqual(first.queryKey);
|
||||
readAccess.mockResolvedValue({ userId: "two", isInstanceAdmin: false, companyIds: [] });
|
||||
expect(await client.fetchQuery(second)).toMatchObject({ userId: "two", companyIds: [] });
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it("refreshes identity instead of caching a response from a changed account", async () => {
|
||||
const changed = vi.fn();
|
||||
readAccess.mockResolvedValue({ userId: "two", isInstanceAdmin: true, companyIds: ["foreign"] });
|
||||
await expect(boardAccessQueryOptions("one", undefined, 0, changed).queryFn()).rejects.toMatchObject({ status: 401 });
|
||||
expect(changed).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { BoardBootstrap } from "@paperclipai/shared";
|
||||
import { accessApi } from "./access";
|
||||
import { ApiError, detachInflightGet } from "./client";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
|
||||
export function boardAccessQueryOptions(
|
||||
userId: string | null,
|
||||
bootstrap: BoardBootstrap | undefined,
|
||||
updatedAt: number,
|
||||
onAccountChanged: () => void,
|
||||
) {
|
||||
const initialData = userId && bootstrap?.userId === userId && bootstrap.boardAccess.userId === userId
|
||||
? bootstrap.boardAccess
|
||||
: undefined;
|
||||
return {
|
||||
queryKey: [...queryKeys.access.currentBoardAccess, userId] as const,
|
||||
initialData,
|
||||
initialDataUpdatedAt: initialData ? updatedAt : undefined,
|
||||
queryFn: async (): Promise<BoardBootstrap["boardAccess"]> => {
|
||||
// Path-only request coalescing must not join reads from two accounts.
|
||||
detachInflightGet("/cli-auth/me");
|
||||
const access = await accessApi.getCurrentBoardAccess();
|
||||
if (access.userId !== userId) {
|
||||
onAccountChanged();
|
||||
throw new ApiError("The signed-in account changed. Checking your session again.", 401, { code: "session_changed" });
|
||||
}
|
||||
return { userId: access.userId, isInstanceAdmin: access.isInstanceAdmin, companyIds: access.companyIds };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useLayoutEffect } from "react";
|
||||
import { hashKey, useQuery, useQueryClient, type QueryClient, type UseQueryOptions } from "@tanstack/react-query";
|
||||
|
||||
const appliedSnapshots = new WeakMap<QueryClient, Map<string, object>>();
|
||||
|
||||
/** Apply each canonical session snapshot once, including when its account has cached reads. */
|
||||
export function useBootstrapQuery<TData>(
|
||||
options: UseQueryOptions<TData>,
|
||||
snapshot: { identity: object; data: TData; updatedAt: number } | undefined,
|
||||
) {
|
||||
const client = useQueryClient();
|
||||
const key = hashKey(options.queryKey);
|
||||
const pending = !!snapshot && (appliedSnapshots.get(client)?.get(key) !== snapshot.identity
|
||||
|| client.getQueryState(options.queryKey)?.data === undefined);
|
||||
const query = useQuery({ ...options, enabled: pending ? false : options.enabled });
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!snapshot || (appliedSnapshots.get(client)?.get(key) === snapshot.identity
|
||||
&& client.getQueryState(options.queryKey)?.data !== undefined)) return;
|
||||
let applied = appliedSnapshots.get(client);
|
||||
if (!applied) appliedSnapshots.set(client, applied = new Map());
|
||||
applied.set(key, snapshot.identity);
|
||||
// An older same-account read must not win after a fresh session snapshot.
|
||||
void client.cancelQueries({ queryKey: options.queryKey, exact: true });
|
||||
client.setQueryData(options.queryKey, snapshot.data, { updatedAt: snapshot.updatedAt });
|
||||
}, [client, key, options.queryKey, snapshot]);
|
||||
|
||||
// Effects run after render. Publish the canonical snapshot immediately so
|
||||
// cached membership/access from an earlier visit cannot reach consumers.
|
||||
// Once applied, ordinary readers and mutations own this entry again.
|
||||
return pending && snapshot ? {
|
||||
...query, data: snapshot.data, dataUpdatedAt: snapshot.updatedAt,
|
||||
status: "success" as const, fetchStatus: "idle" as const,
|
||||
error: null, failureReason: null, failureCount: 0,
|
||||
isLoading: false, isPending: false, isFetching: false, isRefetching: false,
|
||||
isError: false, isSuccess: true, isLoadingError: false, isRefetchError: false,
|
||||
} : query;
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useQuery, type QueryClient } from "@tanstack/react-query";
|
||||
import type { Company } from "@paperclipai/shared";
|
||||
import type { BoardBootstrap, Company } from "@paperclipai/shared";
|
||||
import { authApi } from "./auth";
|
||||
import { companiesApi } from "./companies";
|
||||
import { ApiError } from "./client";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { useBootstrapQuery } from "./bootstrap-query";
|
||||
|
||||
export type CompanyListResult = { companies: Company[]; unauthorized: boolean };
|
||||
|
||||
@@ -73,9 +74,19 @@ const sessionQueryOptions = {
|
||||
* So: settled on success only. A failed session lookup leaves the list unfetched
|
||||
* until the query recovers, which it does on the next refetch.
|
||||
*/
|
||||
export function useAccountIdentity(): { userId: string | null; settled: boolean; failed: boolean } {
|
||||
const { data: session, isSuccess, isError } = useQuery(sessionQueryOptions);
|
||||
return { userId: session?.user.id ?? null, settled: isSuccess, failed: isError };
|
||||
export function useAccountIdentity(): {
|
||||
userId: string | null;
|
||||
settled: boolean;
|
||||
failed: boolean;
|
||||
bootstrap: BoardBootstrap | undefined;
|
||||
updatedAt: number;
|
||||
} {
|
||||
const { data: session, isSuccess, isError, dataUpdatedAt } = useQuery(sessionQueryOptions);
|
||||
const userId = session?.user.id ?? null;
|
||||
return {
|
||||
userId, settled: isSuccess, failed: isError, updatedAt: dataUpdatedAt,
|
||||
bootstrap: isSuccess && session?.boardBootstrap?.userId === userId ? session.boardBootstrap : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,12 +98,12 @@ export function useAccountIdentity(): { userId: string | null; settled: boolean;
|
||||
export function useCompanyListQuery(
|
||||
options: { enabled?: boolean; staleTime?: number; retry?: number | boolean } = {},
|
||||
) {
|
||||
const { userId, settled } = useAccountIdentity();
|
||||
const query = useQuery<CompanyListResult>({
|
||||
const { userId, settled, bootstrap, updatedAt } = useAccountIdentity();
|
||||
const query = useBootstrapQuery<CompanyListResult>({
|
||||
...companyListQueryOptions(userId),
|
||||
...options,
|
||||
enabled: settled && (options.enabled ?? true),
|
||||
});
|
||||
}, bootstrap ? { identity: bootstrap, data: { companies: bootstrap.companies, unauthorized: false }, updatedAt } : undefined);
|
||||
|
||||
// While the account is unknown this query is disabled, and a disabled query
|
||||
// reports `isLoading: false` with `data: undefined` — which consumers default
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
AskUserQuestionsAnswer,
|
||||
Approval,
|
||||
CompactIssue,
|
||||
InboxMineSnapshot,
|
||||
CreateIssueTreeHold,
|
||||
DocumentRevision,
|
||||
FeedbackTargetType,
|
||||
@@ -281,6 +282,11 @@ function issueListSearchParams(filters?: IssueListFilters) {
|
||||
}
|
||||
|
||||
export const issuesApi = {
|
||||
inboxMine: (companyId: string, options?: RequestOptions) => {
|
||||
const path = `/companies/${companyId}/inbox/mine`;
|
||||
detachInflightGet(path);
|
||||
return api.get<InboxMineSnapshot>(path, { ...options, cache: "no-store" });
|
||||
},
|
||||
summaries: async (companyId: string, issueIds: readonly string[], options?: RequestOptions): Promise<IssueSummary[]> => {
|
||||
if (issueIds.length > ISSUE_SUMMARIES_MAX_IDS) throw new Error("Too many issue summary IDs");
|
||||
const ids = [...new Set(issueIds.map((id) => id.trim().toLowerCase()))].sort();
|
||||
|
||||
@@ -27,7 +27,7 @@ const responses: Record<string, unknown> = {
|
||||
user: { id: "user", name: "Operator", email: "operator@example.com", image: null },
|
||||
sentryDsn: null,
|
||||
},
|
||||
"/api/cli-auth/me": { isInstanceAdmin: false, companyIds: ["company"] },
|
||||
"/api/cli-auth/me": { userId: "user", isInstanceAdmin: false, companyIds: ["company"] },
|
||||
};
|
||||
const checks = [
|
||||
["/api/health", queryKeys.health],
|
||||
@@ -104,6 +104,50 @@ describe("CloudAccessGate restart recovery", () => {
|
||||
await flushReact();
|
||||
}
|
||||
|
||||
it("opens from same-session board access without another startup request", async () => {
|
||||
const previous = responses["/api/auth/get-session"];
|
||||
responses["/api/auth/get-session"] = { ...(previous as object), boardBootstrap: {
|
||||
userId: "user", companies: [], boardAccess: { userId: "user", isInstanceAdmin: false, companyIds: ["company"] },
|
||||
} };
|
||||
try {
|
||||
await render();
|
||||
expect(container.querySelector("textarea")).not.toBeNull();
|
||||
expect(callsTo("/api/cli-auth/me")).toBe(0);
|
||||
void client.invalidateQueries({ queryKey: queryKeys.access.currentBoardAccess });
|
||||
await flushReact();
|
||||
expect(callsTo("/api/cli-auth/me")).toBe(1);
|
||||
} finally { responses["/api/auth/get-session"] = previous; }
|
||||
});
|
||||
|
||||
it("revokes cached board access when returning to an account with a new session snapshot", async () => {
|
||||
const previous = responses["/api/auth/get-session"];
|
||||
const boot = (userId: string, companyIds: string[]) => ({
|
||||
session: { id: `session-${userId}`, userId },
|
||||
user: { id: userId, name: "Operator", email: `${userId}@example.com`, image: null },
|
||||
sentryDsn: null,
|
||||
boardBootstrap: { userId, companies: [], boardAccess: { userId, isInstanceAdmin: false, companyIds } },
|
||||
});
|
||||
responses["/api/auth/get-session"] = boot("user", ["revoked-company"]);
|
||||
try {
|
||||
await render();
|
||||
expect(container.querySelector("textarea")).not.toBeNull();
|
||||
client.setQueryData(queryKeys.auth.session, boot("other", ["other-company"]));
|
||||
await flushReact();
|
||||
expect(container.querySelector("textarea")).not.toBeNull();
|
||||
client.setQueryData(queryKeys.auth.session, boot("user", []));
|
||||
await flushReact();
|
||||
expect(container.querySelector("textarea")).toBeNull();
|
||||
expect(client.getQueryData([...queryKeys.access.currentBoardAccess, "user"])).toMatchObject({ companyIds: [] });
|
||||
expect(callsTo("/api/cli-auth/me")).toBe(0);
|
||||
|
||||
// An ordinary post-bootstrap grant is allowed to replace that snapshot.
|
||||
void client.invalidateQueries({ queryKey: queryKeys.access.currentBoardAccess });
|
||||
await flushReact();
|
||||
expect(callsTo("/api/cli-auth/me")).toBe(1);
|
||||
expect(container.querySelector("textarea")).not.toBeNull();
|
||||
} finally { responses["/api/auth/get-session"] = previous; }
|
||||
});
|
||||
|
||||
it.each(checks)("recovers from an HTML response on %s without navigating", async (path) => {
|
||||
failingPath = path;
|
||||
await render();
|
||||
|
||||
@@ -5,6 +5,8 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { accessApi } from "@/api/access";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { authApi } from "@/api/auth";
|
||||
import { boardAccessQueryOptions } from "@/api/board-access-query";
|
||||
import { useBootstrapQuery } from "@/api/bootstrap-query";
|
||||
import { healthApi } from "@/api/health";
|
||||
import { isTemporaryApiError } from "@/api/response";
|
||||
import { useConnectivityStore } from "@/lib/connectivity";
|
||||
@@ -107,13 +109,20 @@ export function CloudAccessGate({ allowMembershipRequest = false }: { allowMembe
|
||||
if (sessionQuery.data) clearCloudSignInAttempt();
|
||||
}, [sessionQuery.data]);
|
||||
|
||||
const boardAccessQuery = useQuery({
|
||||
queryKey: queryKeys.access.currentBoardAccess,
|
||||
queryFn: () => accessApi.getCurrentBoardAccess(),
|
||||
const sessionBootstrap = sessionQuery.isSuccess ? sessionQuery.data?.boardBootstrap : undefined;
|
||||
const bootstrap = sessionBootstrap?.userId === sessionQuery.data?.user.id
|
||||
&& sessionBootstrap?.boardAccess.userId === sessionQuery.data?.user.id ? sessionBootstrap : undefined;
|
||||
const boardAccessQuery = useBootstrapQuery({
|
||||
...boardAccessQueryOptions(
|
||||
sessionQuery.data?.user.id ?? null,
|
||||
sessionQuery.data?.boardBootstrap,
|
||||
sessionQuery.dataUpdatedAt,
|
||||
() => { void queryClient.invalidateQueries({ queryKey: queryKeys.auth.session }); },
|
||||
),
|
||||
enabled: isAuthenticatedMode && !isBootstrapPending && !!sessionQuery.data,
|
||||
retry: retryWhileTransient,
|
||||
retryDelay: reconnectDelayFor,
|
||||
});
|
||||
}, bootstrap ? { identity: bootstrap, data: bootstrap.boardAccess, updatedAt: sessionQuery.dataUpdatedAt } : undefined);
|
||||
const claimMutation = useMutation({
|
||||
mutationFn: () => accessApi.claimBootstrapAdmin(),
|
||||
onSuccess: async () => {
|
||||
|
||||
@@ -236,6 +236,102 @@ describe("CompanyProvider", () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("seeds navigation from the session and preserves ordinary company invalidation", async () => {
|
||||
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: 30_000 } });
|
||||
mockAuthApi.getSession.mockResolvedValue({ ...sessionFor("one"), boardBootstrap: {
|
||||
userId: "one", companies: [makeCompany("bootstrap-company")],
|
||||
boardAccess: { userId: "one", isInstanceAdmin: false, companyIds: ["bootstrap-company"] },
|
||||
} });
|
||||
await act(() => root.render(<QueryClientProvider client={queryClient}><CompanyProvider>
|
||||
<Probe onSelectedCompanyId={() => {}} />
|
||||
</CompanyProvider></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("bootstrap-company"));
|
||||
expect(mockCompaniesApi.list).not.toHaveBeenCalled();
|
||||
expect(queryClient.getQueryData(queryKeys.companies.list("one"))).toMatchObject({ companies: [{ id: "bootstrap-company" }] });
|
||||
mockCompaniesApi.list.mockResolvedValue([makeCompany("fresh-company")]);
|
||||
await act(() => queryClient.invalidateQueries({ queryKey: queryKeys.companies.all }));
|
||||
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("fresh-company"));
|
||||
expect(mockCompaniesApi.list).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("never exposes the previous account's selection while a new bootstrap is ready", async () => {
|
||||
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: 30_000 } });
|
||||
const boot = (userId: string) => ({ ...sessionFor(userId), boardBootstrap: {
|
||||
userId, companies: [makeCompany(`company-${userId}`)],
|
||||
boardAccess: { userId, isInstanceAdmin: false, companyIds: [`company-${userId}`] },
|
||||
} });
|
||||
mockAuthApi.getSession.mockResolvedValue(boot("one"));
|
||||
const snapshots: Array<{ selected: string | null; company: string | undefined }> = [];
|
||||
function AccountProbe() {
|
||||
const current = useCompany();
|
||||
snapshots.push({ selected: current.selectedCompanyId, company: current.companies[0]?.id });
|
||||
return null;
|
||||
}
|
||||
await act(() => root.render(<QueryClientProvider client={queryClient}><CompanyProvider><AccountProbe /></CompanyProvider></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(snapshots.at(-1)?.selected).toBe("company-one"));
|
||||
await act(() => { queryClient.setQueryData(queryKeys.auth.session, boot("two")); });
|
||||
await vi.waitFor(() => expect(snapshots.at(-1)?.selected).toBe("company-two"));
|
||||
expect(snapshots.filter(value => value.company === "company-two").some(value => value.selected === "company-one")).toBe(false);
|
||||
expect(mockCompaniesApi.list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("replaces a returning account's cached companies with its revoked session snapshot once", async () => {
|
||||
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: Infinity } });
|
||||
const boot = (userId: string, ids: string[]) => ({ ...sessionFor(userId), boardBootstrap: {
|
||||
userId, companies: ids.map(makeCompany),
|
||||
boardAccess: { userId, isInstanceAdmin: false, companyIds: ids },
|
||||
} });
|
||||
const seen: Array<{ selected: string | null; companies: string[] }> = [];
|
||||
function AccountProbe() {
|
||||
const current = useCompany();
|
||||
seen.push({ selected: current.selectedCompanyId, companies: current.companies.map(company => company.id) });
|
||||
return null;
|
||||
}
|
||||
mockAuthApi.getSession.mockResolvedValue(boot("one", ["revoked-company"]));
|
||||
await act(() => root.render(<QueryClientProvider client={queryClient}><CompanyProvider><AccountProbe /></CompanyProvider></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(seen.at(-1)?.selected).toBe("revoked-company"));
|
||||
await act(() => { queryClient.setQueryData(queryKeys.auth.session, boot("two", ["company-two"])); });
|
||||
await vi.waitFor(() => expect(seen.at(-1)?.selected).toBe("company-two"));
|
||||
const returningAt = seen.length;
|
||||
await act(() => { queryClient.setQueryData(queryKeys.auth.session, boot("one", [])); });
|
||||
await vi.waitFor(() => expect(seen.at(-1)).toEqual({ selected: null, companies: [] }));
|
||||
expect(seen.slice(returningAt).some(value => value.companies.includes("revoked-company"))).toBe(false);
|
||||
expect(queryClient.getQueryData(queryKeys.companies.list("one"))).toEqual({ companies: [], unauthorized: false });
|
||||
expect(mockCompaniesApi.list).not.toHaveBeenCalled();
|
||||
|
||||
// The session seed must not overwrite a later authoritative read.
|
||||
mockCompaniesApi.list.mockResolvedValue([makeCompany("new-membership")]);
|
||||
await act(() => queryClient.invalidateQueries({ queryKey: queryKeys.companies.all }));
|
||||
await vi.waitFor(() => expect(seen.at(-1)?.selected).toBe("new-membership"));
|
||||
expect(mockCompaniesApi.list).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reseeds a collected bootstrap query and restores ordinary reads after remount", async () => {
|
||||
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: Infinity, gcTime: 0 } });
|
||||
const bootstrap = {
|
||||
userId: "one", companies: [makeCompany("bootstrap-company")],
|
||||
boardAccess: { userId: "one", isInstanceAdmin: false, companyIds: ["bootstrap-company"] },
|
||||
};
|
||||
mockAuthApi.getSession.mockResolvedValue({ ...sessionFor("one"), boardBootstrap: bootstrap });
|
||||
const render = (mounted: boolean) => root.render(<QueryClientProvider client={queryClient}>
|
||||
{mounted ? <CompanyProvider><Probe onSelectedCompanyId={() => {}} /></CompanyProvider> : null}
|
||||
</QueryClientProvider>);
|
||||
await act(() => render(true));
|
||||
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("bootstrap-company"));
|
||||
expect(mockCompaniesApi.list).not.toHaveBeenCalled();
|
||||
await act(() => render(false));
|
||||
await vi.waitFor(() => expect(queryClient.getQueryState(queryKeys.companies.list("one"))).toBeUndefined());
|
||||
captured = null;
|
||||
await act(() => render(true));
|
||||
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("bootstrap-company"));
|
||||
|
||||
mockCompaniesApi.list.mockResolvedValue([makeCompany("ordinary-reader-company")]);
|
||||
await act(() => queryClient.invalidateQueries({ queryKey: queryKeys.companies.all }));
|
||||
await vi.waitFor(() => expect(mockCompaniesApi.list).toHaveBeenCalledOnce());
|
||||
await vi.waitFor(() => expect(captured?.selectedCompanyId).toBe("ordinary-reader-company"));
|
||||
expect(queryClient.getQueryData(queryKeys.companies.list("one"))).toMatchObject({ companies: [{ id: "ordinary-reader-company" }] });
|
||||
});
|
||||
|
||||
it("publishes the URL company without first exposing the remembered company", async () => {
|
||||
const previousUrl = window.location.href;
|
||||
window.history.replaceState(null, "", "/TWO/issues");
|
||||
|
||||
@@ -144,6 +144,8 @@ export function CompanyProvider({ children }: { children: ReactNode }) {
|
||||
// cannot inherit it.
|
||||
const { userId: sessionUserId, settled: isSessionSettled } = useAccountIdentity();
|
||||
const observedUserIdRef = useRef<string | null | undefined>(undefined);
|
||||
const selectionBelongsToPreviousAccount = isSessionSettled
|
||||
&& observedUserIdRef.current !== undefined && observedUserIdRef.current !== sessionUserId;
|
||||
|
||||
useEffect(() => {
|
||||
// Until the session settles the account is unknown, not changed.
|
||||
@@ -259,14 +261,14 @@ export function CompanyProvider({ children }: { children: ReactNode }) {
|
||||
);
|
||||
|
||||
const selectedCompany = useMemo(
|
||||
() => companies.find((company) => company.id === selectedCompanyId) ?? null,
|
||||
[companies, selectedCompanyId],
|
||||
() => selectionBelongsToPreviousAccount ? null : companies.find((company) => company.id === selectedCompanyId) ?? null,
|
||||
[companies, selectedCompanyId, selectionBelongsToPreviousAccount],
|
||||
);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
companies,
|
||||
selectedCompanyId,
|
||||
selectedCompanyId: selectionBelongsToPreviousAccount ? null : selectedCompanyId,
|
||||
selectedCompany,
|
||||
selectionSource,
|
||||
loading: isLoading,
|
||||
@@ -280,6 +282,7 @@ export function CompanyProvider({ children }: { children: ReactNode }) {
|
||||
[
|
||||
companies,
|
||||
selectedCompanyId,
|
||||
selectionBelongsToPreviousAccount,
|
||||
selectedCompany,
|
||||
selectionSource,
|
||||
isLoading,
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// @vitest-environment node
|
||||
import { QueryClient, QueryObserver, type QueryKey } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
vi.mock("./CompanyContext", () => ({ useCompany: vi.fn() }));
|
||||
vi.mock("../api/auth", () => ({ authApi: { getSession: vi.fn() } }));
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { __liveUpdatesTestUtils } from "./LiveUpdatesProvider";
|
||||
|
||||
describe("live read receipts", () => {
|
||||
let client: QueryClient;
|
||||
let subscriptions: Array<() => void>;
|
||||
|
||||
beforeEach(() => {
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });
|
||||
subscriptions = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
subscriptions.forEach(unsubscribe => unsubscribe());
|
||||
client.clear();
|
||||
});
|
||||
|
||||
function watch(key: QueryKey, next: unknown = "fresh") {
|
||||
const collection = key[0] === "agent-chats" || key[0] === "issues" && key[1] !== "detail" && key[1] !== "activity";
|
||||
client.setQueryData(key, collection ? [] : "cached");
|
||||
const read = vi.fn(async () => next);
|
||||
const observer = new QueryObserver(client, { queryKey: key, queryFn: read });
|
||||
subscriptions.push(observer.subscribe(() => undefined));
|
||||
return read;
|
||||
}
|
||||
|
||||
function receipt(action: string, userId: string, actorId = userId) {
|
||||
__liveUpdatesTestUtils.invalidateActivityQueries(client, "company-1", {
|
||||
entityType: "issue", entityId: "task-1", action, actorType: "user", actorId,
|
||||
details: { userId },
|
||||
}, { userId: "viewer", agentId: null });
|
||||
}
|
||||
|
||||
it.each(["issue.read_marked", "issue.read_unmarked"])("refreshes the reader's personal views once without fetching task collections for %s", async action => {
|
||||
const mine = [...queryKeys.issues.listMineByMe("company-1"), "index", 100];
|
||||
const touched = queryKeys.issues.listTouchedByMe("company-1");
|
||||
const unread = queryKeys.issues.listUnreadTouchedByMe("company-1");
|
||||
const badges = queryKeys.sidebarBadges("company-1");
|
||||
const chats = queryKeys.agentChats.list("company-1", "viewer");
|
||||
const ownReads = [mine, touched, unread, badges, chats].map(key => watch(key));
|
||||
const unrelatedReads = [
|
||||
queryKeys.issues.list("company-1"),
|
||||
[...queryKeys.issues.list("company-1"), "row-context"],
|
||||
queryKeys.issues.listByProject("company-1", "project-1"),
|
||||
queryKeys.issues.detail("task-1"),
|
||||
queryKeys.dashboard("company-1"),
|
||||
queryKeys.agentChats.list("company-1", "other-viewer"),
|
||||
queryKeys.issues.listMineByMe("company-2"),
|
||||
].map(key => watch(key));
|
||||
|
||||
receipt(action, "viewer");
|
||||
|
||||
await vi.waitFor(() => expect(client.getQueryData(mine)).toBe("fresh"));
|
||||
ownReads.forEach(read => expect(read).toHaveBeenCalledOnce());
|
||||
unrelatedReads.forEach(read => expect(read).not.toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it.each(["viewer", "other-viewer"])("keeps company and task audit receipts fresh when %s reads", async reader => {
|
||||
const companyActivity = queryKeys.activity("company-1");
|
||||
const taskActivity = queryKeys.issues.activity("task-1");
|
||||
const otherActivity = queryKeys.issues.activity("other-task");
|
||||
const companyRead = watch(companyActivity, [{ action: "issue.read_marked", actorId: reader }]);
|
||||
const taskRead = watch(taskActivity, [{ action: "issue.read_marked", actorId: reader }]);
|
||||
const otherRead = watch(otherActivity);
|
||||
const mineRead = watch(queryKeys.issues.listMineByMe("company-1"));
|
||||
|
||||
receipt("issue.read_marked", reader);
|
||||
|
||||
await vi.waitFor(() => expect(client.getQueryData(companyActivity)).toEqual([{ action: "issue.read_marked", actorId: reader }]));
|
||||
await vi.waitFor(() => expect(client.getQueryData(taskActivity)).toEqual([{ action: "issue.read_marked", actorId: reader }]));
|
||||
expect(companyRead).toHaveBeenCalledOnce();
|
||||
expect(taskRead).toHaveBeenCalledOnce();
|
||||
expect(otherRead).not.toHaveBeenCalled();
|
||||
expect(mineRead).toHaveBeenCalledTimes(reader === "viewer" ? 1 : 0);
|
||||
});
|
||||
|
||||
it("uses the affected person rather than an incidental actor for private read state", async () => {
|
||||
const activity = queryKeys.activity("company-1");
|
||||
watch(activity);
|
||||
const mineRead = watch(queryKeys.issues.listMineByMe("company-1"));
|
||||
const badgesRead = watch(queryKeys.sidebarBadges("company-1"));
|
||||
const chatRead = watch(queryKeys.agentChats.list("company-1", "viewer"));
|
||||
|
||||
receipt("issue.read_unmarked", "other-viewer", "viewer");
|
||||
|
||||
await vi.waitFor(() => expect(client.getQueryData(activity)).toBe("fresh"));
|
||||
for (const read of [mineRead, badgesRead, chatRead]) expect(read).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refreshes the visible identifier's audit without reloading task detail", async () => {
|
||||
const detail = queryKeys.issues.detail("PAP-1");
|
||||
client.setQueryData(detail, { id: "task-1", companyId: "company-1", identifier: "PAP-1" });
|
||||
const activity = queryKeys.issues.activity("PAP-1");
|
||||
const read = watch(activity);
|
||||
__liveUpdatesTestUtils.invalidateActivityQueries(client, "company-1", {
|
||||
entityType: "issue", entityId: "task-1", action: "issue.read_marked",
|
||||
actorType: "user", actorId: "other-viewer", details: { userId: "other-viewer" },
|
||||
}, { userId: "viewer", agentId: null }, { pathname: "/PAP/issues/PAP-1", isForegrounded: true });
|
||||
await vi.waitFor(() => expect(client.getQueryData(activity)).toBe("fresh"));
|
||||
expect(read).toHaveBeenCalledOnce();
|
||||
expect(client.getQueryState(detail)?.isInvalidated).toBe(false);
|
||||
});
|
||||
|
||||
it.each(["queued", "failed", "succeeded"])("refreshes combined Mine state after a run becomes %s", async status => {
|
||||
const mine = [...queryKeys.issues.listMineByMe("company-1"), "index", 100];
|
||||
const next = [{ id: "task-1", companyId: "company-1", status }];
|
||||
const read = watch(mine, next);
|
||||
const otherCompanyRead = watch(queryKeys.issues.listMineByMe("company-2"));
|
||||
__liveUpdatesTestUtils.invalidateHeartbeatQueries(client, "company-1", {
|
||||
runId: "run-1", agentId: "agent-1", issueId: "task-1", status,
|
||||
});
|
||||
await vi.waitFor(() => expect(client.getQueryData(mine)).toEqual(next));
|
||||
expect(read).toHaveBeenCalledOnce();
|
||||
expect(otherCompanyRead).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still refreshes ordinary task mutations for every interested view", async () => {
|
||||
const list = queryKeys.issues.listByProject("company-1", "project-1");
|
||||
const dashboard = queryKeys.dashboard("company-1");
|
||||
const detail = queryKeys.issues.detail("task-1");
|
||||
const reads = [list, dashboard, detail].map(key => watch(key));
|
||||
const otherCompanyRead = watch(queryKeys.issues.list("company-2"));
|
||||
|
||||
receipt("issue.updated", "other-viewer");
|
||||
|
||||
await vi.waitFor(() => expect(client.getQueryData(detail)).toBe("fresh"));
|
||||
reads.forEach(read => expect(read).toHaveBeenCalled());
|
||||
expect(otherCompanyRead).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -333,6 +333,27 @@ function resolveIssueQueryRefs(
|
||||
return Array.from(refs);
|
||||
}
|
||||
|
||||
function resolveIssueActivityQueryRefs(
|
||||
queryClient: QueryClient,
|
||||
companyId: string,
|
||||
entityId: string,
|
||||
details: Record<string, unknown> | null,
|
||||
options?: { pathname?: string; isForegrounded?: boolean },
|
||||
): string[] {
|
||||
const refs = resolveIssueQueryRefs(queryClient, companyId, entityId, details);
|
||||
const visible = options?.pathname
|
||||
? resolveVisibleIssueRouteContext(queryClient, options.pathname, {
|
||||
isForegrounded: options.isForegrounded,
|
||||
})
|
||||
: null;
|
||||
if (visible && overlaps(visible.issueRefs, buildIssueRefsForPayload(entityId, details))
|
||||
&& !refs.includes(visible.routeIssueRef)) {
|
||||
// Authenticated events can omit the identifier used by the visible route.
|
||||
refs.push(visible.routeIssueRef);
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
|
||||
function resolveIssueToastContext(
|
||||
queryClient: QueryClient,
|
||||
companyId: string,
|
||||
@@ -1338,6 +1359,7 @@ function invalidateHeartbeatQueries(
|
||||
// Note: liveRuns(companyId) is intentionally NOT invalidated here — it is
|
||||
// event-sourced via applyRunLifecycleToCompanyLiveRuns in the caller.
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: ["costs", companyId] });
|
||||
@@ -1380,18 +1402,34 @@ function invalidateActivityQueries(
|
||||
currentActor: { userId: string | null; agentId: string | null },
|
||||
options?: { pathname?: string; isForegrounded?: boolean },
|
||||
) {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.activity(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(companyId) });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.sidebarBadges(companyId),
|
||||
});
|
||||
|
||||
const entityType = readString(payload.entityType);
|
||||
const entityId = readString(payload.entityId);
|
||||
const action = readString(payload.action);
|
||||
const actorType = readString(payload.actorType);
|
||||
const actorId = readString(payload.actorId);
|
||||
const details = readRecord(payload.details);
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.activity(companyId) });
|
||||
if (entityType === "issue" && (action === "issue.read_marked" || action === "issue.read_unmarked")) {
|
||||
// Audit views show read receipts, while unread state belongs to one person.
|
||||
if (entityId) {
|
||||
for (const ref of resolveIssueActivityQueryRefs(queryClient, companyId, entityId, details, options)) {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(ref) });
|
||||
}
|
||||
}
|
||||
const readerId = readString(details?.userId) ?? (actorType === "user" ? actorId : null);
|
||||
if (readerId && readerId === currentActor.userId) {
|
||||
for (const queryKey of [
|
||||
queryKeys.issues.listMineByMe(companyId),
|
||||
queryKeys.issues.listTouchedByMe(companyId),
|
||||
queryKeys.issues.listUnreadTouchedByMe(companyId),
|
||||
queryKeys.sidebarBadges(companyId),
|
||||
queryKeys.agentChats.list(companyId, readerId),
|
||||
]) queryClient.invalidateQueries({ queryKey });
|
||||
}
|
||||
return;
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(companyId) });
|
||||
const decisionProjectionChanged = entityType === "decision" ||
|
||||
["inbox.dismissed", "inbox.snoozed", "inbox.restored"].includes(action ?? "") ||
|
||||
action?.startsWith("issue.thread_interaction_") ||
|
||||
@@ -1492,11 +1530,12 @@ function invalidateActivityQueries(
|
||||
payload,
|
||||
{ isForegrounded: options.isForegrounded },
|
||||
);
|
||||
const issueRefs = resolveIssueQueryRefs(
|
||||
const issueRefs = resolveIssueActivityQueryRefs(
|
||||
queryClient,
|
||||
companyId,
|
||||
entityId,
|
||||
details,
|
||||
options,
|
||||
);
|
||||
const taskDocumentsChanged = !!action && ISSUE_DOCUMENT_ACTIVITY_ACTIONS.has(action);
|
||||
const caseWorkChanged = !!action && ISSUE_CASE_WORK_ACTIVITY_ACTIONS.has(action);
|
||||
@@ -1520,20 +1559,6 @@ function invalidateActivityQueries(
|
||||
},
|
||||
});
|
||||
}
|
||||
const visibleContext = options?.pathname
|
||||
? resolveVisibleIssueRouteContext(queryClient, options.pathname, {
|
||||
isForegrounded: options.isForegrounded,
|
||||
})
|
||||
: null;
|
||||
if (
|
||||
visibleContext &&
|
||||
overlaps(visibleContext.issueRefs, buildIssueRefsForPayload(entityId, details)) &&
|
||||
!issueRefs.includes(visibleContext.routeIssueRef)
|
||||
) {
|
||||
// Authenticated payloads omit the identifier. Include the visible
|
||||
// route's cache key when its loaded task matches the event's UUID.
|
||||
issueRefs.push(visibleContext.routeIssueRef);
|
||||
}
|
||||
for (const ref of issueRefs) {
|
||||
const invalidationOptions =
|
||||
selfCommentActivity ||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { QueryClient, QueryObserver } from "@tanstack/react-query";
|
||||
import {
|
||||
createCoalescingQueryClient,
|
||||
createInvalidationBatcher,
|
||||
@@ -149,3 +149,118 @@ describe("createCoalescingQueryClient", () => {
|
||||
expect(realInvalidate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("overlapping live invalidations", () => {
|
||||
it.each([false, true])("does not restart a request already covered by its collection invalidation (child first=%s)", async childFirst => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });
|
||||
const key = ["issues", "company-1", "mine-by-me", "index"];
|
||||
client.setQueryData(key, "cached");
|
||||
const completions: Array<() => void> = [];
|
||||
const aborted = vi.fn();
|
||||
const read = vi.fn(({ signal }: { signal: AbortSignal }) => new Promise<string>((resolve, reject) => {
|
||||
completions.push(() => resolve("fresh"));
|
||||
signal.addEventListener("abort", () => { aborted(); reject(signal.reason); }, { once: true });
|
||||
}));
|
||||
const observer = new QueryObserver(client, { queryKey: key, queryFn: read });
|
||||
const unsubscribe = observer.subscribe(() => undefined);
|
||||
const batcher = createInvalidationBatcher(client);
|
||||
try {
|
||||
const filters = [{ queryKey: ["issues", "company-1"] }, { queryKey: ["issues", "company-1", "mine-by-me"] }];
|
||||
for (const filter of childFirst ? filters.reverse() : filters) void batcher.schedule(filter);
|
||||
const flushed = batcher.flush();
|
||||
completions.forEach(complete => complete());
|
||||
await flushed;
|
||||
expect(client.getQueryData(key)).toBe("fresh");
|
||||
expect(read).toHaveBeenCalledOnce();
|
||||
expect(aborted).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
batcher.dispose();
|
||||
unsubscribe();
|
||||
client.clear();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["exact", "type", "stale", "refetch", "predicate"])("preserves a child refresh when the parent has a different %s constraint", async constraint => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });
|
||||
const key = ["issues", "company-1", "mine-by-me"];
|
||||
client.setQueryData(key, "cached");
|
||||
const read = vi.fn(async () => "fresh");
|
||||
const observer = new QueryObserver(client, { queryKey: key, queryFn: read });
|
||||
const unsubscribe = observer.subscribe(() => undefined);
|
||||
const batcher = createInvalidationBatcher(client);
|
||||
try {
|
||||
const parent = {
|
||||
queryKey: ["issues", "company-1"],
|
||||
...(constraint === "exact" ? { exact: true } : {}),
|
||||
...(constraint === "type" ? { type: "inactive" as const } : {}),
|
||||
...(constraint === "stale" ? { stale: true } : {}),
|
||||
...(constraint === "refetch" ? { refetchType: "none" as const } : {}),
|
||||
...(constraint === "predicate" ? { predicate: () => false } : {}),
|
||||
};
|
||||
void batcher.schedule(parent);
|
||||
void batcher.schedule({ queryKey: key });
|
||||
await batcher.flush();
|
||||
expect(client.getQueryData(key)).toBe("fresh");
|
||||
expect(read).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
batcher.dispose();
|
||||
unsubscribe();
|
||||
client.clear();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["stale", "fetchStatus"])("retains distinct %s filters on the same key", async constraint => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });
|
||||
const key = ["issues", "company-1"];
|
||||
client.setQueryData(key, "cached");
|
||||
const observer = new QueryObserver(client, { queryKey: key, queryFn: async () => "fresh" });
|
||||
const unsubscribe = observer.subscribe(() => undefined);
|
||||
const batcher = createInvalidationBatcher(client);
|
||||
try {
|
||||
if (constraint === "stale") {
|
||||
void batcher.schedule({ queryKey: key, stale: false });
|
||||
void batcher.schedule({ queryKey: key, stale: true });
|
||||
} else {
|
||||
void batcher.schedule({ queryKey: key, fetchStatus: "idle" });
|
||||
void batcher.schedule({ queryKey: key, fetchStatus: "paused" });
|
||||
}
|
||||
await batcher.flush();
|
||||
expect(client.getQueryData(key)).toBe("fresh");
|
||||
} finally {
|
||||
batcher.dispose();
|
||||
unsubscribe();
|
||||
client.clear();
|
||||
}
|
||||
});
|
||||
|
||||
it("starts a newer read when another event arrives in a later batch", async () => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });
|
||||
const key = ["issues", "company-1", "mine-by-me"];
|
||||
client.setQueryData(key, 0);
|
||||
let serverValue = 1;
|
||||
const completions: Array<() => void> = [];
|
||||
const read = vi.fn(({ signal }: { signal: AbortSignal }) => new Promise<number>((resolve, reject) => {
|
||||
const snapshot = serverValue;
|
||||
completions.push(() => resolve(snapshot));
|
||||
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
||||
}));
|
||||
const observer = new QueryObserver(client, { queryKey: key, queryFn: read });
|
||||
const unsubscribe = observer.subscribe(() => undefined);
|
||||
const batcher = createInvalidationBatcher(client);
|
||||
try {
|
||||
void batcher.schedule({ queryKey: ["issues", "company-1"] });
|
||||
const first = batcher.flush();
|
||||
serverValue = 2;
|
||||
void batcher.schedule({ queryKey: key });
|
||||
const second = batcher.flush();
|
||||
completions.forEach(complete => complete());
|
||||
await Promise.all([first, second]);
|
||||
expect(read).toHaveBeenCalledTimes(2);
|
||||
expect(client.getQueryData(key)).toBe(2);
|
||||
} finally {
|
||||
batcher.dispose();
|
||||
unsubscribe();
|
||||
client.clear();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -60,7 +60,7 @@ export function createInvalidationBatcher(
|
||||
deferred?.resolve();
|
||||
return;
|
||||
}
|
||||
const filtersList = [...pending.values()];
|
||||
const filtersList = removeCoveredFilters([...pending.values()]);
|
||||
pending.clear();
|
||||
try {
|
||||
await Promise.all(filtersList.map((filters) => queryClient.invalidateQueries(
|
||||
@@ -98,6 +98,42 @@ export function createInvalidationBatcher(
|
||||
|
||||
let uniqueFilterCounter = 0;
|
||||
|
||||
function filterBehaviorKey(filters: InvalidateQueryFilters): string {
|
||||
return JSON.stringify([
|
||||
filters.type ?? "all",
|
||||
filters.refetchType ?? filters.type ?? "active",
|
||||
filters.stale ?? null,
|
||||
filters.fetchStatus ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
/** A collection prefix already refreshes its children in the same batch. */
|
||||
function removeCoveredFilters(filters: InvalidateQueryFilters[]): InvalidateQueryFilters[] {
|
||||
const prefixesByBehavior = new Map<string, Set<string>>();
|
||||
const isScalar = (value: unknown) => value === null || typeof value === "string"
|
||||
|| typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
||||
for (const filter of filters) {
|
||||
if (filter.predicate || filter.exact || !filter.queryKey?.every(isScalar)) continue;
|
||||
const behavior = filterBehaviorKey(filter);
|
||||
const prefixes = prefixesByBehavior.get(behavior) ?? new Set<string>();
|
||||
prefixes.add(JSON.stringify(filter.queryKey));
|
||||
prefixesByBehavior.set(behavior, prefixes);
|
||||
}
|
||||
return filters.filter(filter => {
|
||||
if (filter.predicate || !filter.queryKey) return true;
|
||||
const prefixes = prefixesByBehavior.get(filterBehaviorKey(filter));
|
||||
if (!prefixes) return true;
|
||||
const key = filter.queryKey;
|
||||
// A non-exact filter covers itself, so only check its shorter prefixes.
|
||||
const last = filter.exact ? key.length : key.length - 1;
|
||||
for (let length = 0; length <= last; length += 1) {
|
||||
if (length > 0 && !isScalar(key[length - 1])) break;
|
||||
if (prefixes.has(JSON.stringify(key.slice(0, length)))) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function serializeFilters(filters: InvalidateQueryFilters): string {
|
||||
// A predicate is an opaque function — two predicate-based filters can never be
|
||||
// proven equal, so never coalesce them (that would silently drop one). Give
|
||||
@@ -105,14 +141,14 @@ function serializeFilters(filters: InvalidateQueryFilters): string {
|
||||
if (typeof filters.predicate === "function") {
|
||||
return `__predicate__:${(uniqueFilterCounter += 1)}`;
|
||||
}
|
||||
// queryKey drives the identity; refetchType/exact/type change the behavior, so
|
||||
// keep them distinct while still collapsing exact repeats.
|
||||
// Query selection and refetch behavior both belong to the identity. In
|
||||
// particular, dropping an idle/fresh filter in favor of a paused/stale one
|
||||
// can lose the only refresh that actually matches a cached query.
|
||||
try {
|
||||
return JSON.stringify([
|
||||
filters.queryKey ?? null,
|
||||
filters.refetchType ?? null,
|
||||
filters.exact ?? null,
|
||||
filters.type ?? null,
|
||||
filterBehaviorKey(filters),
|
||||
filters.exact ?? false,
|
||||
]);
|
||||
} catch {
|
||||
// Non-serializable filter (shouldn't happen for our query keys) — fall back
|
||||
|
||||
+371
-74
@@ -6,9 +6,10 @@ import type { ComponentProps } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { Approval, HeartbeatRun, Issue } from "@paperclipai/shared";
|
||||
import type { Approval, CompactIssue, HeartbeatRun, InboxMineSnapshot, Issue } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { CompanyJoinRequest } from "../api/access";
|
||||
import { ApiError } from "../api/client";
|
||||
import {
|
||||
clearLocalInboxArchive,
|
||||
getLocalInboxArchiveIssueIds,
|
||||
@@ -35,6 +36,7 @@ const apiMocks = vi.hoisted(() => ({
|
||||
dashboardSummary: vi.fn(),
|
||||
executionWorkspaceSummaries: vi.fn(),
|
||||
issuesList: vi.fn(),
|
||||
inboxMine: vi.fn(),
|
||||
issuesCount: vi.fn(),
|
||||
issueLabels: vi.fn(),
|
||||
retryTask: vi.fn(),
|
||||
@@ -78,6 +80,7 @@ vi.mock("../api/issues", () => ({
|
||||
issuesApi: {
|
||||
list: apiMocks.issuesList,
|
||||
listCompact: apiMocks.issuesList,
|
||||
inboxMine: apiMocks.inboxMine,
|
||||
count: apiMocks.issuesCount,
|
||||
listLabels: apiMocks.issueLabels,
|
||||
retryTask: apiMocks.retryTask,
|
||||
@@ -180,7 +183,9 @@ if (typeof Element !== "undefined" && !Element.prototype.scrollIntoView) {
|
||||
Element.prototype.scrollIntoView = () => {};
|
||||
}
|
||||
|
||||
function createIssue(overrides: Partial<Issue> = {}): Issue {
|
||||
type InboxIssueFixture = Issue & CompactIssue;
|
||||
|
||||
function createIssue(overrides: Partial<Issue> = {}): InboxIssueFixture {
|
||||
return {
|
||||
id: "issue-1",
|
||||
identifier: "PAP-904",
|
||||
@@ -224,6 +229,8 @@ function createIssue(overrides: Partial<Issue> = {}): Issue {
|
||||
isUnreadForMe: false,
|
||||
...overrides,
|
||||
workMode: overrides.workMode ?? "standard",
|
||||
activeRecoveryAction: overrides.activeRecoveryAction ?? null,
|
||||
successfulRunHandoff: overrides.successfulRunHandoff ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -344,9 +351,30 @@ function createFailedRun(overrides: Partial<HeartbeatRun> = {}): HeartbeatRun {
|
||||
};
|
||||
}
|
||||
|
||||
let mineFixture: InboxMineSnapshot;
|
||||
|
||||
function createMineSnapshot(overrides: Partial<InboxMineSnapshot> = {}): InboxMineSnapshot {
|
||||
return { userId: "local-board", issues: [], contextIssues: [], failureRuns: [], failureIssueIds: [], ...overrides };
|
||||
}
|
||||
|
||||
// Mine's API response is a complete server-owned snapshot. These fixture helpers
|
||||
// also populate the independent legacy/Recent readers without calling them from
|
||||
// the aggregate mock, so request-budget assertions observe actual client reads.
|
||||
function setIssueRows(rows: InboxIssueFixture[]) {
|
||||
apiMocks.issuesList.mockResolvedValue(rows);
|
||||
mineFixture = { ...mineFixture, issues: rows };
|
||||
}
|
||||
|
||||
function setFailureRuns(runs: HeartbeatRun[]) {
|
||||
apiMocks.heartbeatRunsList.mockResolvedValue(runs);
|
||||
mineFixture = { ...mineFixture, failureRuns: runs };
|
||||
}
|
||||
|
||||
function resetInboxApiMocks() {
|
||||
companyState.selectedCompanyId = "company-1";
|
||||
for (const mock of Object.values(apiMocks)) mock.mockReset();
|
||||
mineFixture = createMineSnapshot();
|
||||
apiMocks.inboxMine.mockImplementation(async () => mineFixture);
|
||||
externalObjectMocks.summaries.clear();
|
||||
externalObjectMocks.error = null;
|
||||
externalObjectMocks.retry.mockReset();
|
||||
@@ -366,14 +394,14 @@ function resetInboxApiMocks() {
|
||||
costs: { monthBudgetCents: 0, monthUtilizationPercent: 0 },
|
||||
});
|
||||
apiMocks.executionWorkspaceSummaries.mockResolvedValue([]);
|
||||
apiMocks.issuesList.mockResolvedValue([]);
|
||||
setIssueRows([]);
|
||||
apiMocks.issuesCount.mockResolvedValue({ count: 0 });
|
||||
apiMocks.issueLabels.mockResolvedValue([]);
|
||||
apiMocks.retryTask.mockReset().mockResolvedValue({ accepted: true, requestId: "retry-intent", presentation: null });
|
||||
apiMocks.archiveFromInbox.mockResolvedValue({ id: "issue-1", archivedAt: new Date() });
|
||||
apiMocks.unarchiveFromInbox.mockResolvedValue({ id: "issue-1", archivedAt: new Date() });
|
||||
apiMocks.agentsList.mockResolvedValue([]);
|
||||
apiMocks.heartbeatRunsList.mockResolvedValue([]);
|
||||
setFailureRuns([]);
|
||||
apiMocks.liveRunsForCompany.mockResolvedValue([]);
|
||||
apiMocks.experimentalSettings.mockResolvedValue({
|
||||
enableIsolatedWorkspaces: false,
|
||||
@@ -411,7 +439,8 @@ describe("Inbox toolbar", () => {
|
||||
apiMocks.experimentalSettings.mockResolvedValue({ enableIsolatedWorkspaces: false, enableStreamlinedUi: streamlined });
|
||||
routerMock.location.pathname = `/inbox/${tab}`;
|
||||
apiMocks.authSession.mockResolvedValue(userId ? { user: { id: userId }, session: { userId } } : null);
|
||||
apiMocks.heartbeatRunsList.mockResolvedValue([
|
||||
mineFixture.userId = userId ?? "local-board";
|
||||
setFailureRuns([
|
||||
createFailedRun({ id: "own-failure", agentId: "agent-1", responsibleUserId: "user-1" }),
|
||||
createFailedRun({ id: "other-failure", agentId: "agent-2", responsibleUserId: "user-2", status: "timed_out" }),
|
||||
createFailedRun({ id: "unowned-failure", agentId: "agent-3" }),
|
||||
@@ -425,8 +454,13 @@ describe("Inbox toolbar", () => {
|
||||
root.render(<QueryClientProvider client={queryClient}><Inbox /></QueryClientProvider>);
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(apiMocks.heartbeatRunsList).toHaveBeenCalled();
|
||||
if (tab === "mine" && userId) expect(apiMocks.inboxMine).toHaveBeenCalledOnce();
|
||||
if (tab !== "mine") expect(apiMocks.heartbeatRunsList).toHaveBeenCalled();
|
||||
expect(queryClient.isFetching()).toBe(0);
|
||||
if (tab === "mine" && !userId) {
|
||||
expect(apiMocks.inboxMine).not.toHaveBeenCalled();
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).toBeNull();
|
||||
}
|
||||
for (const id of visible) expect(container.querySelector(`a[href$="/runs/${id}"]`)).not.toBeNull();
|
||||
for (const id of hidden) expect(container.querySelector(`a[href$="/runs/${id}"]`)).toBeNull();
|
||||
});
|
||||
@@ -443,7 +477,7 @@ describe("Inbox toolbar", () => {
|
||||
enableIsolatedWorkspaces: false,
|
||||
enableStreamlinedUi: false,
|
||||
});
|
||||
apiMocks.issuesList.mockResolvedValue([
|
||||
setIssueRows([
|
||||
createIssue({ id: "legacy-row", identifier: "PAP-1904", title: "Legacy inbox task" }),
|
||||
]);
|
||||
localStorage.setItem(
|
||||
@@ -486,7 +520,7 @@ describe("Inbox toolbar", () => {
|
||||
it("does not render external-object summaries in inbox rows", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
const issue = createIssue({ title: "Inbox row without external object column" });
|
||||
apiMocks.issuesList.mockResolvedValue([issue]);
|
||||
setIssueRows([issue]);
|
||||
externalObjectMocks.summaries.set(issue.id, {
|
||||
total: 1,
|
||||
highestSeverity: "failed",
|
||||
@@ -519,7 +553,7 @@ describe("Inbox toolbar", () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
localStorage.setItem("paperclip:inbox:group-by", "none");
|
||||
apiMocks.approvalsList.mockResolvedValue([createApproval()]);
|
||||
apiMocks.heartbeatRunsList.mockResolvedValue([createFailedRun()]);
|
||||
setFailureRuns([createFailedRun()]);
|
||||
apiMocks.joinRequestsList.mockResolvedValue([createJoinRequest()]);
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
@@ -590,7 +624,7 @@ describe("Inbox toolbar", () => {
|
||||
parentId: child.id,
|
||||
title: "Deeply nested inbox task",
|
||||
});
|
||||
apiMocks.issuesList.mockResolvedValue([parent, child, grandchild]);
|
||||
setIssueRows([parent, child, grandchild]);
|
||||
|
||||
const mountInbox = async () => {
|
||||
const queryClient = new QueryClient({
|
||||
@@ -753,7 +787,7 @@ describe("Inbox toolbar", () => {
|
||||
const now = new Date();
|
||||
const localNoon = (daysAgo: number) =>
|
||||
new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysAgo, 12, 0, 0);
|
||||
apiMocks.issuesList.mockResolvedValue([
|
||||
setIssueRows([
|
||||
createIssue({ id: "today", title: "Today task", lastActivityAt: localNoon(0) }),
|
||||
createIssue({ id: "yesterday", title: "Yesterday task", lastActivityAt: localNoon(1) }),
|
||||
createIssue({ id: "earlier", title: "Earlier task", lastActivityAt: localNoon(3) }),
|
||||
@@ -803,7 +837,7 @@ describe("Inbox toolbar", () => {
|
||||
const now = new Date();
|
||||
const localNoon = (daysAgo: number) =>
|
||||
new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysAgo, 12, 0, 0);
|
||||
apiMocks.issuesList.mockResolvedValue([
|
||||
setIssueRows([
|
||||
createIssue({ id: "today", title: "Today task", lastActivityAt: localNoon(0) }),
|
||||
createIssue({ id: "earlier", title: "Earlier task", lastActivityAt: localNoon(3) }),
|
||||
]);
|
||||
@@ -844,7 +878,7 @@ describe("Inbox toolbar", () => {
|
||||
executionWorkspacePolicy: { defaultProjectWorkspaceId: "project-workspace-1" },
|
||||
primaryWorkspace: null,
|
||||
}]);
|
||||
apiMocks.issuesList.mockResolvedValue([createIssue({
|
||||
setIssueRows([createIssue({
|
||||
projectId: "project-1",
|
||||
executionWorkspaceId: "execution-workspace-1",
|
||||
title: "Workspace-aware task",
|
||||
@@ -910,22 +944,28 @@ describe("Inbox toolbar", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("waits for the task index before revealing faster failed-run rows", async () => {
|
||||
it("waits for the complete Mine bundle before revealing tasks or failed runs", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
let release: (rows: Issue[]) => void = () => undefined;
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => filters.projection === "index"
|
||||
? new Promise<Issue[]>((resolve) => { release = resolve; }) : Promise.resolve([]));
|
||||
apiMocks.heartbeatRunsList.mockResolvedValue([createFailedRun()]);
|
||||
const bundle = createDeferred<InboxMineSnapshot>();
|
||||
apiMocks.inboxMine.mockReturnValue(bundle.promise);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
await act(async () => root.render(<QueryClientProvider client={queryClient}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(apiMocks.heartbeatRunsList).toHaveBeenCalled());
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).not.toBeNull();
|
||||
expect(container.querySelector('[data-inbox-item]')).toBeNull();
|
||||
await act(async () => release([createIssue({ title: "Delayed task index row" })]));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Delayed task index row"));
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).toBeNull();
|
||||
act(() => root.unmount());
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={queryClient}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(apiMocks.inboxMine).toHaveBeenCalledOnce());
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).not.toBeNull();
|
||||
expect(container.querySelector('[data-inbox-item]')).toBeNull();
|
||||
expect(apiMocks.issuesList).not.toHaveBeenCalled();
|
||||
expect(apiMocks.heartbeatRunsList).not.toHaveBeenCalled();
|
||||
await act(() => bundle.resolve(createMineSnapshot({
|
||||
issues: [createIssue({ title: "Bundled task" })], failureRuns: [createFailedRun()],
|
||||
})));
|
||||
await vi.waitFor(() => {
|
||||
expect(container.textContent).toContain("Bundled task");
|
||||
expect(container.textContent).toContain("Failed run");
|
||||
});
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).toBeNull();
|
||||
} finally { await act(() => root.unmount()); queryClient.clear(); }
|
||||
});
|
||||
|
||||
it.each([true, false])("can select a company after a cold inbox mount (Streamlined UI=%s)", async streamlined => {
|
||||
@@ -939,14 +979,265 @@ describe("Inbox toolbar", () => {
|
||||
await act(render);
|
||||
await vi.waitFor(() => expect(container.textContent).toContain(streamlined ? "Select an organization" : "Select a company"));
|
||||
companyState.selectedCompanyId = "company-1";
|
||||
apiMocks.issuesList.mockResolvedValue([createIssue({ title: "Cold company task" })]);
|
||||
setIssueRows([createIssue({ title: "Cold company task" })]);
|
||||
await act(render);
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Cold company task"));
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("loads only missing parent metadata before revealing Mine", async () => {
|
||||
it("uses bundled parent and failure context without separate startup reads", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
const parent = createIssue({ id: "context-parent", title: "Bundled parent", listProjection: "index" });
|
||||
const task = createIssue({ id: "task", title: "Bundled child", parentId: parent.id, listProjection: "index" });
|
||||
const resolvedRun = createFailedRun({ id: "resolved-run", issueId: parent.id });
|
||||
const missingRun = createFailedRun({ id: "missing-run", issueId: "deleted-task", agentId: "missing-agent" });
|
||||
mineFixture = createMineSnapshot({
|
||||
issues: [task],
|
||||
contextIssues: [{ ...parent, listProjection: "rows", interruption: {
|
||||
intentId: "resolved-input", responsibility: "system", state: "resolved", nextRetryAt: null,
|
||||
canRetry: false, userAction: null, sourceRunIds: [resolvedRun.id], observedRunId: resolvedRun.id,
|
||||
} }],
|
||||
failureRuns: [resolvedRun, missingRun],
|
||||
failureIssueIds: [parent.id, "deleted-task"],
|
||||
});
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => Promise.resolve(
|
||||
filters.ids?.includes(task.id) ? [task] : [],
|
||||
));
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => {
|
||||
expect(container.textContent).toContain(task.title);
|
||||
expect(container.querySelector('a[href="/issues/deleted-task"]')).not.toBeNull();
|
||||
expect(client.isFetching()).toBe(0);
|
||||
});
|
||||
expect(container.querySelectorAll("[data-inbox-item]")).toHaveLength(2);
|
||||
expect(apiMocks.inboxMine).toHaveBeenCalledOnce();
|
||||
expect(apiMocks.heartbeatRunsList).not.toHaveBeenCalled();
|
||||
// Post-reveal diagnostics may read the visible task, but neither a primary
|
||||
// index nor parent/failure context is fetched by the Mine client.
|
||||
for (const [, filters] of apiMocks.issuesList.mock.calls) {
|
||||
expect(filters).toMatchObject({ projection: "rows", ids: [task.id] });
|
||||
}
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it("rejects a Mine bundle stamped for another account before caching its rows or context", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
mineFixture = createMineSnapshot({ userId: "other-account", issues: [createIssue({ title: "Private other-account task" })] });
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Your account changed. Refresh the inbox."));
|
||||
expect(container.textContent).not.toContain("Private other-account task");
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).toBeNull();
|
||||
expect(client.getQueryData([...queryKeys.issues.list("company-1"), "mine-context", "local-board"])).toBeUndefined();
|
||||
expect(apiMocks.issuesList).not.toHaveBeenCalled();
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it.each(["network", 429, 503] as const)("keeps cached Mine rows and their DOM nodes during a %s aggregate refresh failure", async status => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
setIssueRows([createIssue({ title: "Cached readable task" })]);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Cached readable task"));
|
||||
const row = container.querySelector("[data-inbox-item]");
|
||||
apiMocks.inboxMine.mockRejectedValue(status === "network" ? new Error("Refresh unavailable") : new ApiError("Refresh unavailable", status, null));
|
||||
await act(async () => { await client.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe("company-1") }); });
|
||||
await vi.waitFor(() => expect(document.body.textContent).toContain("Some inbox items couldn’t load."));
|
||||
expect(container.querySelector("[data-inbox-item]")).toBe(row);
|
||||
expect(container.textContent).toContain("Cached readable task");
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).toBeNull();
|
||||
expect(apiMocks.inboxMine).toHaveBeenCalledTimes(2);
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it.each([401, 403])("hides cached Mine rows after a %s access denial", async status => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
setIssueRows([createIssue({ title: "Previously accessible private task" })]);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
const message = `Company access denied (${status})`;
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Previously accessible private task"));
|
||||
apiMocks.inboxMine.mockRejectedValue(new ApiError(message, status, null));
|
||||
await act(async () => { await client.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe("company-1") }); });
|
||||
await vi.waitFor(() => expect(container.textContent).toContain(message));
|
||||
expect(container.textContent).not.toContain("Previously accessible private task");
|
||||
expect(container.querySelectorAll("[data-inbox-item]")).toHaveLength(0);
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).toBeNull();
|
||||
expect(apiMocks.inboxMine).toHaveBeenCalledTimes(2);
|
||||
expect(apiMocks.inboxMine).toHaveBeenLastCalledWith("company-1", expect.anything());
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it("fails closed when a refresh returns another account's bundle despite cached Mine rows", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
setIssueRows([createIssue({ title: "Previous authenticated task" })]);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Previous authenticated task"));
|
||||
apiMocks.inboxMine.mockResolvedValue(createMineSnapshot({
|
||||
userId: "another-account", issues: [createIssue({ title: "Another account secret" })],
|
||||
}));
|
||||
await act(async () => { await client.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe("company-1") }); });
|
||||
await vi.waitFor(() => {
|
||||
expect(container.textContent).toContain("Your account changed. Refresh the inbox.");
|
||||
expect(apiMocks.authSession).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
expect(container.textContent).not.toContain("Previous authenticated task");
|
||||
expect(container.textContent).not.toContain("Another account secret");
|
||||
expect(client.getQueryData<InboxMineSnapshot>([...queryKeys.issues.list("company-1"), "mine-context", "local-board"])?.userId).toBe("local-board");
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it("isolates an account switch from a late response for the previous account", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
const previous = createDeferred<InboxMineSnapshot>();
|
||||
const next = createDeferred<InboxMineSnapshot>();
|
||||
apiMocks.inboxMine.mockReturnValueOnce(previous.promise).mockReturnValueOnce(next.promise);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(apiMocks.inboxMine).toHaveBeenCalledOnce());
|
||||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "next-account" }, session: { userId: "next-account" } }); });
|
||||
await vi.waitFor(() => expect(apiMocks.inboxMine).toHaveBeenCalledTimes(2));
|
||||
await act(() => next.resolve(createMineSnapshot({ userId: "next-account", issues: [createIssue({ title: "Next account task" })] })));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Next account task"));
|
||||
await act(() => previous.resolve(createMineSnapshot({ issues: [createIssue({ title: "Previous account secret" })] })));
|
||||
await vi.waitFor(() => expect(client.isFetching()).toBe(0));
|
||||
expect(container.textContent).toContain("Next account task");
|
||||
expect(container.textContent).not.toContain("Previous account secret");
|
||||
expect(client.getQueryData<InboxMineSnapshot>([...queryKeys.issues.list("company-1"), "mine-context", "next-account"])?.userId).toBe("next-account");
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it("holds the initial reveal barrier for a new account in the same company", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
setIssueRows([createIssue({ title: "First account task" })]);
|
||||
const next = createDeferred<InboxMineSnapshot>();
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("First account task"));
|
||||
apiMocks.inboxMine.mockReturnValue(next.promise);
|
||||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "next-account" }, session: { userId: "next-account" } }); });
|
||||
await vi.waitFor(() => expect(apiMocks.inboxMine).toHaveBeenCalledTimes(2));
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).not.toBeNull();
|
||||
expect(container.querySelectorAll("[data-inbox-item]")).toHaveLength(0);
|
||||
expect(container.textContent).not.toContain("First account task");
|
||||
expect(container.textContent).not.toContain("Inbox zero.");
|
||||
await act(() => next.resolve(createMineSnapshot({
|
||||
userId: "next-account", issues: [createIssue({ title: "Second account task" })],
|
||||
})));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Second account task"));
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).toBeNull();
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it("keeps aggregate context scoped to the selected company", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
apiMocks.inboxMine.mockImplementation(async companyId => createMineSnapshot({
|
||||
issues: [createIssue({ id: `task-${companyId}`, companyId, title: `Task for ${companyId}` })],
|
||||
}));
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
const render = () => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>);
|
||||
try {
|
||||
await act(render);
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Task for company-1"));
|
||||
companyState.selectedCompanyId = "company-2";
|
||||
await act(render);
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Task for company-2"));
|
||||
expect(container.textContent).not.toContain("Task for company-1");
|
||||
expect(apiMocks.inboxMine).toHaveBeenCalledWith("company-2", expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(client.getQueryData<InboxMineSnapshot>([...queryKeys.issues.list("company-2"), "mine-context", "local-board"])?.issues[0]?.companyId).toBe("company-2");
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it("cannot reuse another account's private parent caption in a cached Mine fallback", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
localStorage.setItem("paperclip:inbox:nesting", "false");
|
||||
localStorage.setItem(taskCollectionPreferencesStorageKey({ companyId: "company-1", collectionKey: "inbox" }), JSON.stringify({
|
||||
version: 1, companyId: "company-1", collectionKey: "inbox", columns: ["parent"], viewState: {},
|
||||
}));
|
||||
const parent = createIssue({ id: "private-parent", title: "First account private caption", identifier: "PAP-SECRET", listProjection: "index" });
|
||||
const child = createIssue({ id: "shared-child", title: "Cached fallback child", parentId: parent.id, listProjection: "index" });
|
||||
const pendingParent = createDeferred<Issue[]>();
|
||||
const pendingBundle = createDeferred<InboxMineSnapshot>();
|
||||
let switched = false;
|
||||
apiMocks.inboxMine.mockRejectedValueOnce(new Error("Aggregate temporarily unavailable")).mockReturnValueOnce(pendingBundle.promise);
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => {
|
||||
if (filters.ids?.includes(parent.id)) return switched ? pendingParent.promise : Promise.resolve([parent]);
|
||||
return Promise.resolve([child]);
|
||||
});
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } });
|
||||
client.setQueryData(queryKeys.auth.session, { user: { id: "local-board" }, session: { userId: "local-board" } });
|
||||
const sourceKey = (userId: string) => [...queryKeys.issues.listMineByMe("company-1"), "index", "with-routine-executions", "live-descendant-summary", 100, userId];
|
||||
client.setQueryData(sourceKey("local-board"), [child]);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(container.querySelector(`[title="${parent.title}"]`)?.textContent).toBe(parent.identifier));
|
||||
switched = true;
|
||||
client.setQueryData(sourceKey("next-account"), [child]);
|
||||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "next-account" }, session: { userId: "next-account" } }); });
|
||||
await vi.waitFor(() => expect(apiMocks.inboxMine).toHaveBeenCalledTimes(2));
|
||||
expect(apiMocks.issuesList.mock.calls.filter(([, filters]) => filters.ids?.includes(parent.id))).toHaveLength(1);
|
||||
expect(container.querySelector(`[title="${parent.title}"]`)).toBeNull();
|
||||
await act(() => pendingBundle.reject(new Error("New account aggregate temporarily unavailable")));
|
||||
await vi.waitFor(() => expect(apiMocks.issuesList.mock.calls.filter(([, filters]) => filters.ids?.includes(parent.id))).toHaveLength(2));
|
||||
expect(container.querySelector(`[title="${parent.title}"]`)).toBeNull();
|
||||
expect(container.textContent).not.toContain(parent.identifier);
|
||||
await act(() => pendingParent.resolve([]));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain(child.title));
|
||||
expect(container.querySelector(`[title="${parent.title}"]`)).toBeNull();
|
||||
expect(container.textContent).not.toContain(parent.identifier);
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it("cannot reuse another account's resolved rich state for a fallback failure", async () => {
|
||||
routerMock.location.pathname = "/inbox/recent";
|
||||
const task = createIssue({ id: "private-failure-task", title: "First account failure context", listProjection: "rows" });
|
||||
const failure = createFailedRun({ issueId: task.id });
|
||||
setFailureRuns([failure]);
|
||||
const pendingContext = createDeferred<Issue[]>();
|
||||
let switched = false;
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => {
|
||||
if (!filters.ids?.includes(task.id)) return Promise.resolve([]);
|
||||
return switched ? pendingContext.promise : Promise.resolve([{ ...task, interruption: {
|
||||
intentId: "private-resolved", responsibility: "system", state: "resolved", nextRetryAt: null,
|
||||
canRetry: false, userAction: null, sourceRunIds: [failure.id], observedRunId: failure.id,
|
||||
} }]);
|
||||
});
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={client}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(client.isFetching()).toBe(0));
|
||||
expect(container.querySelector(`a[href="/issues/${task.id}"]`)).toBeNull();
|
||||
switched = true;
|
||||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "next-account" }, session: { userId: "next-account" } }); });
|
||||
await vi.waitFor(() => expect(apiMocks.issuesList.mock.calls.filter(([, filters]) => filters.ids?.includes(task.id))).toHaveLength(2));
|
||||
expect(container.textContent).not.toContain(task.title);
|
||||
await act(() => pendingContext.resolve([]));
|
||||
await vi.waitFor(() => expect(container.querySelector(`a[href="/issues/${task.id}"]`)).not.toBeNull());
|
||||
expect(container.textContent).not.toContain(task.title);
|
||||
} finally { await act(() => root.unmount()); client.clear(); }
|
||||
});
|
||||
|
||||
it("loads only missing parent metadata before revealing Recent", async () => {
|
||||
routerMock.location.pathname = "/inbox/recent";
|
||||
localStorage.setItem(taskCollectionPreferencesStorageKey({ companyId: "company-1", collectionKey: "inbox" }), JSON.stringify({
|
||||
version: 1, companyId: "company-1", collectionKey: "inbox", columns: ["parent"], viewState: {},
|
||||
}));
|
||||
@@ -983,7 +1274,7 @@ describe("Inbox toolbar", () => {
|
||||
});
|
||||
|
||||
it("discards old parent context when a refreshed index supplies the parent", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
routerMock.location.pathname = "/inbox/recent";
|
||||
localStorage.setItem("paperclip:inbox:nesting", "false");
|
||||
localStorage.setItem(taskCollectionPreferencesStorageKey({ companyId: "company-1", collectionKey: "inbox" }), JSON.stringify({
|
||||
version: 1, companyId: "company-1", collectionKey: "inbox", columns: ["parent"], viewState: {},
|
||||
@@ -1007,11 +1298,11 @@ describe("Inbox toolbar", () => {
|
||||
});
|
||||
|
||||
it.each([true, false])("waits for failure context even when its parent is already indexed=%s", async (indexed) => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
routerMock.location.pathname = "/inbox/recent";
|
||||
const parent = createIssue({ id: "parent", title: "Parent metadata", listProjection: "index" });
|
||||
const child = createIssue({ id: "child", parentId: parent.id, title: "Readable child", listProjection: "index" });
|
||||
const failure = createFailedRun({ issueId: parent.id, responsibleUserId: "local-board" });
|
||||
apiMocks.heartbeatRunsList.mockResolvedValue([failure]);
|
||||
setFailureRuns([failure]);
|
||||
let releaseFailure!: (rows: Issue[]) => void;
|
||||
const pendingFailure = new Promise<Issue[]>(resolve => { releaseFailure = resolve; });
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => !filters.ids
|
||||
@@ -1036,7 +1327,7 @@ describe("Inbox toolbar", () => {
|
||||
});
|
||||
|
||||
it("upgrades cached parent metadata when the same task becomes a failure context", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
routerMock.location.pathname = "/inbox/recent";
|
||||
const parent = createIssue({ id: "parent", title: "Parent metadata", listProjection: "index" });
|
||||
const child = createIssue({ id: "child", parentId: parent.id, title: "Readable child", listProjection: "index" });
|
||||
const failure = createFailedRun({ issueId: parent.id, responsibleUserId: "local-board" });
|
||||
@@ -1074,8 +1365,8 @@ describe("Inbox toolbar", () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
const parent = createIssue({ id: "parent", title: "Parent metadata", listProjection: "index" });
|
||||
const child = createIssue({ id: "child", parentId: parent.id, title: "Mine child", listProjection: "index" });
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => Promise.resolve(filters.ids
|
||||
? [parent] : filters.inboxArchivedByUserId ? [child] : []));
|
||||
mineFixture = createMineSnapshot({ issues: [child], contextIssues: [parent] });
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => Promise.resolve(filters.ids ? [parent] : []));
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
@@ -1089,7 +1380,7 @@ describe("Inbox toolbar", () => {
|
||||
});
|
||||
|
||||
it("waits for rich failure state when heartbeat data arrives after parent captions", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
routerMock.location.pathname = "/inbox/recent";
|
||||
const parent = createIssue({ id: "parent", title: "Parent metadata", listProjection: "index" });
|
||||
const child = createIssue({ id: "child", parentId: parent.id, title: "Mine child", listProjection: "index" });
|
||||
const failure = createFailedRun({ issueId: parent.id, responsibleUserId: "local-board" });
|
||||
@@ -1120,11 +1411,11 @@ describe("Inbox toolbar", () => {
|
||||
});
|
||||
|
||||
it("keeps known missing-task failures visible while new failure context is pending", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
routerMock.location.pathname = "/inbox/recent";
|
||||
const child = createIssue({ title: "Readable task", listProjection: "index" });
|
||||
const first = createFailedRun({ id: "failure-a", issueId: "missing-a", agentId: "agent-a", responsibleUserId: "local-board" });
|
||||
const second = createFailedRun({ id: "failure-b", issueId: "missing-b", agentId: "agent-b", responsibleUserId: "local-board" });
|
||||
apiMocks.heartbeatRunsList.mockResolvedValue([first]);
|
||||
setFailureRuns([first]);
|
||||
let releaseFailures!: (rows: Issue[]) => void;
|
||||
const pendingFailures = new Promise<Issue[]>(resolve => { releaseFailures = resolve; });
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => !filters.ids ? Promise.resolve([child])
|
||||
@@ -1151,6 +1442,7 @@ describe("Inbox toolbar", () => {
|
||||
it("keeps more than 25 description-only matches in Mine with archive actions", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
const rows = Array.from({ length: 30 }, (_, index) => createIssue({ id: `source-${index}`, title: `Source task ${index}`, identifier: `PAP-${index}`, listProjection: "index" }));
|
||||
mineFixture = createMineSnapshot({ issues: rows });
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => Promise.resolve(filters.q && !filters.ids ? [] : rows));
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
@@ -1171,6 +1463,7 @@ describe("Inbox toolbar", () => {
|
||||
it("keeps rows readable and offers retry when optional details fail", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
let failDetails = true;
|
||||
mineFixture = createMineSnapshot({ issues: [createIssue({ title: "Readable task" })] });
|
||||
apiMocks.issuesList.mockImplementation((_company, filters) => filters.projection === "rows" && failDetails
|
||||
? Promise.reject(new Error("Details unavailable")) : Promise.resolve([createIssue({ title: "Readable task" })]));
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
@@ -1188,14 +1481,14 @@ describe("Inbox toolbar", () => {
|
||||
it("refreshes diagnostics when a visible index row changes without changing its ID", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
const row = createIssue({ title: "Live task", listProjection: "index" });
|
||||
apiMocks.issuesList.mockResolvedValue([row]);
|
||||
setIssueRows([row]);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
await act(() => root.render(<QueryClientProvider client={queryClient}><Inbox /></QueryClientProvider>));
|
||||
const detailsReads = () => apiMocks.issuesList.mock.calls.filter(([, filters]) => filters.projection === "rows").length;
|
||||
await vi.waitFor(() => expect(detailsReads()).toBe(1));
|
||||
const updated = { ...row, updatedAt: new Date(new Date(row.updatedAt).getTime() + 1000) };
|
||||
apiMocks.issuesList.mockResolvedValue([updated]);
|
||||
setIssueRows([updated]);
|
||||
await act(() => {
|
||||
queryClient.setQueriesData({ predicate: (query) => query.queryKey.includes("index") }, [updated]);
|
||||
});
|
||||
@@ -1204,25 +1497,31 @@ describe("Inbox toolbar", () => {
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it.each(["approvalsList", "joinRequestsList", "heartbeatRunsList"] as const)(
|
||||
it.each(["approvalsList", "joinRequestsList", "failureError", "contextError"] as const)(
|
||||
"keeps available tasks visible when %s fails and during retry", async (source) => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
apiMocks.issuesList.mockResolvedValue([createIssue({ title: "Available task" })]);
|
||||
apiMocks[source].mockRejectedValue(new Error("Optional source unavailable"));
|
||||
setIssueRows([createIssue({ title: "Available task" })]);
|
||||
const bundled = source === "failureError" || source === "contextError";
|
||||
if (bundled) mineFixture = { ...mineFixture, [source]: { status: 503, message: "Optional source unavailable" } };
|
||||
else apiMocks[source].mockRejectedValue(new Error("Optional source unavailable"));
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
await act(() => root.render(<QueryClientProvider client={queryClient}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Available task"));
|
||||
expect(document.body.textContent).toContain("Some inbox items couldn’t load.");
|
||||
let resolveRetry: (rows: []) => void = () => undefined;
|
||||
apiMocks[source].mockImplementation(() => new Promise((resolve) => { resolveRetry = resolve; }));
|
||||
await act(() => Array.from(document.body.querySelectorAll('button')).find((button) => button.textContent === "Retry missing items")!.click());
|
||||
await vi.waitFor(() => expect(apiMocks[source]).toHaveBeenCalledTimes(2));
|
||||
expect(container.textContent).toContain("Available task");
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).toBeNull();
|
||||
await act(() => resolveRetry([]));
|
||||
await vi.waitFor(() => expect(document.body.textContent).not.toContain("Some inbox items couldn’t load."));
|
||||
act(() => root.unmount());
|
||||
try {
|
||||
await act(() => root.render(<QueryClientProvider client={queryClient}><Inbox /></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Available task"));
|
||||
expect(document.body.textContent).toContain("Some inbox items couldn’t load.");
|
||||
const row = container.querySelector("[data-inbox-item]");
|
||||
const retry = createDeferred<InboxMineSnapshot | []>();
|
||||
if (bundled) apiMocks.inboxMine.mockReturnValue(retry.promise);
|
||||
else apiMocks[source].mockReturnValue(retry.promise);
|
||||
await act(() => Array.from(document.body.querySelectorAll("button")).find(button => button.textContent === "Retry missing items")!.click());
|
||||
await vi.waitFor(() => expect(bundled ? apiMocks.inboxMine : apiMocks[source]).toHaveBeenCalledTimes(2));
|
||||
expect(container.querySelector("[data-inbox-item]")).toBe(row);
|
||||
expect(container.querySelector('[aria-label="Loading tasks"]')).toBeNull();
|
||||
await act(() => retry.resolve(bundled ? createMineSnapshot({ issues: mineFixture.issues }) : []));
|
||||
await vi.waitFor(() => expect(document.body.textContent).not.toContain("Some inbox items couldn’t load."));
|
||||
if (bundled) expect(apiMocks.heartbeatRunsList).not.toHaveBeenCalled();
|
||||
} finally { await act(() => root.unmount()); queryClient.clear(); }
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1233,7 +1532,7 @@ describe("Inbox toolbar", () => {
|
||||
viewState: { issueFilters: { externalObjectStatuses: ["failed"] } },
|
||||
}));
|
||||
apiMocks.experimentalSettings.mockResolvedValue({ enableStreamlinedUi: true, enableExternalObjects: true });
|
||||
apiMocks.issuesList.mockResolvedValue([createIssue()]);
|
||||
setIssueRows([createIssue()]);
|
||||
externalObjectMocks.error = new Error("External statuses unavailable");
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
const root = createRoot(container);
|
||||
@@ -1245,8 +1544,8 @@ describe("Inbox toolbar", () => {
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("requests live descendant summaries for issue rows", async () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
it("requests live descendant summaries for Recent issue rows", async () => {
|
||||
routerMock.location.pathname = "/inbox/recent";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: 0 } },
|
||||
@@ -1263,7 +1562,7 @@ describe("Inbox toolbar", () => {
|
||||
|
||||
await vi.waitFor(() => expect(apiMocks.issuesList).toHaveBeenCalledTimes(1));
|
||||
expect(apiMocks.issuesList).toHaveBeenCalledWith("company-1", expect.objectContaining({
|
||||
touchedByUserId: "me", inboxArchivedByUserId: "me", projection: "index",
|
||||
touchedByUserId: "me", projection: "index",
|
||||
includeLiveDescendantSummary: true, limit: 100, sortField: "updated", sortDir: "desc",
|
||||
}));
|
||||
|
||||
@@ -1276,7 +1575,7 @@ describe("Inbox toolbar", () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
const issueA = createIssue({ id: "issue-a", identifier: "PAP-1001", title: "First inbox row" });
|
||||
const issueB = createIssue({ id: "issue-b", identifier: "PAP-1002", title: "Second inbox row" });
|
||||
apiMocks.issuesList.mockResolvedValue([issueA, issueB]);
|
||||
setIssueRows([issueA, issueB]);
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: 0 } },
|
||||
@@ -1339,7 +1638,7 @@ describe("Inbox toolbar", () => {
|
||||
title: "Read inbox row",
|
||||
isUnreadForMe: false,
|
||||
});
|
||||
apiMocks.issuesList.mockResolvedValue([unread, read]);
|
||||
setIssueRows([unread, read]);
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: 0 } },
|
||||
@@ -1398,7 +1697,7 @@ describe("Inbox toolbar", () => {
|
||||
const issueA = createIssue({ id: "issue-a", identifier: "PAP-2001", title: "Sync row A" });
|
||||
const issueB = createIssue({ id: "issue-b", identifier: "PAP-2002", title: "Sync row B" });
|
||||
const issueC = createIssue({ id: "issue-c", identifier: "PAP-2003", title: "Sync row C" });
|
||||
apiMocks.issuesList.mockResolvedValue([issueA, issueB, issueC]);
|
||||
setIssueRows([issueA, issueB, issueC]);
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: 0 } },
|
||||
@@ -1437,7 +1736,7 @@ describe("Inbox toolbar", () => {
|
||||
// A poll reshapes the list (row B's title changes → new nav array) before
|
||||
// the keypress. This is what used to null the hovered index and strand
|
||||
// j/k back at the top.
|
||||
apiMocks.issuesList.mockResolvedValue([issueA, { ...issueB, title: "Sync row B (updated)" }, issueC]);
|
||||
setIssueRows([issueA, { ...issueB, title: "Sync row B (updated)" }, issueC]);
|
||||
await act(async () => {
|
||||
await queryClient.invalidateQueries();
|
||||
});
|
||||
@@ -1479,7 +1778,7 @@ describe("Inbox toolbar", () => {
|
||||
title: "Pin row C",
|
||||
lastActivityAt: new Date(base + 1000),
|
||||
});
|
||||
apiMocks.issuesList.mockResolvedValue([issueA, issueB, issueC]);
|
||||
setIssueRows([issueA, issueB, issueC]);
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: 0 } },
|
||||
@@ -1517,7 +1816,7 @@ describe("Inbox toolbar", () => {
|
||||
expect(orderOf()).toEqual(["A", "B", "C"]);
|
||||
|
||||
// A poll makes row C the most-recently-active: the fresh sort is now [C, A, B].
|
||||
apiMocks.issuesList.mockResolvedValue([
|
||||
setIssueRows([
|
||||
{ ...issueA },
|
||||
{ ...issueB },
|
||||
{ ...issueC, lastActivityAt: new Date(base + 9000) },
|
||||
@@ -1563,7 +1862,7 @@ describe("Inbox toolbar", () => {
|
||||
routerMock.location.pathname = "/inbox/mine";
|
||||
const issueA = createIssue({ id: "issue-a", identifier: "PAP-1001", title: "First inbox row" });
|
||||
const issueB = createIssue({ id: "issue-b", identifier: "PAP-1002", title: "Second inbox row" });
|
||||
apiMocks.issuesList.mockResolvedValue([issueA, issueB]);
|
||||
setIssueRows([issueA, issueB]);
|
||||
const archiveA = createDeferred<{ id: string; archivedAt: Date }>();
|
||||
apiMocks.archiveFromInbox.mockImplementation((id: string) =>
|
||||
id === "issue-a" ? archiveA.promise : Promise.resolve({ id, archivedAt: new Date() }),
|
||||
@@ -1631,7 +1930,7 @@ describe("Inbox toolbar", () => {
|
||||
identifier: "PAP-1001",
|
||||
title: "Archived inbox row",
|
||||
});
|
||||
apiMocks.issuesList.mockResolvedValue([archivedIssue]);
|
||||
setIssueRows([archivedIssue]);
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: 0 } },
|
||||
@@ -1681,7 +1980,7 @@ describe("Inbox toolbar", () => {
|
||||
identifier: "PAP-1001",
|
||||
title: "Undoable inbox row",
|
||||
});
|
||||
apiMocks.issuesList.mockResolvedValue([archivedIssue]);
|
||||
setIssueRows([archivedIssue]);
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: 0 } },
|
||||
@@ -1974,13 +2273,11 @@ describe("Coordinator Inbox collection reads", () => {
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><CoordinatorPresentation.Provider value={true}><Inbox /></CoordinatorPresentation.Provider></QueryClientProvider>));
|
||||
await vi.waitFor(() => expect(apiMocks.heartbeatRunsList).toHaveBeenCalled());
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 30)); });
|
||||
const sources = apiMocks.issuesList.mock.calls.filter(call => call[1]?.projection !== "rows").map(call => call[1]);
|
||||
expect(sources).toHaveLength(1);
|
||||
expect(sources.every(source => source.projection === "index")).toBe(true);
|
||||
expect(apiMocks.dashboardSummary).toHaveBeenCalledTimes(0);
|
||||
expect(apiMocks.heartbeatRunsList.mock.calls[0]?.[3]?.latestFailuresOnly === true).toBe(true);
|
||||
await vi.waitFor(() => expect(apiMocks.inboxMine).toHaveBeenCalledOnce());
|
||||
await vi.waitFor(() => expect(client.isFetching()).toBe(0));
|
||||
expect(apiMocks.issuesList).not.toHaveBeenCalled();
|
||||
expect(apiMocks.heartbeatRunsList).not.toHaveBeenCalled();
|
||||
expect(apiMocks.dashboardSummary).not.toHaveBeenCalled();
|
||||
} finally { await act(async () => root.unmount()); client.clear(); container.remove(); }
|
||||
});
|
||||
});
|
||||
+72
-40
@@ -129,7 +129,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { PageTabBar } from "../components/PageTabBar";
|
||||
import type { Approval, HeartbeatRun, Issue, JoinRequest } from "@paperclipai/shared";
|
||||
import type { Approval, HeartbeatRun, InboxMineSnapshot, Issue, JoinRequest } from "@paperclipai/shared";
|
||||
import {
|
||||
ACTIONABLE_APPROVAL_STATUSES,
|
||||
DEFAULT_INBOX_ISSUE_COLUMNS,
|
||||
@@ -900,6 +900,10 @@ function StreamlinedInbox({
|
||||
queryKey: queryKeys.auth.session,
|
||||
queryFn: () => authApi.getSession(),
|
||||
});
|
||||
const currentUserId = session?.user.id ?? session?.session.userId ?? null;
|
||||
const mineContextQueryKey = [...queryKeys.issues.list(selectedCompanyId!), "mine-context", currentUserId] as const;
|
||||
const { data: mineSnapshot } = useQuery<InboxMineSnapshot>({ queryKey: mineContextQueryKey, enabled: false });
|
||||
|
||||
|
||||
const { data: agents, isLoading: isAgentsLoading } = useQuery({
|
||||
queryKey: queryKeys.agents.list(selectedCompanyId!),
|
||||
@@ -999,31 +1003,26 @@ function StreamlinedInbox({
|
||||
error: mineIssuesError,
|
||||
dataUpdatedAt: mineIssuesUpdatedAt,
|
||||
} = useQuery({
|
||||
queryKey: [...queryKeys.issues.listMineByMe(selectedCompanyId!), "index", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT] as const,
|
||||
queryFn: () =>
|
||||
issuesApi.listCompact(selectedCompanyId!, {
|
||||
touchedByUserId: "me",
|
||||
inboxArchivedByUserId: "me",
|
||||
status: INBOX_MINE_ISSUE_STATUS_FILTER,
|
||||
projection: "index",
|
||||
sortField: "updated",
|
||||
sortDir: "desc",
|
||||
includeRoutineExecutions: true,
|
||||
includeLiveDescendantSummary: true,
|
||||
limit: INBOX_ISSUE_LIST_LIMIT,
|
||||
}).then((rows) => rows as Issue[]),
|
||||
enabled: !!selectedCompanyId && tab === "mine",
|
||||
queryKey: [...queryKeys.issues.listMineByMe(selectedCompanyId!), "index", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT, currentUserId] as const,
|
||||
queryFn: async ({ signal }) => {
|
||||
const snapshot = await issuesApi.inboxMine(selectedCompanyId!, { signal });
|
||||
if (snapshot.userId !== currentUserId) {
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.auth.session });
|
||||
throw new ApiError("Your account changed. Refresh the inbox.", 409, { error: "account_changed" });
|
||||
}
|
||||
queryClient.setQueryData(mineContextQueryKey, snapshot);
|
||||
return snapshot.issues as Issue[];
|
||||
},
|
||||
enabled: !!selectedCompanyId && !!currentUserId && tab === "mine",
|
||||
refetchOnMount: mineSnapshot ? undefined : "always",
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: INBOX_HOT_PATH_STALE_MS,
|
||||
staleTime: mineSnapshot ? INBOX_HOT_PATH_STALE_MS : 0,
|
||||
});
|
||||
const mineIssuesQueryKey = [...queryKeys.issues.listMineByMe(selectedCompanyId!), "index", "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 && tab === "mine",
|
||||
});
|
||||
usePublishSharedQueryData(sharedMineIssues, mineIssuesRaw, mineIssuesUpdatedAt);
|
||||
const mineIssuesQueryKey = [...queryKeys.issues.listMineByMe(selectedCompanyId!), "index", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT, currentUserId] as const;
|
||||
// Mine owns one coherent response: broadcasting only its task array would
|
||||
// refresh that array while another tab retained stale parent/failure context.
|
||||
// Each tab uses the authenticated aggregate read; the server coalesces it.
|
||||
|
||||
const {
|
||||
data: touchedIssuesRaw = [],
|
||||
isLoading: isTouchedIssuesLoading,
|
||||
@@ -1055,42 +1054,53 @@ function StreamlinedInbox({
|
||||
});
|
||||
usePublishSharedQueryData(sharedTouchedIssues, touchedIssuesRaw, touchedIssuesUpdatedAt);
|
||||
|
||||
const { data: heartbeatRuns, isLoading: isRunsLoading, error: runsError } = useQuery({
|
||||
const { data: otherHeartbeatRuns, isLoading: isOtherRunsLoading, error: otherRunsError } = useQuery({
|
||||
queryKey: [...queryKeys.heartbeats(selectedCompanyId!), "inbox-failures", INBOX_HEARTBEAT_RUN_LIMIT],
|
||||
queryFn: () => heartbeatsApi.list(selectedCompanyId!, undefined, INBOX_HEARTBEAT_RUN_LIMIT, { summary: true, latestFailuresOnly: true }),
|
||||
enabled: !!selectedCompanyId,
|
||||
enabled: !!selectedCompanyId && tab !== "mine",
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: INBOX_HOT_PATH_STALE_MS,
|
||||
});
|
||||
const heartbeatRuns = tab === "mine" ? mineSnapshot?.failureRuns : otherHeartbeatRuns;
|
||||
const isRunsLoading = tab === "mine" ? !!currentUserId && !mineSnapshot && !mineIssuesError : isOtherRunsLoading;
|
||||
const runsError = tab === "mine" && mineSnapshot?.failureError
|
||||
? new ApiError(mineSnapshot.failureError.message, mineSnapshot.failureError.status, null) : tab === "mine" ? null : otherRunsError;
|
||||
const bundledContextIds = useMemo(() => new Set(tab === "mine" && mineSnapshot ? [
|
||||
...mineSnapshot.issues.map((issue) => issue.parentId).filter((id): id is string => Boolean(id)),
|
||||
...mineSnapshot.failureRuns.map(readIssueIdFromRun).filter((id): id is string => Boolean(id)),
|
||||
] : []), [tab, mineSnapshot]);
|
||||
const { parentContextIds, failureContextIds, contextIssueIds } = useMemo(() => {
|
||||
const sourceIssues = tab === "mine" ? mineIssuesRaw : touchedIssuesRaw;
|
||||
const loadedIds = new Set(sourceIssues.map((issue) => issue.id));
|
||||
// Failure cards need interruption state even when their task is already in
|
||||
// the index. Parent captions only need index metadata.
|
||||
const failureIds = new Set((heartbeatRuns ?? []).map(readIssueIdFromRun)
|
||||
.filter((id): id is string => Boolean(id)));
|
||||
.filter((id): id is string => Boolean(id))
|
||||
.filter((id) => !bundledContextIds.has(id)));
|
||||
const parentIds = new Set(sourceIssues.map((issue) => issue.parentId)
|
||||
.filter((id): id is string => Boolean(id))
|
||||
.filter((id) => !loadedIds.has(id) && !failureIds.has(id)));
|
||||
.filter((id) => !loadedIds.has(id) && !failureIds.has(id) && !bundledContextIds.has(id)));
|
||||
return {
|
||||
parentContextIds: [...parentIds].sort(),
|
||||
failureContextIds: [...failureIds].sort(),
|
||||
contextIssueIds: new Set([...parentIds, ...failureIds]),
|
||||
};
|
||||
}, [tab, mineIssuesRaw, touchedIssuesRaw, heartbeatRuns]);
|
||||
const needsIssueContext = !!selectedCompanyId && contextIssueIds.size > 0 && tab !== "blocked";
|
||||
}, [tab, mineIssuesRaw, touchedIssuesRaw, heartbeatRuns, bundledContextIds]);
|
||||
const needsIssueContext = !!selectedCompanyId && contextIssueIds.size > 0 && tab !== "blocked"
|
||||
&& (tab !== "mine" || !!mineSnapshot || !!mineIssuesError);
|
||||
const {
|
||||
data: issueContext,
|
||||
isLoading: isContextIssuesLoading,
|
||||
isPlaceholderData: isContextIssuesPlaceholder,
|
||||
error: contextIssuesError,
|
||||
error: extraContextIssuesError,
|
||||
} = useQuery<{
|
||||
companyId: string | null;
|
||||
userId: string | null;
|
||||
issues: Issue[];
|
||||
failureIssueIds: string[];
|
||||
}>({
|
||||
queryKey: [...queryKeys.issues.list(selectedCompanyId!), "row-context", "parent-index-with-failure-state", parentContextIds, failureContextIds],
|
||||
placeholderData: (previous) => needsIssueContext && previous?.companyId === selectedCompanyId
|
||||
queryKey: [...queryKeys.issues.list(selectedCompanyId!), "row-context", "parent-index-with-failure-state", parentContextIds, failureContextIds, currentUserId],
|
||||
placeholderData: (previous) => needsIssueContext && previous?.companyId === selectedCompanyId && previous.userId === currentUserId
|
||||
? { ...previous, issues: previous.issues.filter((issue) => contextIssueIds.has(issue.id)) }
|
||||
: undefined,
|
||||
queryFn: async ({ signal }) => {
|
||||
@@ -1110,12 +1120,25 @@ function StreamlinedInbox({
|
||||
]);
|
||||
// A completed failure read also establishes absence for filtered/missing
|
||||
// tasks. Parent-only placeholders cannot supply this coverage.
|
||||
return { companyId: selectedCompanyId, issues: [...parents, ...failures], failureIssueIds: failureContextIds };
|
||||
return { companyId: selectedCompanyId, userId: currentUserId, issues: [...parents, ...failures], failureIssueIds: failureContextIds };
|
||||
},
|
||||
enabled: needsIssueContext,
|
||||
});
|
||||
const contextIssues = issueContext?.issues ?? [];
|
||||
const knownFailureContextIds = useMemo(() => new Set(issueContext?.failureIssueIds ?? []), [issueContext]);
|
||||
const contextIssuesError = extraContextIssuesError ?? (tab === "mine" && mineSnapshot?.contextError
|
||||
? new ApiError(mineSnapshot.contextError.message, mineSnapshot.contextError.status, null) : null);
|
||||
const contextIssues = useMemo(() => {
|
||||
if (tab !== "mine" || !mineSnapshot) return issueContext?.issues ?? [];
|
||||
const sourceIds = new Set(mineIssuesRaw.map((issue) => issue.id));
|
||||
const parentIds = new Set(mineIssuesRaw.map((issue) => issue.parentId));
|
||||
return [
|
||||
...mineSnapshot.issues.filter((issue) => !sourceIds.has(issue.id) && parentIds.has(issue.id)),
|
||||
...mineSnapshot.contextIssues.filter((issue) => parentIds.has(issue.id) || mineSnapshot.failureIssueIds.includes(issue.id)),
|
||||
...(issueContext?.issues ?? []),
|
||||
] as Issue[];
|
||||
}, [tab, mineSnapshot, mineIssuesRaw, issueContext]);
|
||||
const knownFailureContextIds = useMemo(() => new Set([
|
||||
...(tab === "mine" ? mineSnapshot?.failureIssueIds ?? [] : []), ...(issueContext?.failureIssueIds ?? []),
|
||||
]), [tab, mineSnapshot, issueContext]);
|
||||
const issues = useMemo(() => [...mineIssuesRaw, ...touchedIssuesRaw, ...contextIssues], [mineIssuesRaw, touchedIssuesRaw, contextIssues]);
|
||||
const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);
|
||||
const sharedLiveRuns = useSharedPollingQuery({
|
||||
@@ -1139,7 +1162,6 @@ function StreamlinedInbox({
|
||||
queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
|
||||
enabled: !!selectedCompanyId,
|
||||
});
|
||||
const currentUserId = session?.user.id ?? session?.session.userId ?? null;
|
||||
const [archivingIssueIds, setArchivingIssueIds] = useState<Set<string>>(new Set());
|
||||
const [undoableArchiveIssueIds, setUndoableArchiveIssueIds] = useState<string[]>([]);
|
||||
const [unarchivingIssueIds, setUnarchivingIssueIds] = useState<Set<string>>(new Set());
|
||||
@@ -1939,6 +1961,7 @@ function StreamlinedInbox({
|
||||
},
|
||||
onSuccess: ({ newRun, originalRun }) => {
|
||||
retryRequestKeys.current.delete(originalRun.id);
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe(originalRun.companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(originalRun.companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(originalRun.companyId, originalRun.agentId) });
|
||||
if (newRun.runId)
|
||||
@@ -2507,16 +2530,25 @@ function StreamlinedInbox({
|
||||
!isRunsLoading
|
||||
&& (!issueFilters.liveOnly || !isLiveRunsLoading)
|
||||
&& (issueFilters.externalObjectStatuses.length === 0 || externalObjectSummariesReady || !!externalObjectSummariesError);
|
||||
const listError = sourceSearchError ?? (tab === "mine" ? mineIssuesError : touchedIssuesError)
|
||||
const sourceError = tab === "mine" ? mineIssuesError : touchedIssuesError;
|
||||
const sourceUpdatedAt = tab === "mine" ? mineIssuesUpdatedAt : touchedIssuesUpdatedAt;
|
||||
const canRetainSourceRows = sourceUpdatedAt > 0 && !(sourceError instanceof ApiError
|
||||
&& (sourceError.status < 500 && sourceError.status !== 429));
|
||||
const listError = sourceSearchError ?? (canRetainSourceRows ? null : sourceError)
|
||||
?? (issueFilters.externalObjectStatuses.length > 0 ? externalObjectSummariesError : null);
|
||||
const optionalSourceError = dismissalsError ?? approvalsError ?? joinRequestsError ?? runsError ?? contextIssuesError;
|
||||
const optionalSourceError = dismissalsError ?? approvalsError ?? joinRequestsError ?? runsError ?? contextIssuesError
|
||||
?? (tab === "mine" ? mineIssuesError : touchedIssuesError);
|
||||
const retryFailedSources = () => {
|
||||
// Optional failures belong to the aggregate read, whose task rows stay usable.
|
||||
if (tab === "mine" && (mineSnapshot?.failureError || mineSnapshot?.contextError)) {
|
||||
void queryClient.refetchQueries({ queryKey: mineIssuesQueryKey, exact: true });
|
||||
}
|
||||
// Retry only failed reads for this company; settled rows stay visible.
|
||||
void queryClient.refetchQueries({ predicate: (query) => query.state.status === "error"
|
||||
&& query.queryKey.includes(selectedCompanyId), type: "active" });
|
||||
};
|
||||
|
||||
const revealScope = JSON.stringify([selectedCompanyId, tab, normalizedSearchQuery, issueFilters]);
|
||||
const revealScope = JSON.stringify([currentUserId, selectedCompanyId, tab, normalizedSearchQuery, issueFilters]);
|
||||
const [revealedScope, setRevealedScope] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (initialSourcesSettled && !listError) setRevealedScope(revealScope);
|
||||
|
||||
Reference in new issue
Block a user