Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,330 @@
import { notifyManager, QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, renderHook } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

vi.mock('../../../../utils/embed-authed-fetch', async importOriginal => ({
...(await importOriginal<Record<string, unknown>>()),
embedAuthedFetch: vi.fn(),
}));
vi.mock('../../../../contexts/chat-runtime-context', async importOriginal => ({
...(await importOriginal<Record<string, unknown>>()),
useRequiredChatRuntime: () => ({ endpoints: {} }),
}));
vi.mock('../../../chat/hooks/use-chat-identity', () => ({
useChatIdentity: () => ({ authTier: 'session', isLoading: false, user: { email: 'customer@example.com' } }),
}));
import { embedAuthedFetch } from '../../../../utils/embed-authed-fetch';
import { type TicketEngagement, type TicketEngagementFile, useTicketEngagements } from '../use-ticket-engagements';

const signedUrl = 'https://1.cdnp1.hubspotusercontent-na1.net/hubfs/1/screen.png?Expires=1&Signature=s';

function file(id: string, url: string | null): TicketEngagementFile {
return { id, name: `${id}.png`, url, mime: url ? 'image/png' : null, size: null };
}

function message(id: string, ...attachments: TicketEngagementFile[]): TicketEngagement {
return {
id,
body: 'Here is the screenshot',
authorId: null,
authorRole: 'customer',
authorName: null,
authorEmail: 'customer@example.com',
authorAvatarUrl: null,
createdAt: '2026-12-04T12:54:49Z',
attachments,
};
}

const unlinked = [message('m1', file('229452971610', null))];
const linked = [message('m1', file('229452971610', signedUrl))];
// Beside a file that never gets its link, so the re-reads' budget outlives the other file's link.
const besideStuckFile = (url: string | null) => [
message('m0', file('stuck', null)),
message('m1', file('229452971610', url)),
];

const fetchMock = vi.mocked(embedAuthedFetch);
const reply = (engagements: TicketEngagement[]) =>
({ ok: true, json: () => Promise.resolve({ engagements }) }) as unknown as Response;

function respondWith(...reads: TicketEngagement[][]) {
for (const engagements of reads) fetchMock.mockResolvedValueOnce(reply(engagements));
fetchMock.mockResolvedValue(reply(reads[reads.length - 1] ?? []));
}

// Queues a read that answers only when the returned function is called.
function heldRead() {
let answer!: (engagements: TicketEngagement[]) => void;
const response = new Promise<Response>(resolve => {
answer = engagements => resolve(reply(engagements));
});
fetchMock.mockImplementationOnce(() => response);
return answer;
}

function renderEngagements(client = new QueryClient({ defaultOptions: { queries: { retry: false } } })) {
const rendered = renderHook(() => useTicketEngagements('52119670862'), {
wrapper: ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={client}>{children}</QueryClientProvider>
),
});
return { ...rendered, client };
}

// Runs the timers due within `ms`, then lets the reads they started reach the hook.
const advance = (ms: number) =>
act(async () => {
await vi.advanceTimersByTimeAsync(ms);
await vi.advanceTimersByTimeAsync(0);
});

beforeEach(() => {
vi.useFakeTimers();
// react-query hands results to the hook on a `setTimeout(0)`, which fake timers run only once a millisecond has
// passed: a microtask keeps every read's result at the time the read finished.
notifyManager.setScheduler(queueMicrotask);
fetchMock.mockReset();
});

afterEach(() => {
notifyManager.setScheduler(callback => setTimeout(callback, 0));
vi.useRealTimers();
});

