@flamingo-stack/openframe-frontend-core 0.0.598 → 0.0.599-2039.5716.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-protocol/index.cjs +8 -1
- package/dist/chat-protocol/index.cjs.map +1 -1
- package/dist/chat-protocol/index.d.ts +1 -0
- package/dist/chat-protocol/index.d.ts.map +1 -1
- package/dist/chat-protocol/index.js +7 -2
- package/dist/chat-protocol/index.js.map +1 -1
- package/dist/chat-protocol/nats-decoder.d.ts.map +1 -1
- package/dist/chat-protocol/wire-narrow.d.ts +17 -0
- package/dist/chat-protocol/wire-narrow.d.ts.map +1 -0
- package/dist/{chunk-VLJTJAHJ.cjs → chunk-2B4HSYAX.cjs} +25 -25
- package/dist/{chunk-VLJTJAHJ.cjs.map → chunk-2B4HSYAX.cjs.map} +1 -1
- package/dist/{chunk-UE7OFLLS.cjs → chunk-2GCBN73M.cjs} +14 -14
- package/dist/{chunk-UE7OFLLS.cjs.map → chunk-2GCBN73M.cjs.map} +1 -1
- package/dist/{chunk-STYNZ4QM.cjs → chunk-3IXDZI3R.cjs} +3 -3
- package/dist/{chunk-STYNZ4QM.cjs.map → chunk-3IXDZI3R.cjs.map} +1 -1
- package/dist/{chunk-DAPOBLAK.cjs → chunk-3RWSKUIN.cjs} +39 -39
- package/dist/{chunk-DAPOBLAK.cjs.map → chunk-3RWSKUIN.cjs.map} +1 -1
- package/dist/{chunk-VNSRNVPD.js → chunk-4HJYXP5O.js} +722 -406
- package/dist/chunk-4HJYXP5O.js.map +1 -0
- package/dist/{chunk-HWAYIK4U.cjs → chunk-4MOY5TQR.cjs} +22 -22
- package/dist/{chunk-HWAYIK4U.cjs.map → chunk-4MOY5TQR.cjs.map} +1 -1
- package/dist/{chunk-VIRTMRS4.js → chunk-4PBUEYAE.js} +7 -7
- package/dist/{chunk-TZPVRWPU.js → chunk-4TG5BWPE.js} +5 -5
- package/dist/{chunk-PTK3CINU.js → chunk-6JF65LRQ.js} +5 -5
- package/dist/{chunk-YWBAIFI2.cjs → chunk-6XISE63Q.cjs} +105 -105
- package/dist/{chunk-YWBAIFI2.cjs.map → chunk-6XISE63Q.cjs.map} +1 -1
- package/dist/{chunk-QD64Q4I2.cjs → chunk-A4HMGZ4L.cjs} +9 -9
- package/dist/{chunk-QD64Q4I2.cjs.map → chunk-A4HMGZ4L.cjs.map} +1 -1
- package/dist/{chunk-BK6CCQG6.js → chunk-AUCJ6I3R.js} +12 -12
- package/dist/{chunk-3WSS7C2V.cjs → chunk-BBBZ5QUB.cjs} +15 -15
- package/dist/{chunk-3WSS7C2V.cjs.map → chunk-BBBZ5QUB.cjs.map} +1 -1
- package/dist/{chunk-EVMHJB6X.js → chunk-BLUL2TE3.js} +4 -4
- package/dist/{chunk-GGQZBSFN.js → chunk-BVQEU5JB.js} +2 -2
- package/dist/{chunk-V2QK5W3O.cjs → chunk-BW644MGF.cjs} +3 -3
- package/dist/{chunk-V2QK5W3O.cjs.map → chunk-BW644MGF.cjs.map} +1 -1
- package/dist/{chunk-H64ZHSYR.cjs → chunk-CCWI3622.cjs} +4 -4
- package/dist/{chunk-H64ZHSYR.cjs.map → chunk-CCWI3622.cjs.map} +1 -1
- package/dist/{chunk-DI3SVVY5.cjs → chunk-COERKO4N.cjs} +85 -85
- package/dist/{chunk-DI3SVVY5.cjs.map → chunk-COERKO4N.cjs.map} +1 -1
- package/dist/{chunk-SE3PVN64.js → chunk-DZ44C6KB.js} +2 -2
- package/dist/{chunk-2SYX2Z7R.cjs → chunk-E27TMQRE.cjs} +34 -34
- package/dist/{chunk-2SYX2Z7R.cjs.map → chunk-E27TMQRE.cjs.map} +1 -1
- package/dist/{chunk-YH6IQTPI.cjs → chunk-EHAYNUOL.cjs} +3 -3
- package/dist/{chunk-YH6IQTPI.cjs.map → chunk-EHAYNUOL.cjs.map} +1 -1
- package/dist/{chunk-WZJOILPU.js → chunk-F2KBCLUG.js} +2 -2
- package/dist/{chunk-MYBXCWEI.js → chunk-FKBM6U43.js} +2 -2
- package/dist/{chunk-75YW6ET4.js → chunk-FNK4RZ25.js} +4 -4
- package/dist/{chunk-UG7JNQZY.cjs → chunk-GB5FPCUN.cjs} +37 -37
- package/dist/{chunk-UG7JNQZY.cjs.map → chunk-GB5FPCUN.cjs.map} +1 -1
- package/dist/{chunk-P24VPJTT.cjs → chunk-HJUXXWTM.cjs} +15 -15
- package/dist/{chunk-P24VPJTT.cjs.map → chunk-HJUXXWTM.cjs.map} +1 -1
- package/dist/{chunk-WPN545FW.js → chunk-ILJTXIEI.js} +12 -12
- package/dist/{chunk-YBPFIXV4.cjs → chunk-ITZDJYWI.cjs} +796 -480
- package/dist/chunk-ITZDJYWI.cjs.map +1 -0
- package/dist/{chunk-LRQCKSZC.js → chunk-IW746HJ7.js} +2 -2
- package/dist/{chunk-PX4IPM7Q.js → chunk-J62LLUDC.js} +3 -3
- package/dist/{chunk-M4YQUHOR.cjs → chunk-JJUV7Z4L.cjs} +15 -15
- package/dist/{chunk-M4YQUHOR.cjs.map → chunk-JJUV7Z4L.cjs.map} +1 -1
- package/dist/{chunk-GHYFVT52.js → chunk-JZF6EUMO.js} +5 -5
- package/dist/{chunk-JVZVVZOZ.cjs → chunk-KYGTR6EG.cjs} +9 -9
- package/dist/{chunk-JVZVVZOZ.cjs.map → chunk-KYGTR6EG.cjs.map} +1 -1
- package/dist/{chunk-QIKBISZM.cjs → chunk-L66UPFCQ.cjs} +242 -242
- package/dist/{chunk-QIKBISZM.cjs.map → chunk-L66UPFCQ.cjs.map} +1 -1
- package/dist/{chunk-NIAMPMKV.js → chunk-LJ4UG2SW.js} +4 -4
- package/dist/{chunk-WDWCQD75.js → chunk-MWQSHXYK.js} +9 -9
- package/dist/{chunk-BPVHDDNY.cjs → chunk-NLFST5II.cjs} +8 -8
- package/dist/{chunk-BPVHDDNY.cjs.map → chunk-NLFST5II.cjs.map} +1 -1
- package/dist/{chunk-SAEJGTCI.cjs → chunk-QPAPUIF3.cjs} +35 -35
- package/dist/{chunk-SAEJGTCI.cjs.map → chunk-QPAPUIF3.cjs.map} +1 -1
- package/dist/{chunk-HLPAVYK7.js → chunk-RSTEDWAT.js} +4 -4
- package/dist/{chunk-UAAXUFK6.js → chunk-RU3IKVY2.js} +3 -3
- package/dist/{chunk-EZM5DNII.js → chunk-S6WBBSII.js} +3 -3
- package/dist/{chunk-2JNCZDJR.js → chunk-TSCIVH7T.js} +2 -2
- package/dist/{chunk-RDTOMWDN.cjs → chunk-UPKZU6QU.cjs} +1 -1
- package/dist/chunk-UPKZU6QU.cjs.map +1 -0
- package/dist/{chunk-WCBRZCU4.cjs → chunk-UQEOAPAI.cjs} +9 -9
- package/dist/{chunk-WCBRZCU4.cjs.map → chunk-UQEOAPAI.cjs.map} +1 -1
- package/dist/{chunk-O4VZOA2Q.cjs → chunk-UXOOVP77.cjs} +3 -3
- package/dist/{chunk-O4VZOA2Q.cjs.map → chunk-UXOOVP77.cjs.map} +1 -1
- package/dist/{chunk-R4UV366K.js → chunk-UYLZAW6Y.js} +6 -6
- package/dist/{chunk-BZEWPW5A.cjs → chunk-VIBREYUK.cjs} +3 -3
- package/dist/{chunk-BZEWPW5A.cjs.map → chunk-VIBREYUK.cjs.map} +1 -1
- package/dist/{chunk-KHOZ52NR.js → chunk-XSMBLU44.js} +6 -6
- package/dist/{chunk-RYXIRVDC.js → chunk-YB6FI2G3.js} +1 -1
- package/dist/chunk-YB6FI2G3.js.map +1 -0
- package/dist/{chunk-XNPAVMPB.js → chunk-YG7DCXRD.js} +5 -5
- package/dist/components/case-studies/index.cjs +14 -14
- package/dist/components/case-studies/index.js +8 -8
- package/dist/components/chat/embeddable-chat.d.ts +10 -19
- package/dist/components/chat/embeddable-chat.d.ts.map +1 -1
- package/dist/components/chat/hooks/index.d.ts +1 -0
- package/dist/components/chat/hooks/index.d.ts.map +1 -1
- package/dist/components/chat/hooks/use-chat-history-hydration.d.ts +13 -3
- package/dist/components/chat/hooks/use-chat-history-hydration.d.ts.map +1 -1
- package/dist/components/chat/hooks/use-managed-dialog-list.d.ts +53 -0
- package/dist/components/chat/hooks/use-managed-dialog-list.d.ts.map +1 -0
- package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts +2 -16
- package/dist/components/chat/hooks/use-nats-chat-adapter.d.ts.map +1 -1
- package/dist/components/chat/hooks/use-sse-chat-adapter.d.ts.map +1 -1
- package/dist/components/chat/hooks/use-unified-chat.d.ts.map +1 -1
- package/dist/components/chat/index.cjs +9 -5
- package/dist/components/chat/index.cjs.map +1 -1
- package/dist/components/chat/index.js +8 -4
- package/dist/components/chat/types/unified-chat-state.types.d.ts +72 -6
- package/dist/components/chat/types/unified-chat-state.types.d.ts.map +1 -1
- package/dist/components/chat/utils/chat-conversations-api.d.ts +29 -0
- package/dist/components/chat/utils/chat-conversations-api.d.ts.map +1 -0
- package/dist/components/chat/utils/index.d.ts +1 -0
- package/dist/components/chat/utils/index.d.ts.map +1 -1
- package/dist/components/contact/index.cjs +9 -9
- package/dist/components/contact/index.js +8 -8
- package/dist/components/docs/index.cjs +12 -12
- package/dist/components/docs/index.js +11 -11
- package/dist/components/embeds/index.cjs +9 -9
- package/dist/components/embeds/index.js +8 -8
- package/dist/components/faq/index.cjs +10 -10
- package/dist/components/faq/index.js +9 -9
- package/dist/components/features/index.cjs +8 -8
- package/dist/components/features/index.js +7 -7
- package/dist/components/help-center-pages/index.cjs +31 -31
- package/dist/components/help-center-pages/index.js +22 -22
- package/dist/components/index.cjs +70 -66
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.js +26 -22
- package/dist/components/index.js.map +1 -1
- package/dist/components/meeting-scheduler/index.cjs +49 -49
- package/dist/components/meeting-scheduler/index.js +9 -9
- package/dist/components/navigation/index.cjs +11 -11
- package/dist/components/navigation/index.js +10 -10
- package/dist/components/onboarding-guides/index.cjs +12 -12
- package/dist/components/onboarding-guides/index.js +11 -11
- package/dist/components/related-content/index.cjs +7 -7
- package/dist/components/related-content/index.js +6 -6
- package/dist/components/tickets/index.cjs +13 -13
- package/dist/components/tickets/index.js +12 -12
- package/dist/components/ui/index.cjs +12 -8
- package/dist/components/ui/index.cjs.map +1 -1
- package/dist/components/ui/index.js +11 -7
- package/dist/contexts/chat-runtime-context.d.ts +12 -0
- package/dist/contexts/chat-runtime-context.d.ts.map +1 -1
- package/dist/contexts/index.cjs +2 -2
- package/dist/contexts/index.js +1 -1
- package/dist/hooks/index.cjs +5 -5
- package/dist/hooks/index.js +4 -4
- package/dist/index.cjs +16 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +15 -11
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/chat-protocol/index.ts +1 -0
- package/src/chat-protocol/nats-decoder.ts +1 -5
- package/src/chat-protocol/wire-narrow.ts +22 -0
- package/src/components/chat/.embeddable-chat.md +4 -2
- package/src/components/chat/embeddable-chat.tsx +136 -84
- package/src/components/chat/hooks/.index.md +1 -1
- package/src/components/chat/hooks/.use-managed-dialog-list.md +31 -0
- package/src/components/chat/hooks/.use-nats-chat-adapter.md +3 -1
- package/src/components/chat/hooks/.use-sse-chat-adapter.md +8 -1
- package/src/components/chat/hooks/.use-unified-chat.md +2 -2
- package/src/components/chat/hooks/__tests__/managed-dialog-list.test.ts +280 -0
- package/src/components/chat/hooks/__tests__/nats-adapter-managed-dialogs.test.ts +173 -0
- package/src/components/chat/hooks/__tests__/sse-managed-dialogs.test.ts +310 -0
- package/src/components/chat/hooks/index.ts +2 -0
- package/src/components/chat/hooks/use-chat-history-hydration.ts +67 -24
- package/src/components/chat/hooks/use-managed-dialog-list.ts +339 -0
- package/src/components/chat/hooks/use-nats-chat-adapter.ts +65 -150
- package/src/components/chat/hooks/use-sse-chat-adapter.ts +233 -59
- package/src/components/chat/hooks/use-unified-chat.ts +5 -0
- package/src/components/chat/types/.unified-chat-state.types.md +13 -1
- package/src/components/chat/types/unified-chat-state.types.ts +79 -6
- package/src/components/chat/utils/.chat-conversations-api.md +16 -0
- package/src/components/chat/utils/.index.md +1 -1
- package/src/components/chat/utils/__tests__/chat-conversations-api-golden.test.ts +105 -0
- package/src/components/chat/utils/chat-conversations-api.ts +83 -0
- package/src/components/chat/utils/index.ts +7 -0
- package/src/contexts/.chat-runtime-context.md +3 -1
- package/src/contexts/chat-runtime-context.tsx +12 -0
- package/dist/chunk-RDTOMWDN.cjs.map +0 -1
- package/dist/chunk-RYXIRVDC.js.map +0 -1
- package/dist/chunk-VNSRNVPD.js.map +0 -1
- package/dist/chunk-YBPFIXV4.cjs.map +0 -1
- /package/dist/{chunk-VIRTMRS4.js.map → chunk-4PBUEYAE.js.map} +0 -0
- /package/dist/{chunk-TZPVRWPU.js.map → chunk-4TG5BWPE.js.map} +0 -0
- /package/dist/{chunk-PTK3CINU.js.map → chunk-6JF65LRQ.js.map} +0 -0
- /package/dist/{chunk-BK6CCQG6.js.map → chunk-AUCJ6I3R.js.map} +0 -0
- /package/dist/{chunk-EVMHJB6X.js.map → chunk-BLUL2TE3.js.map} +0 -0
- /package/dist/{chunk-GGQZBSFN.js.map → chunk-BVQEU5JB.js.map} +0 -0
- /package/dist/{chunk-SE3PVN64.js.map → chunk-DZ44C6KB.js.map} +0 -0
- /package/dist/{chunk-WZJOILPU.js.map → chunk-F2KBCLUG.js.map} +0 -0
- /package/dist/{chunk-MYBXCWEI.js.map → chunk-FKBM6U43.js.map} +0 -0
- /package/dist/{chunk-75YW6ET4.js.map → chunk-FNK4RZ25.js.map} +0 -0
- /package/dist/{chunk-WPN545FW.js.map → chunk-ILJTXIEI.js.map} +0 -0
- /package/dist/{chunk-LRQCKSZC.js.map → chunk-IW746HJ7.js.map} +0 -0
- /package/dist/{chunk-PX4IPM7Q.js.map → chunk-J62LLUDC.js.map} +0 -0
- /package/dist/{chunk-GHYFVT52.js.map → chunk-JZF6EUMO.js.map} +0 -0
- /package/dist/{chunk-NIAMPMKV.js.map → chunk-LJ4UG2SW.js.map} +0 -0
- /package/dist/{chunk-WDWCQD75.js.map → chunk-MWQSHXYK.js.map} +0 -0
- /package/dist/{chunk-HLPAVYK7.js.map → chunk-RSTEDWAT.js.map} +0 -0
- /package/dist/{chunk-UAAXUFK6.js.map → chunk-RU3IKVY2.js.map} +0 -0
- /package/dist/{chunk-EZM5DNII.js.map → chunk-S6WBBSII.js.map} +0 -0
- /package/dist/{chunk-2JNCZDJR.js.map → chunk-TSCIVH7T.js.map} +0 -0
- /package/dist/{chunk-R4UV366K.js.map → chunk-UYLZAW6Y.js.map} +0 -0
- /package/dist/{chunk-KHOZ52NR.js.map → chunk-XSMBLU44.js.map} +0 -0
- /package/dist/{chunk-XNPAVMPB.js.map → chunk-YG7DCXRD.js.map} +0 -0
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GOLDEN CONTRACT TESTS — Guide/SSE adapter with a managed conversation list
|
|
3
|
+
* (`ChatRuntime.endpoints.chatConversationsUrl`).
|
|
4
|
+
*
|
|
5
|
+
* Pins:
|
|
6
|
+
* - mount with a stored id → `activeDialogId` = stored, ONE list GET
|
|
7
|
+
* (`status=active&limit=20`), ONE history GET;
|
|
8
|
+
* - `selectDialog('b')` → thread reset, history GET for `b`, storage = `b`,
|
|
9
|
+
* `isMessagesLoading` true → false;
|
|
10
|
+
* - `clearMessages` → draft state (null id, storage cleared);
|
|
11
|
+
* - first send of a NEW conversation → id captured from the metadata frame,
|
|
12
|
+
* NO history GET for that id, list re-read at end of turn;
|
|
13
|
+
* - rename / archive / restore go to the PATCH wire; archiving the open
|
|
14
|
+
* conversation drops to draft;
|
|
15
|
+
* - ZERO-REGRESSION: without the endpoint `dialogs` is `[]`,
|
|
16
|
+
* `dialogsManaged` is false and no conversations request is issued.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
20
|
+
import { renderHook, act, waitFor } from '@testing-library/react';
|
|
21
|
+
import { createElement, type ReactNode } from 'react';
|
|
22
|
+
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
23
|
+
import { ChatRuntimeContext, type ChatRuntime } from '../../../../contexts/chat-runtime-context';
|
|
24
|
+
import { useSseChatAdapter } from '../use-sse-chat-adapter';
|
|
25
|
+
|
|
26
|
+
const SOURCE = 'managedsrc';
|
|
27
|
+
const CONVERSATION_KEY = `mingo-chat-${SOURCE}.conversation`;
|
|
28
|
+
const CONVERSATIONS_URL = '/api/docs/chat/conversations';
|
|
29
|
+
|
|
30
|
+
const baseEndpoints: ChatRuntime['endpoints'] = {
|
|
31
|
+
chatStreamUrl: '/api/docs/chat',
|
|
32
|
+
approvalToolUrl: '/api/chat/agent/confirm-tool',
|
|
33
|
+
commandsUrl: '/api/docs/commands',
|
|
34
|
+
buildListUrl: () => null,
|
|
35
|
+
attachmentUploadUrl: '/api/storage/generate-upload-url',
|
|
36
|
+
attachmentViewUrlPrefix: '/api/storage/view/chat-attachments/',
|
|
37
|
+
identityUrl: '/api/chat/identity',
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function makeWrapper(runtime: ChatRuntime) {
|
|
41
|
+
return function wrapper({ children }: { children: ReactNode }) {
|
|
42
|
+
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
|
43
|
+
return createElement(
|
|
44
|
+
QueryClientProvider,
|
|
45
|
+
{ client: queryClient },
|
|
46
|
+
createElement(ChatRuntimeContext.Provider, { value: runtime }, children),
|
|
47
|
+
);
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const managedRuntime: ChatRuntime = {
|
|
52
|
+
endpoints: { ...baseEndpoints, chatConversationsUrl: CONVERSATIONS_URL },
|
|
53
|
+
navigation: { mode: 'host' },
|
|
54
|
+
source: SOURCE,
|
|
55
|
+
};
|
|
56
|
+
const plainRuntime: ChatRuntime = { endpoints: baseEndpoints, navigation: { mode: 'host' }, source: SOURCE };
|
|
57
|
+
|
|
58
|
+
const enc = new TextEncoder();
|
|
59
|
+
function streamOf(chunks: string[]): ReadableStream<Uint8Array> {
|
|
60
|
+
return new ReadableStream<Uint8Array>({
|
|
61
|
+
start(controller) {
|
|
62
|
+
for (const c of chunks) controller.enqueue(enc.encode(c));
|
|
63
|
+
controller.close();
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
const USAGE_END_TRAILER = '{"kind":"usage","stage":"end","input_tokens":10,"output_tokens":5,"hit_rate_pct":50}';
|
|
68
|
+
function wireTurn(conversationId: string, answer: string): string[] {
|
|
69
|
+
return [
|
|
70
|
+
`{"modelLabel":"Claude Sonnet","provider":"anthropic","conversationId":"${conversationId}"}\0`,
|
|
71
|
+
'\x1E',
|
|
72
|
+
answer,
|
|
73
|
+
'\x1F' + USAGE_END_TRAILER,
|
|
74
|
+
];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const historyFor = (id: string) => ({
|
|
78
|
+
data: {
|
|
79
|
+
messages: [
|
|
80
|
+
{ seq: 0, role: 'user', content: `q for ${id}`, created_at: '2026-09-01T09:00:00.000Z' },
|
|
81
|
+
{ seq: 1, role: 'assistant', content: `a for ${id}`, created_at: '2026-09-01T09:00:05.000Z' },
|
|
82
|
+
],
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
const listPayload = (ids: string[]) => ({
|
|
86
|
+
data: {
|
|
87
|
+
dialogs: ids.map(id => ({ id, title: `Chat ${id}`, timestamp: '2026-09-01T09:00:00.000Z' })),
|
|
88
|
+
nextCursor: null,
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
type Call = { url: string; init: RequestInit };
|
|
93
|
+
function mockFetch(options: { list?: () => unknown; streams?: string[][] }) {
|
|
94
|
+
const calls: Call[] = [];
|
|
95
|
+
let streamCall = 0;
|
|
96
|
+
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
|
|
97
|
+
const u = String(url);
|
|
98
|
+
calls.push({ url: u, init: init ?? {} });
|
|
99
|
+
const json = (body: unknown, status = 200) =>
|
|
100
|
+
Promise.resolve({ ok: status < 300, status, json: () => Promise.resolve(body) } as unknown as Response);
|
|
101
|
+
if (u.startsWith(CONVERSATIONS_URL + '/')) return json({ data: { id: 'x' } });
|
|
102
|
+
if (u.startsWith(CONVERSATIONS_URL)) return json(options.list ? options.list() : listPayload([]));
|
|
103
|
+
if (u.includes('/history')) {
|
|
104
|
+
const id = new URL(u, 'http://x').searchParams.get('conversationId') ?? '';
|
|
105
|
+
return json(historyFor(id));
|
|
106
|
+
}
|
|
107
|
+
if (u.includes('/commands')) return json({ commands: [] });
|
|
108
|
+
const streams = options.streams ?? [];
|
|
109
|
+
const chunks = streams[Math.min(streamCall, streams.length - 1)] ?? [];
|
|
110
|
+
streamCall += 1;
|
|
111
|
+
return Promise.resolve({ ok: true, status: 200, body: streamOf(chunks) } as unknown as Response);
|
|
112
|
+
});
|
|
113
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
114
|
+
return { fetchMock, calls };
|
|
115
|
+
}
|
|
116
|
+
const urlsOf = (calls: Call[], prefix: string) => calls.filter(c => c.url.startsWith(prefix)).map(c => c.url);
|
|
117
|
+
|
|
118
|
+
describe('useSseChatAdapter — managed conversation list', () => {
|
|
119
|
+
beforeEach(() => {
|
|
120
|
+
window.localStorage.clear();
|
|
121
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
122
|
+
});
|
|
123
|
+
afterEach(() => {
|
|
124
|
+
vi.restoreAllMocks();
|
|
125
|
+
vi.unstubAllGlobals();
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('mount with a stored id: lists once, hydrates once, highlights the stored conversation', async () => {
|
|
129
|
+
window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
|
|
130
|
+
const { calls } = mockFetch({ list: () => listPayload(['a', 'b']) });
|
|
131
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
|
|
132
|
+
|
|
133
|
+
await waitFor(() => expect(result.current.dialogs.map(d => d.id)).toEqual(['a', 'b']));
|
|
134
|
+
await waitFor(() => expect(result.current.messages.length).toBe(2));
|
|
135
|
+
expect(result.current.dialogsManaged).toBe(true);
|
|
136
|
+
expect(result.current.activeDialogId).toBe('a');
|
|
137
|
+
expect(urlsOf(calls, CONVERSATIONS_URL)).toEqual([`${CONVERSATIONS_URL}?status=active&limit=20`]);
|
|
138
|
+
expect(urlsOf(calls, '/api/docs/chat/history')).toEqual(['/api/docs/chat/history?conversationId=a']);
|
|
139
|
+
expect(result.current.dialogCapabilities).toMatchObject({ canRename: true, canArchive: true, searchQuery: '' });
|
|
140
|
+
expect(result.current.dialogCapabilities?.fetchArchivedDialogs).toBeTypeOf('function');
|
|
141
|
+
expect(result.current.dialogCapabilities?.unarchiveDialog).toBeTypeOf('function');
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('selectDialog switches the thread: reset, hydrate the new id, persist it', async () => {
|
|
145
|
+
window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
|
|
146
|
+
const { calls } = mockFetch({ list: () => listPayload(['a', 'b']) });
|
|
147
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
|
|
148
|
+
await waitFor(() => expect(result.current.messages.length).toBe(2));
|
|
149
|
+
|
|
150
|
+
act(() => result.current.selectDialog('b'));
|
|
151
|
+
expect(result.current.activeDialogId).toBe('b');
|
|
152
|
+
expect(JSON.parse(window.localStorage.getItem(CONVERSATION_KEY) ?? '{}')).toEqual({ conversationId: 'b' });
|
|
153
|
+
await waitFor(() => expect(result.current.messages.map(m => m.content)).toEqual(['q for b', 'a for b']));
|
|
154
|
+
expect(result.current.isMessagesLoading).toBe(false);
|
|
155
|
+
expect(urlsOf(calls, '/api/docs/chat/history')).toEqual([
|
|
156
|
+
'/api/docs/chat/history?conversationId=a',
|
|
157
|
+
'/api/docs/chat/history?conversationId=b',
|
|
158
|
+
]);
|
|
159
|
+
|
|
160
|
+
// Idempotent on the active id — no extra fetch.
|
|
161
|
+
act(() => result.current.selectDialog('b'));
|
|
162
|
+
expect(urlsOf(calls, '/api/docs/chat/history').length).toBe(2);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('clearMessages drops to draft state (null id, storage cleared)', async () => {
|
|
166
|
+
window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
|
|
167
|
+
mockFetch({ list: () => listPayload(['a']) });
|
|
168
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
|
|
169
|
+
await waitFor(() => expect(result.current.messages.length).toBe(2));
|
|
170
|
+
act(() => result.current.clearMessages());
|
|
171
|
+
expect(result.current.activeDialogId).toBeNull();
|
|
172
|
+
expect(result.current.messages).toEqual([]);
|
|
173
|
+
expect(window.localStorage.getItem(CONVERSATION_KEY)).toBeNull();
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it('first send: captures the minted id WITHOUT hydrating it, and re-reads the list at end of turn', async () => {
|
|
177
|
+
let listed = 0;
|
|
178
|
+
const { calls } = mockFetch({
|
|
179
|
+
list: () => {
|
|
180
|
+
listed += 1;
|
|
181
|
+
return listed === 1 ? listPayload([]) : listPayload(['conv-new']);
|
|
182
|
+
},
|
|
183
|
+
streams: [wireTurn('conv-new', 'Hello there.')],
|
|
184
|
+
});
|
|
185
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
|
|
186
|
+
await waitFor(() => expect(listed).toBe(1));
|
|
187
|
+
|
|
188
|
+
await act(async () => {
|
|
189
|
+
await result.current.sendMessage('first question');
|
|
190
|
+
});
|
|
191
|
+
expect(result.current.activeDialogId).toBe('conv-new');
|
|
192
|
+
expect(urlsOf(calls, '/api/docs/chat/history')).toEqual([]);
|
|
193
|
+
await waitFor(() => expect(listed).toBe(2));
|
|
194
|
+
expect(result.current.dialogs.map(d => d.id)).toEqual(['conv-new']);
|
|
195
|
+
// The streamed turn is the thread — nothing was prepended by hydration.
|
|
196
|
+
expect(result.current.messages.map(m => m.role)).toEqual(['user', 'assistant']);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it('rename / archive / restore hit the PATCH wire; archiving the open chat drops to draft', async () => {
|
|
200
|
+
window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
|
|
201
|
+
const { calls } = mockFetch({ list: () => listPayload(['a', 'b']) });
|
|
202
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
|
|
203
|
+
await waitFor(() => expect(result.current.dialogs.length).toBe(2));
|
|
204
|
+
|
|
205
|
+
await act(async () => {
|
|
206
|
+
await result.current.renameDialog('b', 'Renamed B');
|
|
207
|
+
});
|
|
208
|
+
expect(result.current.dialogs.find(d => d.id === 'b')?.title).toBe('Renamed B');
|
|
209
|
+
|
|
210
|
+
await act(async () => {
|
|
211
|
+
await result.current.archiveDialog('a');
|
|
212
|
+
});
|
|
213
|
+
expect(result.current.dialogs.map(d => d.id)).toEqual(['b']);
|
|
214
|
+
expect(result.current.activeDialogId).toBeNull();
|
|
215
|
+
|
|
216
|
+
await act(async () => {
|
|
217
|
+
await result.current.dialogCapabilities?.unarchiveDialog?.('a');
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
const patches = calls.filter(c => c.url.startsWith(CONVERSATIONS_URL + '/'));
|
|
221
|
+
const parseBody = (c: Call): unknown => JSON.parse(String(c.init.body));
|
|
222
|
+
expect(patches.map(c => [c.url, c.init.method, parseBody(c)])).toEqual([
|
|
223
|
+
[`${CONVERSATIONS_URL}/b`, 'PATCH', { title: 'Renamed B' }],
|
|
224
|
+
[`${CONVERSATIONS_URL}/a`, 'PATCH', { archived: true }],
|
|
225
|
+
[`${CONVERSATIONS_URL}/a`, 'PATCH', { archived: false }],
|
|
226
|
+
]);
|
|
227
|
+
// Restore re-reads the active list.
|
|
228
|
+
expect(urlsOf(calls, `${CONVERSATIONS_URL}?`).length).toBeGreaterThanOrEqual(2);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it('search term change re-reads page 1 with `search`', async () => {
|
|
232
|
+
const { calls } = mockFetch({ list: () => listPayload(['a']) });
|
|
233
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
|
|
234
|
+
await waitFor(() => expect(result.current.dialogs.length).toBe(1));
|
|
235
|
+
act(() => result.current.dialogCapabilities?.onSearchChange?.('print'));
|
|
236
|
+
await waitFor(() =>
|
|
237
|
+
expect(urlsOf(calls, `${CONVERSATIONS_URL}?`)).toEqual([
|
|
238
|
+
`${CONVERSATIONS_URL}?status=active&limit=20`,
|
|
239
|
+
`${CONVERSATIONS_URL}?status=active&limit=20&search=print`,
|
|
240
|
+
]),
|
|
241
|
+
);
|
|
242
|
+
expect(result.current.dialogCapabilities?.searchQuery).toBe('print');
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it('never wedges on the message skeleton when a hydration is superseded', async () => {
|
|
246
|
+
window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
|
|
247
|
+
mockFetch({ list: () => listPayload(['a', 'b']) });
|
|
248
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
|
|
249
|
+
await waitFor(() => expect(result.current.messages.length).toBe(2));
|
|
250
|
+
|
|
251
|
+
// "New chat" while a hydration could still be in flight: the loading flag
|
|
252
|
+
// must clear, or `hasConversation` pins the panel on a skeleton forever.
|
|
253
|
+
act(() => result.current.clearMessages());
|
|
254
|
+
await waitFor(() => expect(result.current.isMessagesLoading).toBe(false));
|
|
255
|
+
expect(result.current.activeDialogId).toBeNull();
|
|
256
|
+
|
|
257
|
+
// Same for selecting away mid-flight.
|
|
258
|
+
act(() => result.current.selectDialog('b'));
|
|
259
|
+
act(() => result.current.selectDialog(null));
|
|
260
|
+
await waitFor(() => expect(result.current.isMessagesLoading).toBe(false));
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it('keeps a stored id whose thread is legitimately empty but owned', async () => {
|
|
264
|
+
window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'empty-but-mine' }));
|
|
265
|
+
const { fetchMock } = mockFetch({ list: () => listPayload([]) });
|
|
266
|
+
fetchMock.mockImplementation((url: string) => {
|
|
267
|
+
const u = String(url);
|
|
268
|
+
const json = (body: unknown) =>
|
|
269
|
+
Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(body) } as unknown as Response);
|
|
270
|
+
// Owned, just has no rows yet — the id must SURVIVE.
|
|
271
|
+
if (u.includes('/history')) return json({ conversationId: 'empty-but-mine', messages: [], found: true });
|
|
272
|
+
if (u.startsWith(CONVERSATIONS_URL)) return json(listPayload([]));
|
|
273
|
+
return json({ commands: [] });
|
|
274
|
+
});
|
|
275
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
|
|
276
|
+
await waitFor(() => expect(result.current.dialogsManaged).toBe(true));
|
|
277
|
+
await new Promise(resolve => setTimeout(resolve, 20));
|
|
278
|
+
expect(window.localStorage.getItem(CONVERSATION_KEY)).not.toBeNull();
|
|
279
|
+
expect(result.current.activeDialogId).toBe('empty-but-mine');
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
it('drops a stored id the server reports as not ours (found: false)', async () => {
|
|
283
|
+
window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'gone' }));
|
|
284
|
+
const { fetchMock } = mockFetch({ list: () => listPayload([]) });
|
|
285
|
+
fetchMock.mockImplementation((url: string) => {
|
|
286
|
+
const u = String(url);
|
|
287
|
+
const json = (body: unknown) =>
|
|
288
|
+
Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(body) } as unknown as Response);
|
|
289
|
+
// `found: false` = the server does not recognize this id for us.
|
|
290
|
+
if (u.includes('/history')) return json({ conversationId: 'gone', messages: [], found: false });
|
|
291
|
+
if (u.startsWith(CONVERSATIONS_URL)) return json(listPayload([]));
|
|
292
|
+
return json({ commands: [] });
|
|
293
|
+
});
|
|
294
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(managedRuntime) });
|
|
295
|
+
await waitFor(() => expect(window.localStorage.getItem(CONVERSATION_KEY)).toBeNull());
|
|
296
|
+
expect(result.current.activeDialogId).toBeNull();
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it('ZERO-REGRESSION: without chatConversationsUrl the single-thread stubs are returned', async () => {
|
|
300
|
+
window.localStorage.setItem(CONVERSATION_KEY, JSON.stringify({ conversationId: 'a' }));
|
|
301
|
+
const { calls } = mockFetch({});
|
|
302
|
+
const { result } = renderHook(() => useSseChatAdapter(), { wrapper: makeWrapper(plainRuntime) });
|
|
303
|
+
await waitFor(() => expect(result.current.messages.length).toBe(2));
|
|
304
|
+
expect(result.current.dialogs).toEqual([]);
|
|
305
|
+
expect(result.current.dialogsManaged).toBe(false);
|
|
306
|
+
expect(result.current.dialogCapabilities).toBeUndefined();
|
|
307
|
+
expect(result.current.activeDialogId).toBeNull();
|
|
308
|
+
expect(urlsOf(calls, CONVERSATIONS_URL)).toEqual([]);
|
|
309
|
+
});
|
|
310
|
+
});
|
|
@@ -27,6 +27,8 @@ export * from './use-sse';
|
|
|
27
27
|
// access is needed. `useEmbeddedChat` is the legacy SSE alias.
|
|
28
28
|
export * from './use-sse-chat-adapter';
|
|
29
29
|
export * from './use-nats-chat-adapter';
|
|
30
|
+
// Shared dialog-list state machine behind both adapters' managed modes.
|
|
31
|
+
export * from './use-managed-dialog-list';
|
|
30
32
|
export * from './use-unified-chat';
|
|
31
33
|
export * from './use-embedded-chat';
|
|
32
34
|
|
|
@@ -18,16 +18,11 @@
|
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
import { useEffect, useRef, useState, type MutableRefObject } from 'react';
|
|
21
|
+
import { isRecord, unwrapEnvelope } from '../../../chat-protocol/wire-narrow';
|
|
21
22
|
import { embedAuthedFetch } from '../../../utils/embed-authed-fetch';
|
|
22
23
|
import { AUTO_CONTINUATION_DIRECTIVE_PREFIX } from '../utils/auto-continuation-directive';
|
|
23
24
|
import type { Message } from './use-chat';
|
|
24
25
|
|
|
25
|
-
/** Narrow one hop of an untrusted JSON body to something with readable keys.
|
|
26
|
-
* `typeof null === 'object'`, so the null check is the whole point. */
|
|
27
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
28
|
-
return typeof value === 'object' && value !== null;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
26
|
export interface UseChatHistoryHydrationArgs {
|
|
32
27
|
/** Mirrors the adapter's `active` gate — an idle (Mingo-mode) mount never fetches. */
|
|
33
28
|
active: boolean;
|
|
@@ -35,8 +30,10 @@ export interface UseChatHistoryHydrationArgs {
|
|
|
35
30
|
source: string;
|
|
36
31
|
/** Resolved history endpoint (`<chatStreamUrl>/history` by default). */
|
|
37
32
|
historyUrl: string;
|
|
38
|
-
/** The server-issued conversation id (null = nothing to hydrate).
|
|
39
|
-
|
|
33
|
+
/** The server-issued conversation id (null = nothing to hydrate). A VALUE,
|
|
34
|
+
* not a ref: switching conversations (`selectDialog`) must re-run the
|
|
35
|
+
* fetch, so the id is an effect dependency. */
|
|
36
|
+
conversationId: string | null;
|
|
40
37
|
/** User-send counter — set to the hydrated user-turn count so the next
|
|
41
38
|
* live send lands on the following `sendIdx`. */
|
|
42
39
|
sendCountRef: MutableRefObject<number>;
|
|
@@ -49,6 +46,14 @@ export interface UseChatHistoryHydrationArgs {
|
|
|
49
46
|
) => void;
|
|
50
47
|
/** Invalidates the adapter's `latestMeta` memo after hydration lands. */
|
|
51
48
|
bumpMetaTick: () => void;
|
|
49
|
+
/** The server answered OK and reported the id as NOT READABLE by this caller
|
|
50
|
+
* (`found: false`) — it no longer exists, or is no longer ours (e.g. the
|
|
51
|
+
* thread was claimed by an account and this browser is now signed out).
|
|
52
|
+
* Distinct from a fetch FAILURE, which keeps the id so a transient outage
|
|
53
|
+
* never loses context, and from a legitimately EMPTY but owned thread, which
|
|
54
|
+
* also keeps it. A host that persists the id should drop it here — otherwise
|
|
55
|
+
* every later turn streams an answer the server refuses to record. */
|
|
56
|
+
onOrphanedConversation?: (conversationId: string) => void;
|
|
52
57
|
}
|
|
53
58
|
|
|
54
59
|
export interface UseChatHistoryHydrationResult {
|
|
@@ -64,24 +69,34 @@ export function useChatHistoryHydration({
|
|
|
64
69
|
active,
|
|
65
70
|
source,
|
|
66
71
|
historyUrl,
|
|
67
|
-
|
|
72
|
+
conversationId,
|
|
68
73
|
sendCountRef,
|
|
69
74
|
hydrateMessages,
|
|
70
75
|
bumpMetaTick,
|
|
76
|
+
onOrphanedConversation,
|
|
71
77
|
}: UseChatHistoryHydrationArgs): UseChatHistoryHydrationResult {
|
|
72
78
|
const [isHydratingHistory, setIsHydratingHistory] = useState(false);
|
|
73
79
|
const hydratedKeyRef = useRef<string | null>(null);
|
|
80
|
+
// Monotonic run id: only the LATEST hydration owns the loading flag, so a
|
|
81
|
+
// slow superseded run resolving after a newer one started cannot clear the
|
|
82
|
+
// skeleton out from under it. (Same guard `useManagedDialogList` uses.)
|
|
83
|
+
const runIdRef = useRef(0);
|
|
74
84
|
|
|
75
85
|
useEffect(() => {
|
|
76
|
-
|
|
77
|
-
//
|
|
78
|
-
//
|
|
79
|
-
|
|
80
|
-
|
|
86
|
+
// The flag is owned by the fetch below and released in its `finally`; the
|
|
87
|
+
// CLEANUP releases it for every early exit and for a superseded run.
|
|
88
|
+
// `conversationId` is a DEPENDENCY (a dialog switch must re-fetch), so that
|
|
89
|
+
// path is reachable in normal use: before this, "new chat" or archiving the
|
|
90
|
+
// open thread mid-fetch left the flag stuck true forever and the panel
|
|
91
|
+
// wedged on a message skeleton.
|
|
92
|
+
if (!active || !conversationId) return () => setIsHydratingHistory(false);
|
|
81
93
|
const key = `${source}:${conversationId}`;
|
|
82
|
-
if (hydratedKeyRef.current === key) return
|
|
94
|
+
if (hydratedKeyRef.current === key) return () => setIsHydratingHistory(false);
|
|
83
95
|
hydratedKeyRef.current = key;
|
|
84
96
|
let cancelled = false;
|
|
97
|
+
let completed = false;
|
|
98
|
+
const runId = ++runIdRef.current;
|
|
99
|
+
const isCurrentRun = () => runIdRef.current === runId;
|
|
85
100
|
setIsHydratingHistory(true);
|
|
86
101
|
// Self-contained: try/catch/finally below, and every state write is gated
|
|
87
102
|
// on `cancelled` so a superseded effect can't hydrate the new conversation.
|
|
@@ -90,13 +105,19 @@ export function useChatHistoryHydration({
|
|
|
90
105
|
const res = await embedAuthedFetch(`${historyUrl}?conversationId=${encodeURIComponent(conversationId)}`, {
|
|
91
106
|
method: 'GET',
|
|
92
107
|
});
|
|
93
|
-
if (!res.ok)
|
|
108
|
+
if (!res.ok) {
|
|
109
|
+
// Releases the once-guard exactly like the catch below — this path
|
|
110
|
+
// returns BEFORE it, and a transient 429/5xx must not mark the
|
|
111
|
+
// conversation hydrated for the rest of the mount. `isCurrentRun` so
|
|
112
|
+
// a superseded run can't release a key its replacement re-claimed
|
|
113
|
+
// (same key string, different run).
|
|
114
|
+
if (isCurrentRun() && hydratedKeyRef.current === key) hydratedKeyRef.current = null;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
94
117
|
// `.json()` is `any` — this is untrusted wire, so narrow it rather than
|
|
95
118
|
// asserting the shape we hope for.
|
|
96
119
|
const payload: unknown = await res.json().catch(() => null);
|
|
97
|
-
|
|
98
|
-
const envelope = isRecord(payload) ? payload.data : undefined;
|
|
99
|
-
const body = envelope ?? payload;
|
|
120
|
+
const body = unwrapEnvelope(payload);
|
|
100
121
|
const rawRows = isRecord(body) ? body.messages : undefined;
|
|
101
122
|
// Non-object rows are DROPPED, not carried into the loop below. The
|
|
102
123
|
// loop reads `row.role` unguarded, so a single `null` row threw a
|
|
@@ -104,7 +125,15 @@ export function useChatHistoryHydration({
|
|
|
104
125
|
// hydration wholesale and rendering an EMPTY conversation on refresh.
|
|
105
126
|
// Skipping the bad row keeps every good one.
|
|
106
127
|
const rows: Array<Record<string, unknown>> = Array.isArray(rawRows) ? rawRows.filter(isRecord) : [];
|
|
107
|
-
if (cancelled
|
|
128
|
+
if (cancelled) return;
|
|
129
|
+
if (rows.length === 0) {
|
|
130
|
+
// `found === false` = unknown or foreign id → the stored id is dead.
|
|
131
|
+
// An owned-but-empty thread (`found === true`, or a server that
|
|
132
|
+
// predates the flag) keeps it.
|
|
133
|
+
const found = isRecord(body) ? body.found : undefined;
|
|
134
|
+
if (found === false) onOrphanedConversation?.(conversationId);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
108
137
|
const hydrated: Message[] = [];
|
|
109
138
|
// Per-send "Sources used" chips, restored from the persisted audit
|
|
110
139
|
// copy the history route projects as `sources` on assistant rows —
|
|
@@ -139,16 +168,30 @@ export function useChatHistoryHydration({
|
|
|
139
168
|
bumpMetaTick();
|
|
140
169
|
} catch {
|
|
141
170
|
// Fetch failed — start empty; the server still owns history (above).
|
|
171
|
+
// Release the once-guard so re-selecting the conversation retries
|
|
172
|
+
// (a transient 429/5xx must not mark it hydrated for the mount).
|
|
173
|
+
if (isCurrentRun() && hydratedKeyRef.current === key) hydratedKeyRef.current = null;
|
|
142
174
|
} finally {
|
|
143
|
-
|
|
175
|
+
completed = true;
|
|
176
|
+
// Only the latest run owns the flag (React no-ops updates after unmount).
|
|
177
|
+
if (isCurrentRun()) setIsHydratingHistory(false);
|
|
144
178
|
}
|
|
145
179
|
})();
|
|
146
180
|
return () => {
|
|
147
181
|
cancelled = true;
|
|
182
|
+
// An INCOMPLETE run must hand the key back, or a re-run for the SAME key
|
|
183
|
+
// (a mode toggle flipping `active`, a StrictMode remount) early-returns
|
|
184
|
+
// on the guard, drops the in-flight response and never refetches — the
|
|
185
|
+
// thread would render empty for the rest of the mount while the server
|
|
186
|
+
// keeps answering from history the user cannot see.
|
|
187
|
+
if (!completed && isCurrentRun() && hydratedKeyRef.current === key) hydratedKeyRef.current = null;
|
|
188
|
+
// Release the skeleton unless a newer run has already claimed it (that
|
|
189
|
+
// run raises the flag itself and owns clearing it).
|
|
190
|
+
if (isCurrentRun()) setIsHydratingHistory(false);
|
|
148
191
|
};
|
|
149
|
-
// `
|
|
150
|
-
//
|
|
151
|
-
}, [active, source, historyUrl, hydrateMessages, bumpMetaTick,
|
|
192
|
+
// `sendCountRef` is a ref: a stable identity, so listing it costs nothing;
|
|
193
|
+
// `conversationId` is the real re-run trigger (dialog switch).
|
|
194
|
+
}, [active, source, historyUrl, conversationId, hydrateMessages, bumpMetaTick, onOrphanedConversation, sendCountRef]);
|
|
152
195
|
|
|
153
196
|
return { isHydratingHistory, hydratedKeyRef };
|
|
154
197
|
}
|