mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-21 10:52:06 +01:00
Synchronize resolved chat questions across inbox surfaces
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
da00e353f4
commit
025e14f940
10 files changed
+124
-13
No files matched your search
@@ -4,6 +4,32 @@ import { idle, json, send, setup } from "./agent-chat.shared";
|
||||
test.use({ trace: "retain-on-failure" });
|
||||
test.setTimeout(120_000);
|
||||
|
||||
test("answering questions in chat and inbox updates both open surfaces", async ({ page, request, context }) => {
|
||||
const f = await setup(request);
|
||||
const inbox = await context.newPage();
|
||||
try {
|
||||
await page.goto(f.route);
|
||||
for (const answerIn of ["chat", "inbox"] as const) {
|
||||
await send(page, { action: "question" });
|
||||
await expect(page.getByRole("radio", { name: "Garden club", exact: true }).last()).toBeVisible({ timeout: 45_000 });
|
||||
if (answerIn === "chat") await inbox.goto(`/${f.company.issuePrefix}/decisions`);
|
||||
const inboxQuestion = inbox.getByRole("radio", { name: "Garden club", exact: true });
|
||||
await expect(inboxQuestion).toBeVisible({ timeout: 20_000 });
|
||||
const answeringPage = answerIn === "chat" ? page : inbox;
|
||||
await answeringPage.getByRole("radio", { name: "Garden club", exact: true }).last().click();
|
||||
await answeringPage.getByRole("button", { name: "Submit answers", exact: true }).last().click();
|
||||
await expect(inboxQuestion).toHaveCount(0, { timeout: 20_000 });
|
||||
await expect(page.getByRole("radio", { name: "Garden club", exact: true })).toHaveCount(0, { timeout: 20_000 });
|
||||
const chat = await json(await request.get(f.chatPath));
|
||||
await expect.poll(async () => {
|
||||
const feed = await json(await request.get(`/api/companies/${f.company.id}/attention?all=true&view=mine`));
|
||||
return feed.items.filter((item: any) => item.sourceKind === "issue_thread_interaction" && item.relatedIssue?.id === chat.id).length;
|
||||
}).toBe(0);
|
||||
await idle(request, f.chatPath, answerIn === "chat" ? 2 : 4);
|
||||
}
|
||||
} finally { await inbox.close(); await f.restore(); }
|
||||
});
|
||||
|
||||
test("a routine delivers a first digest, unread state, source link and replyable history", async ({ page, request }) => {
|
||||
const f = await setup(request);
|
||||
try {
|
||||
|
||||
@@ -26,6 +26,7 @@ describe("attentionApi.list", () => {
|
||||
|
||||
expect(mockApi.get).toHaveBeenCalledWith(
|
||||
"/companies/company-1/attention?includeDismissed=true&archived=true&activitySince=2026-08-01T00%3A00%3A00.000Z&activityUntil=2026-08-01T23%3A59%3A59.999Z&queue=release+review&sort=decide&cursor=next%2Fpage&limit=25",
|
||||
{ fresh: true, cache: "no-store" },
|
||||
);
|
||||
});
|
||||
|
||||
@@ -34,13 +35,14 @@ describe("attentionApi.list", () => {
|
||||
|
||||
expect(mockApi.get).toHaveBeenCalledWith(
|
||||
"/companies/company-1/attention?all=true&queue=release+review",
|
||||
{ fresh: true, cache: "no-store" },
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the query delimiter when no options are supplied", async () => {
|
||||
await attentionApi.list("company-1");
|
||||
|
||||
expect(mockApi.get).toHaveBeenCalledWith("/companies/company-1/attention");
|
||||
expect(mockApi.get).toHaveBeenCalledWith("/companies/company-1/attention", { fresh: true, cache: "no-store" });
|
||||
});
|
||||
|
||||
it("requests the complete task membership without decision card bodies", async () => {
|
||||
|
||||
@@ -44,7 +44,8 @@ export const attentionApi = {
|
||||
if (options.cursor) params.set("cursor", options.cursor);
|
||||
if (options.limit !== undefined) params.set("limit", String(options.limit));
|
||||
const query = params.toString();
|
||||
return api.get<AttentionFeed>(`/companies/${companyId}/attention${query ? `?${query}` : ""}`);
|
||||
// A post-answer refresh must not join a GET begun before the answer.
|
||||
return api.get<AttentionFeed>(`/companies/${companyId}/attention${query ? `?${query}` : ""}`, { fresh: true, cache: "no-store" });
|
||||
},
|
||||
/** Claim an Unassigned card: you become its addressee (PAP-749 plan §1, Rule 3). */
|
||||
claim: (companyId: string, sourceKind: AttentionSourceKind, sourceId: string) =>
|
||||
|
||||
@@ -614,7 +614,7 @@ export const issuesApi = {
|
||||
data,
|
||||
),
|
||||
listInteractions: (id: string) =>
|
||||
api.get<IssueThreadInteraction[]>(`/issues/${id}/interactions`),
|
||||
api.get<IssueThreadInteraction[]>(`/issues/${id}/interactions`, { fresh: true, cache: "no-store" }),
|
||||
listAcceptedPlanDecompositions: (id: string) =>
|
||||
api.get<AcceptedPlanDecompositionSummary[]>(
|
||||
`/issues/${id}/accepted-plan-decompositions`,
|
||||
|
||||
@@ -94,6 +94,8 @@ export function AttentionInteractionResolver({
|
||||
}, [interactions, interactionId]);
|
||||
|
||||
const invalidate = (resolvedInteraction?: IssueThreadInteraction) => {
|
||||
// Cancel old reads before publishing the write's canonical response.
|
||||
invalidateInteractionRecordViews(queryClient, companyId, resolvedInteraction);
|
||||
// The accept route returns the fully stitched interaction (including
|
||||
// secretProposal.executed/failed). Put that receipt in the cache before
|
||||
// invalidating so the attention surface never flashes a generic Accepted
|
||||
@@ -104,8 +106,6 @@ export function AttentionInteractionResolver({
|
||||
(current) => replaceResolvedInteraction(current, resolvedInteraction),
|
||||
);
|
||||
}
|
||||
// Task detail keys the same list by identifier, so refresh every view (UX2).
|
||||
invalidateInteractionRecordViews(queryClient, companyId);
|
||||
onResolved?.(resolvedInteraction);
|
||||
};
|
||||
|
||||
|
||||
@@ -33,12 +33,17 @@ describe("LiveUpdatesProvider issue invalidation", () => {
|
||||
it.each(["issue.thread_interaction_accepted", "issue.thread_interaction_answered", "decision.decided", "decision.effect_succeeded", "decision.effect_failed", "issue.conversation_session_started", "inbox.dismissed", "inbox.snoozed", "inbox.restored"])("refreshes canonical attention, history and source-chat projections after %s", action => {
|
||||
const client = new QueryClient();
|
||||
const invalidate = vi.spyOn(client, "invalidateQueries");
|
||||
const cancel = vi.spyOn(client, "cancelQueries");
|
||||
__liveUpdatesTestUtils.invalidateActivityQueries(client, "company-1", {
|
||||
entityType: action.startsWith("decision.") ? "decision" : "issue", entityId: "task-1", action,
|
||||
}, { userId: "user-1", agentId: null });
|
||||
for (const queryKey of [queryKeys.attention("company-1"), ["decisions", "company-1"], ["issues", "decision-receipts"], ["issues", "chat-handoffs"], ["issues", "pending-questions"]]) {
|
||||
expect(invalidate).toHaveBeenCalledWith({ queryKey });
|
||||
}
|
||||
if (action.startsWith("issue.thread_interaction_")) {
|
||||
expect(cancel).toHaveBeenCalledWith({ queryKey: queryKeys.attention("company-1") });
|
||||
expect(cancel).toHaveBeenCalledWith({ queryKey: ["issues", "interactions"] });
|
||||
}
|
||||
client.clear();
|
||||
});
|
||||
it("refreshes cached tasks whose relation summaries embed a changed blocker", () => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createLiveQueryRecovery } from "../lib/live-query-recovery";
|
||||
import { isLiveReconciledQuery } from "../lib/live-reconcile";
|
||||
import { refreshPendingTaskBrowserReads, refreshTaskBrowsers } from "../lib/task-browsers-refresh";
|
||||
import { refreshRecentSubtasks, refreshRecentTaskSummaries } from "../lib/recent-subtasks-refresh";
|
||||
import { invalidateInteractionRecordViews } from "../lib/attention-record-views";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
@@ -1642,6 +1643,9 @@ function invalidateActivityQueries(
|
||||
void queryClient.resetQueries({ queryKey });
|
||||
}
|
||||
} else if (decisionProjectionChanged) {
|
||||
if (action?.startsWith("issue.thread_interaction_")) {
|
||||
invalidateInteractionRecordViews(queryClient, companyId);
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.attention(companyId) });
|
||||
queryClient.invalidateQueries({ queryKey: ["decisions", companyId] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.decisionQueues.list(companyId) });
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { QueryClient, QueryObserver } from "@tanstack/react-query";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { attentionApi } from "../api/attention";
|
||||
import { detachInflightGets } from "../api/client";
|
||||
import { coordinatorAttentionQueryKey } from "./coordinator-attention";
|
||||
import { invalidateInteractionRecordViews } from "./attention-record-views";
|
||||
import { coordinatorTaskQuestion } from "../fixtures/coordinatorTaskQuestion";
|
||||
import { queryKeys } from "./queryKeys";
|
||||
|
||||
afterEach(() => { detachInflightGets(); vi.unstubAllGlobals(); });
|
||||
|
||||
it("publishes an answer to both task references without changing another question", () => {
|
||||
const client = new QueryClient();
|
||||
const question = coordinatorTaskQuestion;
|
||||
const other = { ...question, id: "another-question" };
|
||||
const uuidKey = queryKeys.issues.interactions(question.issueId);
|
||||
const identifierKey = queryKeys.issues.interactions("BOB-1");
|
||||
const unrelatedKey = queryKeys.issues.interactions("unrelated-task");
|
||||
client.setQueryData(uuidKey, [question, other]);
|
||||
client.setQueryData(identifierKey, [question]);
|
||||
client.setQueryData(unrelatedKey, [other]);
|
||||
const answered = { ...question, status: "answered" as const };
|
||||
invalidateInteractionRecordViews(client, question.companyId, answered);
|
||||
expect(client.getQueryData(uuidKey)).toEqual([answered, other]);
|
||||
expect(client.getQueryData(identifierKey)).toEqual([answered]);
|
||||
expect(client.getQueryData(unrelatedKey)).toEqual([other]);
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it.each(["initial", "background"])("does not restore an answered question from a pre-answer %s inbox read", async mode => {
|
||||
let reads = 0;
|
||||
const oldRead = mode === "initial" ? 1 : 2;
|
||||
let releaseOldRead!: () => void;
|
||||
const question = { id: "question-card", sourceKind: "issue_thread_interaction", subject: { id: "question" } };
|
||||
vi.stubGlobal("fetch", vi.fn(async () => {
|
||||
const read = ++reads;
|
||||
if (read === oldRead) await new Promise<void>(resolve => { releaseOldRead = resolve; });
|
||||
return new Response(JSON.stringify({ items: read <= oldRead ? [question] : [], deskBadgeCount: read <= oldRead ? 1 : 0 }), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}));
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const key = coordinatorAttentionQueryKey("company", "person", "mine");
|
||||
const observer = new QueryObserver(client, { queryKey: key, queryFn: () => attentionApi.list("company", { all: true, view: "mine" }) });
|
||||
const unsubscribe = observer.subscribe(() => {});
|
||||
try {
|
||||
if (mode === "background") {
|
||||
await vi.waitFor(() => expect(observer.getCurrentResult().data?.items).toEqual([question]));
|
||||
void observer.refetch();
|
||||
}
|
||||
await vi.waitFor(() => expect(reads).toBe(oldRead));
|
||||
invalidateInteractionRecordViews(client, "company");
|
||||
await vi.waitFor(() => expect(reads).toBe(oldRead + 1));
|
||||
await vi.waitFor(() => expect(observer.getCurrentResult().data?.items).toEqual([]));
|
||||
releaseOldRead();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
expect(observer.getCurrentResult().data?.items).toEqual([]);
|
||||
expect(observer.getCurrentResult().data?.deskBadgeCount).toBe(0);
|
||||
} finally {
|
||||
releaseOldRead?.(); unsubscribe(); client.clear();
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import type { AttentionItem } from "@paperclipai/shared";
|
||||
import { queryKeys } from "./queryKeys";
|
||||
import type { IssueThreadInteraction } from "./issue-thread-interactions";
|
||||
|
||||
/**
|
||||
* One record, many views (PAP-749 design review, Part 2). A card's source
|
||||
@@ -58,9 +59,20 @@ export function invalidateAttentionRecordViews(queryClient: QueryClient, company
|
||||
* the task's interaction list under both its UUID and its identifier key.
|
||||
* Other people's tabs get the same change from LiveUpdatesProvider.
|
||||
*/
|
||||
export function invalidateInteractionRecordViews(queryClient: QueryClient, companyId: string) {
|
||||
void queryClient.invalidateQueries({ queryKey: ["issues", "interactions"] });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.attention(companyId) });
|
||||
void queryClient.invalidateQueries({ queryKey: ["issues", "pending-questions"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["issues", "decision-receipts"] });
|
||||
export function invalidateInteractionRecordViews(queryClient: QueryClient, companyId: string, interaction?: IssueThreadInteraction) {
|
||||
const keys = [["issues", "interactions"], queryKeys.attention(companyId), ["issues", "pending-questions"], ["issues", "decision-receipts"]];
|
||||
// Initial reads can also predate this write. Cancel before invalidation so
|
||||
// they cannot restore a question that has already been answered.
|
||||
for (const queryKey of keys) {
|
||||
void queryClient.cancelQueries({ queryKey });
|
||||
}
|
||||
if (interaction) {
|
||||
// UUID and identifier routes can both be mounted. Give every cached copy
|
||||
// the same canonical receipt before their authoritative reads complete.
|
||||
queryClient.setQueriesData<IssueThreadInteraction[]>(
|
||||
{ queryKey: ["issues", "interactions"] },
|
||||
current => current?.map(entry => entry.id === interaction.id ? interaction : entry),
|
||||
);
|
||||
}
|
||||
for (const queryKey of keys) void queryClient.invalidateQueries({ queryKey });
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createUuid } from "@/lib/uuid";
|
||||
import { invalidateInteractionRecordViews } from "@/lib/attention-record-views";
|
||||
import { companyProjectsQuery } from "@/lib/company-projects-query";
|
||||
import { NativeControllerContainmentRecovery } from "../components/IssueRecoveryActionCard";
|
||||
import { useIssueIdBatches } from "@/hooks/useIssueIdBatches";
|
||||
@@ -4570,6 +4571,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
);
|
||||
const upsertInteractionInCache = useCallback(
|
||||
(interaction: IssueThreadInteraction) => {
|
||||
invalidateInteractionRecordViews(queryClient, interaction.companyId, interaction);
|
||||
queryClient.setQueryData<IssueThreadInteraction[] | undefined>(
|
||||
queryKeys.issues.interactions(issueId!),
|
||||
(current) => {
|
||||
@@ -4587,9 +4589,6 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
return next;
|
||||
},
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: ["issues", "pending-questions"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["issues", "decision-receipts"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.attention(interaction.companyId) });
|
||||
},
|
||||
[issueId, queryClient],
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user