describe('useTicketEngagements: a file the server could not link yet', () => {
it('reads the timeline again and shows the link the next read brings', async () => {
respondWith(unlinked, linked);
const { result } = renderEngagements();
await advance(0);
expect(result.current.engagements[0]?.attachments[0]?.url).toBeNull();

await advance(2_000);

expect(fetchMock).toHaveBeenCalledTimes(2);
expect(result.current.engagements[0]?.attachments[0]?.url).toBe(signedUrl);
});

it('stops after three more reads when the link never comes', async () => {
respondWith(unlinked);
renderEngagements();
await advance(0);

await advance(2_000);
await advance(4_000);
await advance(8_000);
expect(fetchMock).toHaveBeenCalledTimes(4);

await advance(60_000);
expect(fetchMock).toHaveBeenCalledTimes(4);
});

it('waits longer before each further read', async () => {
respondWith(unlinked);
renderEngagements();
await advance(0);

await advance(1_999);
expect(fetchMock).toHaveBeenCalledTimes(1);
await advance(1);
expect(fetchMock).toHaveBeenCalledTimes(2);
await advance(3_999);
expect(fetchMock).toHaveBeenCalledTimes(2);
await advance(1);
expect(fetchMock).toHaveBeenCalledTimes(3);
await advance(7_999);
expect(fetchMock).toHaveBeenCalledTimes(3);
await advance(1);
expect(fetchMock).toHaveBeenCalledTimes(4);
});

it('does not read again when every file has its link', async () => {
respondWith([message('m0'), ...linked]);
renderEngagements();
await advance(0);

await advance(60_000);
expect(fetchMock).toHaveBeenCalledTimes(1);
});

it('reads again when one file among several messages has no link', async () => {
respondWith(
[message('m0'), message('m1', file('f1', signedUrl)), message('m2', file('f2', null))],
[message('m0'), message('m1', file('f1', signedUrl)), message('m2', file('f2', signedUrl))],
);
renderEngagements();
await advance(0);

await advance(2_000);
expect(fetchMock).toHaveBeenCalledTimes(2);
await advance(60_000);
expect(fetchMock).toHaveBeenCalledTimes(2);
});

it('reads again when one of a message’s files has no link', async () => {
respondWith([message('m1', file('f1', signedUrl), file('f2', null))]);
renderEngagements();
await advance(0);

await advance(2_000);
expect(fetchMock).toHaveBeenCalledTimes(2);
});

it('stops when the reads after a file without a link keep failing', async () => {
respondWith(unlinked);
fetchMock.mockRejectedValue(new Error('network down'));
const { result } = renderEngagements();
await advance(0);

await advance(2_000);
await advance(4_000);
await advance(8_000);
await advance(60_000);

expect(fetchMock).toHaveBeenCalledTimes(4);
expect(result.current.engagements[0]?.attachments[0]?.url).toBeNull();
});

it('does not read again after a failed read that brought no timeline', async () => {
fetchMock.mockRejectedValue(new Error('network down'));
const { result } = renderEngagements();
await advance(0);
expect(result.current.error).not.toBeNull();

await advance(60_000);
expect(fetchMock).toHaveBeenCalledTimes(1);
});

it('reads again when a later read brings the file without its link once more', async () => {
respondWith(unlinked, linked, unlinked, linked);
const { result } = renderEngagements();
await advance(0);
await advance(2_000);
expect(result.current.engagements[0]?.attachments[0]?.url).toBe(signedUrl);

act(() => result.current.refetch());
await advance(0);
expect(fetchMock).toHaveBeenCalledTimes(3);
expect(result.current.engagements[0]?.attachments[0]?.url).toBeNull();

await advance(2_000);
expect(fetchMock).toHaveBeenCalledTimes(4);
expect(result.current.engagements[0]?.attachments[0]?.url).toBe(signedUrl);
});

it('starts over for a new file without a link after the re-reads ran out', async () => {
respondWith(unlinked, unlinked, unlinked, unlinked, [...unlinked, message('m2', file('f2', null))]);
const { result } = renderEngagements();
await advance(0);
await advance(2_000);
await advance(4_000);
await advance(8_000);
expect(fetchMock).toHaveBeenCalledTimes(4);

act(() => result.current.refetch());
await advance(0);
expect(fetchMock).toHaveBeenCalledTimes(5);

await advance(2_000);
expect(fetchMock).toHaveBeenCalledTimes(6);
});

it('does not start over when a later read brings the same file without a link', async () => {
respondWith(unlinked);
const { result } = renderEngagements();
await advance(0);
await advance(2_000);
await advance(4_000);
await advance(8_000);

act(() => result.current.refetch());
await advance(0);
expect(fetchMock).toHaveBeenCalledTimes(5);

await advance(60_000);
expect(fetchMock).toHaveBeenCalledTimes(5);
});

it('starts over for a file that lost its link again after the re-reads ran out', async () => {
respondWith(
besideStuckFile(null),
besideStuckFile(signedUrl),
besideStuckFile(signedUrl),
besideStuckFile(signedUrl),
besideStuckFile(null),
);
const { result } = renderEngagements();
await advance(0);
await advance(2_000);
await advance(4_000);
await advance(8_000);
expect(fetchMock).toHaveBeenCalledTimes(4);

act(() => result.current.refetch());
await advance(0);
expect(fetchMock).toHaveBeenCalledTimes(5);

await advance(2_000);
expect(fetchMock).toHaveBeenCalledTimes(6);
});

it('does not start over for a file that lost its link again during the re-reads', async () => {
respondWith(besideStuckFile(null), besideStuckFile(signedUrl), besideStuckFile(signedUrl), besideStuckFile(null));
renderEngagements();
await advance(0);
await advance(2_000);
await advance(4_000);
await advance(8_000);
expect(fetchMock).toHaveBeenCalledTimes(4);

await advance(60_000);
expect(fetchMock).toHaveBeenCalledTimes(4);
});

it('counts only the reads the timeline keeps, not one a newer read replaced', async () => {
fetchMock.mockResolvedValueOnce(reply(unlinked));
const replaced = heldRead();
const newer = heldRead();
fetchMock.mockResolvedValue(reply(linked));
const { result, client } = renderEngagements();
await advance(0);
await advance(2_000);
expect(fetchMock).toHaveBeenCalledTimes(2);

// A stream event invalidates the ticket while the re-read is on its way: a newer read replaces it.
act(() => {
void client.invalidateQueries({ queryKey: ['ticket-engagements'] });
});
expect(fetchMock).toHaveBeenCalledTimes(3);
act(() => {
replaced(linked);
newer(unlinked);
});
await advance(0);
expect(result.current.engagements[0]?.attachments[0]?.url).toBeNull();

await advance(4_000);
expect(fetchMock).toHaveBeenCalledTimes(4);
expect(result.current.engagements[0]?.attachments[0]?.url).toBe(signedUrl);
});

it('keeps reading again for a drawer reopened while the first read was on its way', async () => {
const first = heldRead();
fetchMock.mockResolvedValue(reply(linked));
const closed = renderEngagements();
await advance(0);
closed.unmount();

const { result } = renderEngagements(closed.client);
await advance(0);
expect(fetchMock).toHaveBeenCalledTimes(1);
act(() => first(unlinked));
await advance(0);
expect(result.current.engagements[0]?.attachments[0]?.url).toBeNull();

await advance(2_000);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(result.current.engagements[0]?.attachments[0]?.url).toBe(signedUrl);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,56 @@
* guessing ticket ids.
*/

import { useQuery } from '@tanstack/react-query';
import { type Query, useQuery } from '@tanstack/react-query';
import { useRequiredChatRuntime } from '../../../contexts/chat-runtime-context';
import { embedAuthedFetch } from '../../../utils/embed-authed-fetch';
import { useChatIdentity } from '../../chat/hooks/use-chat-identity';

const LIST_ENGAGEMENTS_ENDPOINT = '/api/chat/agent/list-engagements';
// The hub signs a ticket's files on each read, under a short budget, and keeps no link it failed to sign. A file it
// could not sign in time comes without a link, and the drawer can neither show nor download it. Nothing else reads the
// timeline again while the drawer is open, so such a read is followed by a few more, each after a longer wait. A file
// that never gets a link costs those three reads each time the drawer opens.
const RELINK_DELAYS_MS = [2_000, 4_000, 8_000];

// Kept on the query, not the component: every drawer showing the ticket shares it, and only results the query keeps
// move it, never a read that a newer one replaced.
interface RelinkBudget {
/** Each file seen without a link, and whether a read brought its link since. */
files: Map<string, boolean>;
/** The query's result count when the re-reads last started. */
since: number;
}
const relinkBudgets = new WeakMap<object, RelinkBudget>();

function unlinkedFiles(engagements: readonly TicketEngagement[] | undefined): Set<string> {
return new Set(
(engagements ?? []).flatMap(engagement => engagement.attachments.filter(file => !file.url).map(file => file.id)),
);
}

// Failed reads count as results too, so a run of errors cannot keep the re-reads going. A file starts the re-reads over
// when it first comes without a link, and when it loses its link again after a run is over: never during a run, so a
Comment thread
oleksandr-blip marked this conversation as resolved.
Resolved
// file that keeps losing and getting its link cannot extend one.
function relinkInterval(query: Query<TicketEngagement[], Error>): number | false {
const unlinked = unlinkedFiles(query.state.data);
if (unlinked.size === 0) {
relinkBudgets.delete(query);
return false;
}
const results = query.state.dataUpdateCount + query.state.errorUpdateCount;
const budget = relinkBudgets.get(query) ?? { files: new Map<string, boolean>(), since: results };
const runOver = results - budget.since > RELINK_DELAYS_MS.length;
const startsOver = [...unlinked].some(file => {
const linkedSince = budget.files.get(file);
return linkedSince === undefined || (runOver && linkedSince);
});
for (const file of budget.files.keys()) budget.files.set(file, !unlinked.has(file));
for (const file of unlinked) budget.files.set(file, false);
if (startsOver) budget.since = results;
relinkBudgets.set(query, budget);
return RELINK_DELAYS_MS[results - budget.since] ?? false;
}

export interface TicketEngagementFile {
id: string;
Expand Down Expand Up @@ -105,7 +149,9 @@ export function useTicketEngagements(
// NO interval polling (deleted 2026-08): new agent replies arrive via
// `TicketLiveProvider`'s stream-driven invalidation of
// `['ticket-engagements', id]`; focus/mount refetch is the no-stream
// fallback.
// fallback. The one timer left is the bounded re-read of a file that
// came without its link.
refetchInterval: relinkInterval,
Comment thread
oleksandr-blip marked this conversation as resolved.
Resolved
queryFn: async (): Promise<TicketEngagement[]> => {
const response = await embedAuthedFetch(listEngagementsEndpoint, {
method: 'POST',
Expand Down
Loading