@aintela/chat 0.2.59 → 0.3.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/README.md +77 -0
- package/dist/{ClientMessage-EKgfuTp8.js → ClientMessage-DUby3KyC.js} +16 -22
- package/dist/{ClientMessage-EKgfuTp8.js.map → ClientMessage-DUby3KyC.js.map} +1 -1
- package/dist/Memory-CjrYSkzB.js +47 -0
- package/dist/Memory-CjrYSkzB.js.map +1 -0
- package/dist/atMentions-CnHuJKhX.js +959 -0
- package/dist/atMentions-CnHuJKhX.js.map +1 -0
- package/dist/components.js +10161 -11344
- package/dist/components.js.map +1 -1
- package/dist/environmentUtils-VZNTCzEE.js +88 -0
- package/dist/environmentUtils-VZNTCzEE.js.map +1 -0
- package/dist/hooks.js +4 -5
- package/dist/{httpArtifactService-CpbRpTHb.js → httpArtifactService-Ba9xFy1E.js} +537 -646
- package/dist/httpArtifactService-Ba9xFy1E.js.map +1 -0
- package/dist/{httpSessionService-BEQMIKfv.js → httpSessionService-DXlT2vxT.js} +34 -24
- package/dist/httpSessionService-DXlT2vxT.js.map +1 -0
- package/dist/index.js +242 -243
- package/dist/models.js +48 -51
- package/dist/models.js.map +1 -1
- package/dist/serializer-D2W42bdT.js +1730 -0
- package/dist/serializer-D2W42bdT.js.map +1 -0
- package/dist/services.js +2 -2
- package/dist/src/components/AiChat/AiChatContext.d.ts +0 -3
- package/dist/src/components/AiChat/AiChatProvider.agent.test.d.ts +1 -0
- package/dist/src/components/AiChat/AiChatProvider.d.ts +2 -2
- package/dist/src/components/AiChat/AiChatTypes.d.ts +45 -27
- package/dist/src/components/AiChat/ChatPane/ChatPane.test.d.ts +1 -0
- package/dist/src/components/AiChat/ChatPane/MessageAgent.d.ts +0 -1
- package/dist/src/components/AiChat/ChatPane/MessagePart.d.ts +5 -3
- package/dist/src/components/AiChat/ChatPane/MessagePart.test.d.ts +1 -0
- package/dist/src/components/AiChat/ChatPane/friendlyToolConfig.test.d.ts +1 -0
- package/dist/src/components/AiChat/ChatPane/messageAgentThoughts.test.d.ts +1 -0
- package/dist/src/components/AiChat/ChatPane/parts/ThoughtRun.d.ts +28 -0
- package/dist/src/components/AiChat/ChatPane/parts/ThoughtRunContext.d.ts +18 -0
- package/dist/src/components/AiChat/ChatPane/parts/index.d.ts +5 -1
- package/dist/src/components/AiChat/ChatPane/parts/thoughtRun.test.d.ts +1 -0
- package/dist/src/components/AiChat/ChatPane/parts/uiToolDispatcher.test.d.ts +1 -0
- package/dist/src/components/AiChat/ChatPane/parts/uiToolRegistry.test.d.ts +1 -0
- package/dist/src/components/AiChat/aiChatEngine.d.ts +24 -5
- package/dist/src/components/AiChat/index.d.ts +1 -3
- package/dist/src/components/AiChat/sessionStateManagerService.bind.test.d.ts +1 -0
- package/dist/src/components/AiChat/sessionStateManagerService.d.ts +22 -10
- package/dist/src/components/AiChat/useAgentEngine.d.ts +69 -0
- package/dist/src/components/AiChat/useAgentEngine.test.d.ts +1 -0
- package/dist/src/components/index.d.ts +4 -7
- package/dist/src/components/v2/AiChatFloating.d.ts +3 -0
- package/dist/src/components/v2/PromptV2.d.ts +21 -6
- package/dist/src/components/v2/PromptV2.test.d.ts +1 -0
- package/dist/src/components/v2/icons.d.ts +1 -0
- package/dist/src/components/v2/index.d.ts +25 -25
- package/dist/src/hooks/index.d.ts +1 -1
- package/dist/src/hooks/useContainerWidth.d.ts +0 -1
- package/dist/src/models/ArtifactData.d.ts +0 -7
- package/dist/src/models/ChatSession.d.ts +0 -32
- package/dist/src/models/ClientMessage.d.ts +0 -4
- package/dist/src/models/ServerEvent.d.ts +0 -36
- package/dist/src/models/enums.d.ts +0 -1
- package/dist/src/models/index.d.ts +1 -2
- package/dist/src/models/interactionPartUtils.test.d.ts +1 -0
- package/dist/src/models/semanticKernelModel/sanitizeJsonString.test.d.ts +0 -0
- package/dist/src/models/serverEventDecode.test.d.ts +0 -0
- package/dist/src/services/WebSocketConnection/webSocketConnectionV2.reconnect.test.d.ts +0 -0
- package/dist/src/services/interactionService.d.ts +11 -0
- package/dist/src/services/interactionServiceGrouping.test.d.ts +1 -0
- package/dist/src/services/servers/AgentGatewayService.d.ts +25 -18
- package/dist/src/services/servers/AgentGatewayWSAsync.d.ts +0 -1
- package/dist/src/services/servers/agentGatewayAgentContext.test.d.ts +1 -0
- package/dist/src/services/storageService.d.ts +34 -59
- package/dist/src/services/storageService.test.d.ts +1 -0
- package/dist/src/utils/index.d.ts +2 -6
- package/dist/src/utils/urlParser.d.ts +0 -1
- package/dist/src/utils/urlParser.test.d.ts +1 -0
- package/dist/tests/fakes/fakeChatServices.d.ts +42 -0
- package/dist/tests/fakes/fakeRawWebSocket.d.ts +51 -0
- package/dist/tests/fakes/fakeStorage.d.ts +7 -0
- package/dist/tests/fakes/makeGateway.d.ts +24 -1
- package/dist/{useChatSessions-BQP7DhY1.js → useChatSessions-1AAvAdPW.js} +2 -2
- package/dist/{useChatSessions-BQP7DhY1.js.map → useChatSessions-1AAvAdPW.js.map} +1 -1
- package/dist/useContainerWidth-B40_i-NW.js +295 -0
- package/dist/{useContainerWidth-B3t1ZTlo.js.map → useContainerWidth-B40_i-NW.js.map} +1 -1
- package/dist/utils.js +340 -57
- package/dist/utils.js.map +1 -1
- package/package.json +1 -1
- package/dist/Memory-DjLZqgbF.js +0 -84
- package/dist/Memory-DjLZqgbF.js.map +0 -1
- package/dist/atMentions-C0dza8DD.js +0 -1000
- package/dist/atMentions-C0dza8DD.js.map +0 -1
- package/dist/auth-lluJZyQO.js +0 -524
- package/dist/auth-lluJZyQO.js.map +0 -1
- package/dist/environmentUtils-CUVZ6Dq1.js +0 -478
- package/dist/environmentUtils-CUVZ6Dq1.js.map +0 -1
- package/dist/httpArtifactService-CpbRpTHb.js.map +0 -1
- package/dist/httpSessionService-BEQMIKfv.js.map +0 -1
- package/dist/serializer-BXSH9aYQ.js +0 -1360
- package/dist/serializer-BXSH9aYQ.js.map +0 -1
- package/dist/src/components/AiChat/AiChatFloating.d.ts +0 -3
- package/dist/src/components/AiChat/ChatPane/LastPrompts.d.ts +0 -9
- package/dist/src/components/AiChat/ChatPane/Prompt.d.ts +0 -9
- package/dist/src/components/AiChat/ChatPane/SubAgentBox.d.ts +0 -9
- package/dist/src/components/AiChat/ChatPane/TaskList.d.ts +0 -6
- package/dist/src/components/AiChat/useLiveSession.d.ts +0 -52
- package/dist/src/components/v2/AiChatFloatingV2.d.ts +0 -3
- package/dist/src/utils/jsonDetector.d.ts +0 -50
- package/dist/src/utils/jsonUtils.d.ts +0 -1
- package/dist/src/utils/materialIconsSvg.d.ts +0 -51
- package/dist/src/utils/objectUtils.d.ts +0 -31
- package/dist/src/utils/parseArtifact.d.ts +0 -3
- package/dist/src/utils/uriUtils.d.ts +0 -39
- package/dist/useContainerWidth-B3t1ZTlo.js +0 -309
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ServerEvent, ToolEventDetails } from '../../models/ServerEvent';
|
|
2
2
|
import { User, AgentContext } from '../../models/contexts';
|
|
3
|
+
import { Customer } from '../../models/Customer';
|
|
3
4
|
import { ClientMessage } from '../../models/ClientMessage';
|
|
4
5
|
import { Interaction, MergeResult } from '../../models/Interaction';
|
|
5
6
|
import { EventBusService, FirstTokenEventDetails } from '../eventBusService';
|
|
@@ -66,29 +67,36 @@ export declare abstract class AgentGatewayService {
|
|
|
66
67
|
*/
|
|
67
68
|
answerHumanTool(toolCallId: string, answer: string): 'sent' | 'queued';
|
|
68
69
|
constructor(user: User, eventBusService: EventBusService, artifactService: IArtifactService, baseUrl: string, config: AgentContext, sessionStore: AiChatStore, notificationPort: INotificationPort, storageService: IStorageService, sessionId?: string, runMode?: RunMode);
|
|
70
|
+
/**
|
|
71
|
+
* The agent this gateway speaks to — the ONE truth for the conversation.
|
|
72
|
+
* `sendMessageInternal` stamps every outbound frame's `AgentId` from it,
|
|
73
|
+
* and the session manager binds/rebinds against it. Fixed at construction;
|
|
74
|
+
* see {@link forceAgentContext} for the single exception (issue #59).
|
|
75
|
+
*/
|
|
69
76
|
getAgentContext(): AgentContext;
|
|
70
77
|
getModel(): string | undefined;
|
|
71
78
|
setModel(modelId: string): void;
|
|
72
79
|
/**
|
|
73
|
-
* Live update for the
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
80
|
+
* Live update for the ordinary, non-identity slice of the context — the
|
|
81
|
+
* dataset/customer the same agent works over. No "force" needed: swapping
|
|
82
|
+
* datasets mid-conversation is routine and changes nothing about who is
|
|
83
|
+
* answering.
|
|
84
|
+
*/
|
|
85
|
+
setCustomer(customer: Customer): void;
|
|
86
|
+
/**
|
|
87
|
+
* Replace the AGENT mid-conversation. The escape hatch for an agent picker,
|
|
88
|
+
* and nothing else: the session already holds another agent's history, and
|
|
89
|
+
* the server stamps `Session.AgentId` on the first turn only — so the
|
|
90
|
+
* conversation keeps reporting the agent it STARTED as, however many times
|
|
91
|
+
* this is called. Prefer a new engine (new key, see `engineKeyFor`) per
|
|
92
|
+
* agent.
|
|
83
93
|
*
|
|
84
|
-
* Callers
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
* separately by `setModel` and shouldn't get clobbered by an
|
|
89
|
-
* agent-only change.
|
|
94
|
+
* Callers pass the FULL replacement context (the same shape the gateway was
|
|
95
|
+
* constructed with). The `model` slice is preserved when the incoming
|
|
96
|
+
* context omits it — the model is owned separately by {@link setModel} and
|
|
97
|
+
* must not be clobbered by an agent-only change.
|
|
90
98
|
*/
|
|
91
|
-
|
|
99
|
+
forceAgentContext(config: AgentContext): void;
|
|
92
100
|
getSessionId(): string | undefined;
|
|
93
101
|
getErrorEvent(errorMessage: string): {
|
|
94
102
|
interaction_id: string | null;
|
|
@@ -164,7 +172,6 @@ export declare abstract class AgentGatewayService {
|
|
|
164
172
|
abstract sendMessageInternal(message: ClientMessage, options?: GatewaySendMessageOptions): Promise<SendMessageResponse>;
|
|
165
173
|
abstract isSuspended(): boolean;
|
|
166
174
|
abstract suspend(): Promise<boolean>;
|
|
167
|
-
abstract reset(user: User, config?: AgentContext): void;
|
|
168
175
|
check(): Promise<boolean>;
|
|
169
176
|
startAndForget(): void;
|
|
170
177
|
forceReceiveMessage(serverEvent: ServerEvent): void;
|
|
@@ -15,7 +15,6 @@ import { IStorageService } from '../storageService';
|
|
|
15
15
|
export type Reader = (response: AxiosResponse, wasSuspended: boolean, onFirstRead?: () => void) => void;
|
|
16
16
|
export declare class AgentGatewayWSAsync extends AgentGatewayService {
|
|
17
17
|
suspendState: boolean;
|
|
18
|
-
reset(_user: User, _config?: AgentContext): void;
|
|
19
18
|
startStream(_sendStartMessage?: boolean): Promise<StartStreamResponse>;
|
|
20
19
|
isSuspended(): boolean;
|
|
21
20
|
protected wsService: IWebSocketConnection;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,73 +1,48 @@
|
|
|
1
|
-
import { ArtifactData, Section } from '../models/ArtifactData';
|
|
2
1
|
import { Prompt } from '../models/Prompt';
|
|
2
|
+
/**
|
|
3
|
+
* The prompt-history port. Three methods, all of them live:
|
|
4
|
+
* `storePrompt` on every sent turn, `getPrompts` for the two LastPrompts
|
|
5
|
+
* surfaces, `clearAllPrompts` for the clear control.
|
|
6
|
+
*
|
|
7
|
+
* Keep it this small. It is injected into the gateway, so anything added here
|
|
8
|
+
* has to be implemented by every test fake — and an 18-method interface that
|
|
9
|
+
* fakes could not honestly satisfy is precisely how `sendMessage` came to throw
|
|
10
|
+
* a TypeError in every gateway test without anyone noticing.
|
|
11
|
+
*/
|
|
3
12
|
export interface IStorageService {
|
|
4
|
-
initializeStorage(): void;
|
|
5
|
-
getSections(): Section[];
|
|
6
|
-
getArtifacts(): ArtifactData[];
|
|
7
|
-
createSection(name: string, iconType?: 'dashboard' | 'chart' | 'folder'): Section;
|
|
8
|
-
updateSection(sectionId: string, updates: Partial<Section>): void;
|
|
9
|
-
deleteSection(sectionId: string): void;
|
|
10
|
-
storeArtifact(artifact: ArtifactData): void;
|
|
11
|
-
moveArtifact(artifactId: string, newSectionId: string): void;
|
|
12
|
-
deleteArtifact(artifactId: string): void;
|
|
13
|
-
updateArtifact(artifactId: string, updates: Partial<ArtifactData>): void;
|
|
14
|
-
getArtifactsBySection(sectionId: string): ArtifactData[];
|
|
15
13
|
getPrompts(): Prompt[];
|
|
16
14
|
storePrompt(prompt: Prompt): void;
|
|
17
|
-
deletePrompt(promptId: string): void;
|
|
18
15
|
clearAllPrompts(): void;
|
|
19
|
-
getItem(key: string): any;
|
|
20
|
-
setItem(key: string, value: any): void;
|
|
21
|
-
removeItem(key: string): void;
|
|
22
16
|
}
|
|
17
|
+
/** The only implementation — no consumer has ever supplied its own. */
|
|
23
18
|
export declare class LocalStorageService implements IStorageService {
|
|
24
|
-
getItem(key: string): string | null;
|
|
25
|
-
setItem(key: string, value: any): void;
|
|
26
|
-
removeItem(key: string): void;
|
|
27
|
-
onPromptCreated: (prompt: Prompt) => void;
|
|
28
|
-
initializeStorage(): void;
|
|
29
|
-
getSections(): Section[];
|
|
30
|
-
getArtifacts(): ArtifactData[];
|
|
31
|
-
createSection(name: string, iconType?: 'dashboard' | 'chart' | 'folder'): Section;
|
|
32
|
-
updateSection(sectionId: string, updates: Partial<Section>): void;
|
|
33
|
-
deleteSection(sectionId: string): void;
|
|
34
|
-
storeArtifact(artifact: ArtifactData): void;
|
|
35
|
-
moveArtifact(artifactId: string, newSectionId: string): void;
|
|
36
|
-
deleteArtifact(artifactId: string): void;
|
|
37
|
-
updateArtifact(artifactId: string, updates: Partial<ArtifactData>): void;
|
|
38
|
-
getArtifactsBySection(sectionId: string): ArtifactData[];
|
|
39
19
|
getPrompts(): Prompt[];
|
|
20
|
+
/**
|
|
21
|
+
* Record a sent prompt, most recent first, de-duplicated by text.
|
|
22
|
+
*
|
|
23
|
+
* Asking the same thing again MOVES that entry to the top rather than adding
|
|
24
|
+
* a second copy — the history is a list of distinct things you have asked,
|
|
25
|
+
* and a repeated question spending two of the twelve visible rows costs a
|
|
26
|
+
* suggestion for nothing. The repeat's own `id` and `created` win, because
|
|
27
|
+
* what the list orders by is when you last asked.
|
|
28
|
+
*
|
|
29
|
+
* The dedupe used to look only at `prompts[0]`, and then unshifted anyway:
|
|
30
|
+
* a consecutive repeat overwrote the older copy's id and timestamp AND
|
|
31
|
+
* appended a new row, so the same text appeared twice with the same id.
|
|
32
|
+
*
|
|
33
|
+
* Matching is exact on `promptText` (`PromptUtils.createPrompt` has already
|
|
34
|
+
* trimmed it). Two prompts differing only in case or inner whitespace stay
|
|
35
|
+
* separate entries — that is deliberate, not an oversight: normalising them
|
|
36
|
+
* would mean re-surfacing text the user never typed.
|
|
37
|
+
*/
|
|
40
38
|
storePrompt(prompt: Prompt): void;
|
|
41
|
-
deletePrompt(promptId: string): void;
|
|
42
|
-
clearAllPrompts(): void;
|
|
43
|
-
}
|
|
44
|
-
export declare class MockStorageService implements IStorageService {
|
|
45
|
-
getItem(_key: string): string;
|
|
46
|
-
setItem(_key: string, _value: any): void;
|
|
47
|
-
removeItem(_key: string): void;
|
|
48
|
-
private artifacts;
|
|
49
|
-
private sections;
|
|
50
|
-
private prompts;
|
|
51
|
-
onPromptCreated: (prompt: Prompt) => void;
|
|
52
|
-
setMockArtifacts(artifacts: ArtifactData[]): void;
|
|
53
|
-
setMockSections(sections: Section[]): void;
|
|
54
|
-
setMockPrompts(prompts: Prompt[]): void;
|
|
55
|
-
initializeStorage(): void;
|
|
56
|
-
getSections(): Section[];
|
|
57
|
-
getArtifacts(): ArtifactData[];
|
|
58
|
-
createSection(name: string, iconType?: 'dashboard' | 'chart' | 'folder'): Section;
|
|
59
|
-
updateSection(sectionId: string, updates: Partial<Section>): void;
|
|
60
|
-
deleteSection(sectionId: string): void;
|
|
61
|
-
storeArtifact(artifact: ArtifactData): void;
|
|
62
|
-
moveArtifact(artifactId: string, newSectionId: string): void;
|
|
63
|
-
deleteArtifact(artifactId: string): void;
|
|
64
|
-
updateArtifact(artifactId: string, updates: Partial<ArtifactData>): void;
|
|
65
|
-
getArtifactsBySection(sectionId: string): ArtifactData[];
|
|
66
|
-
getPrompts(): Prompt[];
|
|
67
|
-
storePrompt(prompt: Prompt): void;
|
|
68
|
-
deletePrompt(promptId: string): void;
|
|
69
39
|
clearAllPrompts(): void;
|
|
70
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* A cheap change-signal over the stored prompts, so the LastPrompts surfaces
|
|
43
|
+
* re-render when a freshly sent prompt lands. It is a digest, not state: the
|
|
44
|
+
* count plus the first/last text and the newest timestamp.
|
|
45
|
+
*/
|
|
71
46
|
export declare const usePromptState: (storageService: IStorageService) => {
|
|
72
47
|
promptState: string;
|
|
73
48
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -3,12 +3,8 @@ export { getAgentBaseUrl } from './getAgentBaseUrl';
|
|
|
3
3
|
export { getArtifactsBaseUrl } from './getAgentArtifactsBaseUrl';
|
|
4
4
|
export { getDotNetBaseUrl } from './getDotNetBaseUrl';
|
|
5
5
|
export { getRandomUUID, getEnvVar } from './envUtils';
|
|
6
|
-
export {
|
|
7
|
-
export {
|
|
8
|
-
export { parseKnownNumbers, chunkArray, splitBigLinesWithSpaces } from './stringUtils';
|
|
9
|
-
export { parseArtifactFromJson } from './parseArtifact';
|
|
10
|
-
export { decodeBase64, encodeBase64, decodeUriFromPython, isBase64Encoded } from './jsonDetector';
|
|
11
|
-
export { isUriEncoded, decodeUri, encodeUri, isValidUri, parseUriParams } from './uriUtils';
|
|
6
|
+
export { extractLinkAction } from './urlParser';
|
|
7
|
+
export { chunkArray, splitBigLinesWithSpaces } from './stringUtils';
|
|
12
8
|
export { startsWithInteractionId, extractInteractionId, isValidInteractionId, } from './interactionIdChecker';
|
|
13
9
|
export { setEbiContextSessionId, setEbiContextData } from './sessionWindowParameters';
|
|
14
10
|
export { default as materialIcons, getIconByName, searchIcons, iconCategories, } from './materialIconsList';
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
export declare const parseAndValidateArtifactUrl: (url: string) => string | null;
|
|
2
1
|
export type LinkAction = 'Export' | 'Question' | 'OpenDashboard' | 'URL';
|
|
3
2
|
export declare const extractLinkAction: (link: string, sessionId: string, content: string | null) => {
|
|
4
3
|
action: LinkAction;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { AiChatContextState } from '../../src/components/AiChat/AiChatContext';
|
|
2
|
+
import { AiChatStore } from '../../src/components/AiChat/stateConfiguration';
|
|
3
|
+
import { EventBusService } from '../../src/services/eventBusService';
|
|
4
|
+
import { SendMessageOptions } from '../../src/components/AiChat/AiChatTypes';
|
|
5
|
+
import { MakeGatewayOptions, FakeNotificationCapture } from './makeGateway';
|
|
6
|
+
import { FakeStorage } from './fakeStorage';
|
|
7
|
+
import { FakeWebSocketConnection } from './fakeWebSocket';
|
|
8
|
+
/** One turn the component asked to send, as the UI phrased it. */
|
|
9
|
+
export interface RecordedSend {
|
|
10
|
+
text: string;
|
|
11
|
+
options?: SendMessageOptions;
|
|
12
|
+
}
|
|
13
|
+
export interface FakeChatServices {
|
|
14
|
+
/** Hand this to `<AiChatServiceContext.Provider value={…}>`. */
|
|
15
|
+
context: AiChatContextState;
|
|
16
|
+
/** The same object — mutate a field then re-render to test a context switch. */
|
|
17
|
+
store: AiChatStore;
|
|
18
|
+
bus: EventBusService;
|
|
19
|
+
ws: FakeWebSocketConnection;
|
|
20
|
+
storage: FakeStorage;
|
|
21
|
+
notifications: FakeNotificationCapture;
|
|
22
|
+
/** Everything the component passed to `sendMessage`, in order. */
|
|
23
|
+
sent: RecordedSend[];
|
|
24
|
+
}
|
|
25
|
+
export interface FakeChatServicesOptions extends MakeGatewayOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Context fields to replace. The `show*` flags, `partRenderers`, `uiTools`
|
|
28
|
+
* and the callbacks are the interesting ones; passing a service here
|
|
29
|
+
* overrides the real one built below.
|
|
30
|
+
*/
|
|
31
|
+
overrides?: Partial<AiChatContextState>;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Build a complete chat-services context for a component test.
|
|
35
|
+
*
|
|
36
|
+
* `sendMessage` records rather than sends — the components under test are being
|
|
37
|
+
* asked "did you decide to send, and with what?", which is a different question
|
|
38
|
+
* from "does the gateway put it on the wire" (that one is
|
|
39
|
+
* `agentGatewayAgentContext.test.ts`). Tests that want the real path can
|
|
40
|
+
* override `sendMessage` with `services.context.agentGatewayService`'s.
|
|
41
|
+
*/
|
|
42
|
+
export declare function fakeChatServices(options?: FakeChatServicesOptions): FakeChatServices;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** One fake socket instance — one `new WebSocket(url)` in the code under test. */
|
|
2
|
+
export declare class FakeRawWebSocket {
|
|
3
|
+
static readonly CONNECTING = 0;
|
|
4
|
+
static readonly OPEN = 1;
|
|
5
|
+
static readonly CLOSING = 2;
|
|
6
|
+
static readonly CLOSED = 3;
|
|
7
|
+
readonly url: string;
|
|
8
|
+
readyState: number;
|
|
9
|
+
/** Every frame the production code sent through this socket, parsed. */
|
|
10
|
+
readonly sent: any[];
|
|
11
|
+
/** `close(code, reason)` calls made BY the production code (not server-driven). */
|
|
12
|
+
readonly closedByClient: {
|
|
13
|
+
code?: number;
|
|
14
|
+
reason?: string;
|
|
15
|
+
}[];
|
|
16
|
+
onopen: ((event?: unknown) => void) | null;
|
|
17
|
+
onmessage: ((event: {
|
|
18
|
+
data: string;
|
|
19
|
+
}) => void) | null;
|
|
20
|
+
onerror: ((event?: unknown) => void) | null;
|
|
21
|
+
onclose: ((event: {
|
|
22
|
+
code: number;
|
|
23
|
+
reason: string;
|
|
24
|
+
}) => void) | null;
|
|
25
|
+
constructor(url: string);
|
|
26
|
+
send(data: string): void;
|
|
27
|
+
close(code?: number, reason?: string): void;
|
|
28
|
+
/** Complete the handshake. */
|
|
29
|
+
open(): void;
|
|
30
|
+
/** Deliver a raw frame (a JSON string, as the wire does). */
|
|
31
|
+
message(data: unknown): void;
|
|
32
|
+
/** The SERVER (or the network) closed us — the path that decides reconnect vs handoff. */
|
|
33
|
+
serverClose(code: number, reason?: string): void;
|
|
34
|
+
error(): void;
|
|
35
|
+
/** The query value the dial carried, or undefined when absent. */
|
|
36
|
+
param(name: string): string | undefined;
|
|
37
|
+
}
|
|
38
|
+
export interface FakeWebSocketHandle {
|
|
39
|
+
/** Every socket constructed since install, in order. */
|
|
40
|
+
readonly instances: FakeRawWebSocket[];
|
|
41
|
+
/** The most recently constructed socket — what the code under test is holding. */
|
|
42
|
+
readonly last: FakeRawWebSocket;
|
|
43
|
+
/** Dial URLs in order, handy for asserting a whole reconnect sequence at once. */
|
|
44
|
+
readonly urls: string[];
|
|
45
|
+
restore(): void;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Replace `globalThis.WebSocket` with the fake for the duration of a test.
|
|
49
|
+
* Returns a handle over every socket the code under test constructs.
|
|
50
|
+
*/
|
|
51
|
+
export declare function installFakeWebSocket(): FakeWebSocketHandle;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { IStorageService } from '../../src/services/storageService';
|
|
2
|
+
import { Prompt } from '../../src/models/Prompt';
|
|
3
|
+
export interface FakeStorage extends IStorageService {
|
|
4
|
+
/** Everything `storePrompt` received, oldest first. */
|
|
5
|
+
readonly stored: Prompt[];
|
|
6
|
+
}
|
|
7
|
+
export declare function fakeStorageService(): FakeStorage;
|
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import { AiChatStore } from '../../src/components/AiChat/stateConfiguration';
|
|
2
2
|
import { EventBusService } from '../../src/services/eventBusService';
|
|
3
3
|
import { AgentGatewayWSAsync } from '../../src/services/servers/AgentGatewayWSAsync';
|
|
4
|
+
import { AgentContext } from '../../src/models/contexts';
|
|
4
5
|
import { BasicNotification } from '../../src/models/Notification';
|
|
5
6
|
import { INotificationPort } from '../../src/interfaces/INotificationPort';
|
|
7
|
+
import { IArtifactService } from '../../src/services/interfaces/artifactService';
|
|
8
|
+
import { ISessionService } from '../../src/services/servers/sessionService/ISessionService';
|
|
6
9
|
import { FakeWebSocketConnection } from './fakeWebSocket';
|
|
10
|
+
import { IStorageService } from '../../src/services/storageService';
|
|
11
|
+
declare function fakeArtifactService(): IArtifactService;
|
|
7
12
|
export interface FakeNotificationCapture extends INotificationPort {
|
|
8
13
|
/** Every notification the gateway pushed during the test. */
|
|
9
14
|
readonly notifications: BasicNotification[];
|
|
10
15
|
}
|
|
16
|
+
declare function fakeSessionService(): ISessionService;
|
|
11
17
|
export interface MakeGatewayHandle {
|
|
12
18
|
gateway: AgentGatewayWSAsync;
|
|
13
19
|
ws: FakeWebSocketConnection;
|
|
@@ -15,10 +21,27 @@ export interface MakeGatewayHandle {
|
|
|
15
21
|
bus: EventBusService;
|
|
16
22
|
sessionStore: AiChatStore;
|
|
17
23
|
}
|
|
24
|
+
export interface MakeGatewayOptions {
|
|
25
|
+
/**
|
|
26
|
+
* The agent the gateway is constructed with. Defaults to
|
|
27
|
+
* `{ id: 'agent-1', name: 'TestAgent', model: 'gpt-test' }`. Tests that care
|
|
28
|
+
* about agent OWNERSHIP (issue #59) pass their own so the id under
|
|
29
|
+
* assertion is unmistakably the one the gateway was built with.
|
|
30
|
+
*/
|
|
31
|
+
agentContext?: AgentContext;
|
|
32
|
+
/** Session service the store (and any manager wired to it) talks to. */
|
|
33
|
+
sessionService?: ISessionService;
|
|
34
|
+
/**
|
|
35
|
+
* Prompt storage. Pass a `fakeStorageService()` you hold a reference to when
|
|
36
|
+
* the test asserts on what `sendMessage` recorded.
|
|
37
|
+
*/
|
|
38
|
+
storageService?: IStorageService;
|
|
39
|
+
}
|
|
18
40
|
/**
|
|
19
41
|
* Build a fully-wired AgentGatewayWSAsync for tests. The `ws` field is
|
|
20
42
|
* the fake socket — call `await ws.deliver(serverEvent)` to drive the
|
|
21
43
|
* inbound stream. The `notifications` field is the captured array of
|
|
22
44
|
* everything pushed to the notification port during the test.
|
|
23
45
|
*/
|
|
24
|
-
export declare function makeGateway(): MakeGatewayHandle;
|
|
46
|
+
export declare function makeGateway(options?: MakeGatewayOptions): MakeGatewayHandle;
|
|
47
|
+
export { fakeArtifactService, fakeSessionService };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var L = Object.defineProperty;
|
|
2
2
|
var d = (e, t) => L(e, "name", { value: t, configurable: !0 });
|
|
3
3
|
import { useMemo as h, useState as v, useCallback as g, useEffect as C } from "react";
|
|
4
|
-
import { H } from "./httpSessionService-
|
|
4
|
+
import { H } from "./httpSessionService-DXlT2vxT.js";
|
|
5
5
|
const w = 6e4, y = 60 * w, l = 24 * y;
|
|
6
6
|
function k(e) {
|
|
7
7
|
if (!e) return;
|
|
@@ -104,4 +104,4 @@ d(Y, "useChatSessions");
|
|
|
104
104
|
export {
|
|
105
105
|
Y as u
|
|
106
106
|
};
|
|
107
|
-
//# sourceMappingURL=useChatSessions-
|
|
107
|
+
//# sourceMappingURL=useChatSessions-1AAvAdPW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useChatSessions-BQP7DhY1.js","sources":["../src/hooks/useChatSessions.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from 'react';\nimport type { ChatSession } from '@lib/models/ChatSession';\nimport type { ISessionService } from '@lib/services/servers/sessionService/ISessionService';\nimport { HttpSessionService } from '../services';\n\n/**\n * One row in a session-picker UI. `raw` is the original ChatSession the\n * server returned; everything else is a derived label the hook computed\n * (and the host's `decorate` callback may have overridden).\n */\nexport interface ChatSessionListItem {\n id: string;\n title: string;\n snippet?: string;\n /** Compact relative-time label (\"now\", \"5m\", \"2h\", \"Mar 14\"). */\n timeLabel?: string;\n /** Optional per-row tag — host-supplied via the `decorate` callback. */\n kind?: string;\n updatedAt?: Date;\n raw: ChatSession;\n}\n\n/**\n * Sessions bucketed by recency. The order of `label` reflects display\n * order top-down (\"Today\" first, \"Older\" last).\n */\nexport interface ChatSessionGroup {\n label: string;\n items: ChatSessionListItem[];\n}\n\nexport interface UseChatSessionsOptions {\n sessionService?: ISessionService;\n /**\n * If provided, the live (current) session is merged into the list —\n * replacing an existing entry by id, or prepended if not yet on the\n * server. Lets a \"New chat\" row appear instantly without waiting for\n * the server roundtrip.\n */\n liveSession?: ChatSession | null;\n\n accessToken: string,\n serverBaseUrl: string,\n /**\n * Per-row override hook. Whatever fields you return are merged on top\n * of the hook's computed item — typical use is adding a `kind` tag for\n * application-specific session types (`'chat' | 'composer' | ...`) the\n * library doesn't know about.\n */\n decorate?: (session: ChatSession) => Partial<ChatSessionListItem>;\n}\n\nexport interface UseChatSessionsResult {\n /** Flat list (live session merged in, server order preserved). */\n sessions: ChatSession[];\n /** Same data bucketed by recency. */\n groups: ChatSessionGroup[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n /** Optimistic rename — patches local state immediately, rolls back on failure. */\n rename: (id: string, title: string) => Promise<void>;\n /** Optimistic remove — drops from local state immediately, rolls back on failure. */\n remove: (id: string) => Promise<void>;\n}\n\nconst MINUTE_MS = 60_000;\nconst HOUR_MS = 60 * MINUTE_MS;\nconst DAY_MS = 24 * HOUR_MS;\n\nfunction toDate(value: Date | string | undefined | null): Date | undefined {\n if (!value) return undefined;\n if (value instanceof Date) return value;\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? undefined : d;\n}\n\nfunction formatTimeLabel(date: Date | undefined): string {\n if (!date) return '';\n const diff = Date.now() - date.getTime();\n if (diff < MINUTE_MS) return 'now';\n if (diff < HOUR_MS) return `${Math.floor(diff / MINUTE_MS)}m`;\n if (diff < DAY_MS) return `${Math.floor(diff / HOUR_MS)}h`;\n if (diff < 7 * DAY_MS) return `${Math.floor(diff / DAY_MS)}d`;\n return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });\n}\n\nfunction startOfToday(): Date {\n const d = new Date();\n d.setHours(0, 0, 0, 0);\n return d;\n}\n\nfunction groupByTime(items: ChatSessionListItem[]): ChatSessionGroup[] {\n const today = startOfToday();\n const yesterday = new Date(today.getTime() - DAY_MS);\n const weekAgo = new Date(today.getTime() - 7 * DAY_MS);\n const monthAgo = new Date(today.getTime() - 30 * DAY_MS);\n\n // Insertion-ordered map preserves the bucket display order.\n const buckets: Array<[string, ChatSessionListItem[]]> = [\n ['Today', []],\n ['Yesterday', []],\n ['This Week', []],\n ['This Month', []],\n ['Older', []],\n ];\n\n for (const item of items) {\n const u = item.updatedAt;\n if (!u) { buckets[4][1].push(item); continue; }\n if (u >= today) buckets[0][1].push(item);\n else if (u >= yesterday) buckets[1][1].push(item);\n else if (u >= weekAgo) buckets[2][1].push(item);\n else if (u >= monthAgo) buckets[3][1].push(item);\n else buckets[4][1].push(item);\n }\n\n return buckets\n .filter(([, list]) => list.length > 0)\n .map(([label, list]) => ({ label, items: list }));\n}\n\nfunction buildItem(\n session: ChatSession,\n decorate?: (s: ChatSession) => Partial<ChatSessionListItem>,\n): ChatSessionListItem {\n const updatedAt = toDate(session.updatedAt) ?? toDate(session.created);\n const base: ChatSessionListItem = {\n id: session.id ?? session.browserScopeId ?? '',\n title: session.overview || session.userDescription || '(untitled chat)',\n snippet: session.lastQuestion ?? undefined,\n timeLabel: formatTimeLabel(updatedAt),\n kind: session.agentType as string | undefined,\n updatedAt,\n raw: session,\n };\n return { ...base, ...(decorate?.(session) ?? {}) };\n}\n\n/**\n * Fetch + organise the user's chat sessions for a picker UI. Backend-agnostic\n * — the host injects an `ISessionService` so the same hook drives an HTTP\n * client, an in-memory fake, or whatever else.\n *\n * Replaces the duplicated `useEffect(async () => sessionService.getAllSessions())`\n * + grouping logic that lived in DataExplorerViewV2 and MobileSessionsList,\n * and consolidates the optimistic rename/delete pattern.\n */\nexport function useChatSessions(opts: UseChatSessionsOptions): UseChatSessionsResult {\n\n const defaultSessionService = useMemo(() => {\n return new HttpSessionService(opts.serverBaseUrl, opts.accessToken);\n }, [opts.accessToken, opts.serverBaseUrl]);\n\n const { sessionService, liveSession, decorate } = {\n sessionService: defaultSessionService,\n liveSession: opts.liveSession,\n decorate: opts.decorate\n };\n const [sessions, setSessions] = useState<ChatSession[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n\n const refresh = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const list = await sessionService.getAllSessions();\n setSessions(list);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [sessionService]);\n\n useEffect(() => { void refresh(); }, [refresh]);\n\n const merged = useMemo(() => {\n if (!liveSession?.id) return sessions;\n const idx = sessions.findIndex(s => s.id === liveSession.id);\n if (idx === -1) return [liveSession, ...sessions];\n const copy = sessions.slice();\n copy[idx] = liveSession;\n return copy;\n }, [sessions, liveSession]);\n\n const items = useMemo(\n () => merged.map(s => buildItem(s, decorate)),\n [merged, decorate],\n );\n\n const groups = useMemo(() => groupByTime(items), [items]);\n\n const rename = useCallback(async (id: string, title: string) => {\n setSessions(current =>\n current.map(s => (s.id === id ? { ...s, overview: title } : s)),\n );\n try {\n await sessionService.patchSession(id, { overview: title });\n } catch (err) {\n console.error('[useChatSessions] rename failed; refreshing to roll back:', err);\n void refresh();\n }\n }, [sessionService, refresh]);\n\n const remove = useCallback(async (id: string) => {\n setSessions(current => current.filter(s => s.id !== id));\n try {\n await sessionService.removeSession(id);\n } catch (err) {\n console.error('[useChatSessions] remove failed; refreshing to roll back:', err);\n void refresh();\n }\n }, [sessionService, refresh]);\n\n return { sessions: merged, groups, isLoading, error, refresh, rename, remove };\n}\n"],"names":["MINUTE_MS","HOUR_MS","DAY_MS","toDate","value","d","__name","formatTimeLabel","date","diff","startOfToday","groupByTime","items","today","yesterday","weekAgo","monthAgo","buckets","item","u","list","label","buildItem","session","decorate","updatedAt","useChatSessions","opts","defaultSessionService","useMemo","HttpSessionService","sessionService","liveSession","sessions","setSessions","useState","isLoading","setIsLoading","error","setError","refresh","useCallback","err","use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CAAQ;AAAA,EAAA,GAGfwB,IAASnB,EAAQ,MAAMlB,EAAYC,CAAK,GAAG,CAACA,CAAK,CAAC,GAElDqC,IAASR,EAAY,OAAOS,GAAYC,MAAkB;AAC5D,IAAAjB;AAAA,MAAY,CAAAkB,MACRA,EAAQ,IAAI,CAAAN,MAAMA,EAAE,OAAOI,IAAK,EAAE,GAAGJ,GAAG,UAAUK,EAAA,IAAUL,CAAE;AAAA,IAAA;AAElE,QAAI;AACA,YAAMf,EAAe,aAAamB,GAAI,EAAE,UAAUC,GAAO;AAAA,IAC7D,SAAST,GAAK;AACV,cAAQ,MAAM,6DAA6DA,CAAG,GACzEF,EAAA;AAAA,IACT;AAAA,EACJ,GAAG,CAACT,GAAgBS,CAAO,CAAC,GAEtBa,IAASZ,EAAY,OAAOS,MAAe;AAC7C,IAAAhB,EAAY,OAAWkB,EAAQ,OAAO,OAAKN,EAAE,OAAOI,CAAE,CAAC;AACvD,QAAI;AACA,YAAMnB,EAAe,cAAcmB,CAAE;AAAA,IACzC,SAASR,GAAK;AACV,cAAQ,MAAM,6DAA6DA,CAAG,GACzEF,EAAA;AAAA,IACT;AAAA,EACJ,GAAG,CAACT,GAAgBS,CAAO,CAAC;AAE5B,SAAO,EAAE,UAAUI,GAAQ,QAAAI,GAAQ,WAAAZ,GAAW,OAAAE,GAAO,SAAAE,GAAS,QAAAS,GAAQ,QAAAI,EAAA;AAC1E;AAtEgB/C,EAAAoB,GAAA;"}
|
|
1
|
+
{"version":3,"file":"useChatSessions-1AAvAdPW.js","sources":["../src/hooks/useChatSessions.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from 'react';\nimport type { ChatSession } from '@lib/models/ChatSession';\nimport type { ISessionService } from '@lib/services/servers/sessionService/ISessionService';\nimport { HttpSessionService } from '../services';\n\n/**\n * One row in a session-picker UI. `raw` is the original ChatSession the\n * server returned; everything else is a derived label the hook computed\n * (and the host's `decorate` callback may have overridden).\n */\nexport interface ChatSessionListItem {\n id: string;\n title: string;\n snippet?: string;\n /** Compact relative-time label (\"now\", \"5m\", \"2h\", \"Mar 14\"). */\n timeLabel?: string;\n /** Optional per-row tag — host-supplied via the `decorate` callback. */\n kind?: string;\n updatedAt?: Date;\n raw: ChatSession;\n}\n\n/**\n * Sessions bucketed by recency. The order of `label` reflects display\n * order top-down (\"Today\" first, \"Older\" last).\n */\nexport interface ChatSessionGroup {\n label: string;\n items: ChatSessionListItem[];\n}\n\nexport interface UseChatSessionsOptions {\n sessionService?: ISessionService;\n /**\n * If provided, the live (current) session is merged into the list —\n * replacing an existing entry by id, or prepended if not yet on the\n * server. Lets a \"New chat\" row appear instantly without waiting for\n * the server roundtrip.\n */\n liveSession?: ChatSession | null;\n\n accessToken: string,\n serverBaseUrl: string,\n /**\n * Per-row override hook. Whatever fields you return are merged on top\n * of the hook's computed item — typical use is adding a `kind` tag for\n * application-specific session types (`'chat' | 'composer' | ...`) the\n * library doesn't know about.\n */\n decorate?: (session: ChatSession) => Partial<ChatSessionListItem>;\n}\n\nexport interface UseChatSessionsResult {\n /** Flat list (live session merged in, server order preserved). */\n sessions: ChatSession[];\n /** Same data bucketed by recency. */\n groups: ChatSessionGroup[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n /** Optimistic rename — patches local state immediately, rolls back on failure. */\n rename: (id: string, title: string) => Promise<void>;\n /** Optimistic remove — drops from local state immediately, rolls back on failure. */\n remove: (id: string) => Promise<void>;\n}\n\nconst MINUTE_MS = 60_000;\nconst HOUR_MS = 60 * MINUTE_MS;\nconst DAY_MS = 24 * HOUR_MS;\n\nfunction toDate(value: Date | string | undefined | null): Date | undefined {\n if (!value) return undefined;\n if (value instanceof Date) return value;\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? undefined : d;\n}\n\nfunction formatTimeLabel(date: Date | undefined): string {\n if (!date) return '';\n const diff = Date.now() - date.getTime();\n if (diff < MINUTE_MS) return 'now';\n if (diff < HOUR_MS) return `${Math.floor(diff / MINUTE_MS)}m`;\n if (diff < DAY_MS) return `${Math.floor(diff / HOUR_MS)}h`;\n if (diff < 7 * DAY_MS) return `${Math.floor(diff / DAY_MS)}d`;\n return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });\n}\n\nfunction startOfToday(): Date {\n const d = new Date();\n d.setHours(0, 0, 0, 0);\n return d;\n}\n\nfunction groupByTime(items: ChatSessionListItem[]): ChatSessionGroup[] {\n const today = startOfToday();\n const yesterday = new Date(today.getTime() - DAY_MS);\n const weekAgo = new Date(today.getTime() - 7 * DAY_MS);\n const monthAgo = new Date(today.getTime() - 30 * DAY_MS);\n\n // Insertion-ordered map preserves the bucket display order.\n const buckets: Array<[string, ChatSessionListItem[]]> = [\n ['Today', []],\n ['Yesterday', []],\n ['This Week', []],\n ['This Month', []],\n ['Older', []],\n ];\n\n for (const item of items) {\n const u = item.updatedAt;\n if (!u) { buckets[4][1].push(item); continue; }\n if (u >= today) buckets[0][1].push(item);\n else if (u >= yesterday) buckets[1][1].push(item);\n else if (u >= weekAgo) buckets[2][1].push(item);\n else if (u >= monthAgo) buckets[3][1].push(item);\n else buckets[4][1].push(item);\n }\n\n return buckets\n .filter(([, list]) => list.length > 0)\n .map(([label, list]) => ({ label, items: list }));\n}\n\nfunction buildItem(\n session: ChatSession,\n decorate?: (s: ChatSession) => Partial<ChatSessionListItem>,\n): ChatSessionListItem {\n const updatedAt = toDate(session.updatedAt) ?? toDate(session.created);\n const base: ChatSessionListItem = {\n id: session.id ?? session.browserScopeId ?? '',\n title: session.overview || session.userDescription || '(untitled chat)',\n snippet: session.lastQuestion ?? undefined,\n timeLabel: formatTimeLabel(updatedAt),\n kind: session.agentType as string | undefined,\n updatedAt,\n raw: session,\n };\n return { ...base, ...(decorate?.(session) ?? {}) };\n}\n\n/**\n * Fetch + organise the user's chat sessions for a picker UI. Backend-agnostic\n * — the host injects an `ISessionService` so the same hook drives an HTTP\n * client, an in-memory fake, or whatever else.\n *\n * Replaces the duplicated `useEffect(async () => sessionService.getAllSessions())`\n * + grouping logic that lived in DataExplorerViewV2 and MobileSessionsList,\n * and consolidates the optimistic rename/delete pattern.\n */\nexport function useChatSessions(opts: UseChatSessionsOptions): UseChatSessionsResult {\n\n const defaultSessionService = useMemo(() => {\n return new HttpSessionService(opts.serverBaseUrl, opts.accessToken);\n }, [opts.accessToken, opts.serverBaseUrl]);\n\n const { sessionService, liveSession, decorate } = {\n sessionService: defaultSessionService,\n liveSession: opts.liveSession,\n decorate: opts.decorate\n };\n const [sessions, setSessions] = useState<ChatSession[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n\n const refresh = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const list = await sessionService.getAllSessions();\n setSessions(list);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [sessionService]);\n\n useEffect(() => { void refresh(); }, [refresh]);\n\n const merged = useMemo(() => {\n if (!liveSession?.id) return sessions;\n const idx = sessions.findIndex(s => s.id === liveSession.id);\n if (idx === -1) return [liveSession, ...sessions];\n const copy = sessions.slice();\n copy[idx] = liveSession;\n return copy;\n }, [sessions, liveSession]);\n\n const items = useMemo(\n () => merged.map(s => buildItem(s, decorate)),\n [merged, decorate],\n );\n\n const groups = useMemo(() => groupByTime(items), [items]);\n\n const rename = useCallback(async (id: string, title: string) => {\n setSessions(current =>\n current.map(s => (s.id === id ? { ...s, overview: title } : s)),\n );\n try {\n await sessionService.patchSession(id, { overview: title });\n } catch (err) {\n console.error('[useChatSessions] rename failed; refreshing to roll back:', err);\n void refresh();\n }\n }, [sessionService, refresh]);\n\n const remove = useCallback(async (id: string) => {\n setSessions(current => current.filter(s => s.id !== id));\n try {\n await sessionService.removeSession(id);\n } catch (err) {\n console.error('[useChatSessions] remove failed; refreshing to roll back:', err);\n void refresh();\n }\n }, [sessionService, refresh]);\n\n return { sessions: merged, groups, isLoading, error, refresh, rename, remove };\n}\n"],"names":["MINUTE_MS","HOUR_MS","DAY_MS","toDate","value","d","__name","formatTimeLabel","date","diff","startOfToday","groupByTime","items","today","yesterday","weekAgo","monthAgo","buckets","item","u","list","label","buildItem","session","decorate","updatedAt","useChatSessions","opts","defaultSessionService","useMemo","HttpSessionService","sessionService","liveSession","sessions","setSessions","useState","isLoading","setIsLoading","error","setError","refresh","useCallback","err","useEffect","merged","idx","s","copy","groups","rename","id","title","current","remove"],"mappings":";;;;AAkEA,MAAMA,IAAY,KACZC,IAAU,KAAKD,GACfE,IAAS,KAAKD;AAEpB,SAASE,EAAOC,GAA2D;AACvE,MAAI,CAACA,EAAO;AACZ,MAAIA,aAAiB,KAAM,QAAOA;AAClC,QAAMC,IAAI,IAAI,KAAKD,CAAK;AACxB,SAAO,OAAO,MAAMC,EAAE,QAAA,CAAS,IAAI,SAAYA;AACnD;AALSC,EAAAH,GAAA;AAOT,SAASI,EAAgBC,GAAgC;AACrD,MAAI,CAACA,EAAM,QAAO;AAClB,QAAMC,IAAO,KAAK,IAAA,IAAQD,EAAK,QAAA;AAC/B,SAAIC,IAAOT,IAAkB,QACzBS,IAAOR,IAAgB,GAAG,KAAK,MAAMQ,IAAOT,CAAS,CAAC,MACtDS,IAAOP,IAAe,GAAG,KAAK,MAAMO,IAAOR,CAAO,CAAC,MACnDQ,IAAO,IAAIP,IAAe,GAAG,KAAK,MAAMO,IAAOP,CAAM,CAAC,MACnDM,EAAK,mBAAmB,QAAW,EAAE,OAAO,SAAS,KAAK,WAAW;AAChF;AARSF,EAAAC,GAAA;AAUT,SAASG,IAAqB;AAC1B,QAAML,wBAAQ,KAAA;AACd,SAAAA,EAAE,SAAS,GAAG,GAAG,GAAG,CAAC,GACdA;AACX;AAJSC,EAAAI,GAAA;AAMT,SAASC,EAAYC,GAAkD;AACnE,QAAMC,IAAQH,EAAA,GACRI,IAAY,IAAI,KAAKD,EAAM,QAAA,IAAYX,CAAM,GAC7Ca,IAAU,IAAI,KAAKF,EAAM,QAAA,IAAY,IAAIX,CAAM,GAC/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