@aintela/chat 0.2.59 → 0.3.0

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.
Files changed (85) hide show
  1. package/README.md +63 -0
  2. package/dist/{ClientMessage-EKgfuTp8.js → ClientMessage-DUby3KyC.js} +16 -22
  3. package/dist/{ClientMessage-EKgfuTp8.js.map → ClientMessage-DUby3KyC.js.map} +1 -1
  4. package/dist/Memory-CjrYSkzB.js +47 -0
  5. package/dist/Memory-CjrYSkzB.js.map +1 -0
  6. package/dist/atMentions-CCNBOf5W.js +954 -0
  7. package/dist/atMentions-CCNBOf5W.js.map +1 -0
  8. package/dist/components.js +4239 -4165
  9. package/dist/components.js.map +1 -1
  10. package/dist/environmentUtils-VZNTCzEE.js +88 -0
  11. package/dist/environmentUtils-VZNTCzEE.js.map +1 -0
  12. package/dist/hooks.js +4 -5
  13. package/dist/{httpArtifactService-CpbRpTHb.js → httpArtifactService-kXjuQtGa.js} +518 -643
  14. package/dist/httpArtifactService-kXjuQtGa.js.map +1 -0
  15. package/dist/{httpSessionService-BEQMIKfv.js → httpSessionService-CMT6k-Nu.js} +2 -3
  16. package/dist/{httpSessionService-BEQMIKfv.js.map → httpSessionService-CMT6k-Nu.js.map} +1 -1
  17. package/dist/index.js +243 -258
  18. package/dist/models.js +48 -51
  19. package/dist/models.js.map +1 -1
  20. package/dist/serializer-D2W42bdT.js +1730 -0
  21. package/dist/serializer-D2W42bdT.js.map +1 -0
  22. package/dist/services.js +2 -2
  23. package/dist/src/components/AiChat/AiChatProvider.agent.test.d.ts +1 -0
  24. package/dist/src/components/AiChat/AiChatProvider.d.ts +2 -2
  25. package/dist/src/components/AiChat/AiChatTypes.d.ts +45 -16
  26. package/dist/src/components/AiChat/ChatPane/parts/ThoughtRun.d.ts +28 -0
  27. package/dist/src/components/AiChat/ChatPane/parts/ThoughtRunContext.d.ts +18 -0
  28. package/dist/src/components/AiChat/ChatPane/parts/index.d.ts +5 -1
  29. package/dist/src/components/AiChat/ChatPane/parts/thoughtRun.test.d.ts +1 -0
  30. package/dist/src/components/AiChat/aiChatEngine.d.ts +24 -5
  31. package/dist/src/components/AiChat/sessionStateManagerService.bind.test.d.ts +1 -0
  32. package/dist/src/components/AiChat/sessionStateManagerService.d.ts +22 -10
  33. package/dist/src/components/AiChat/useAgentEngine.d.ts +69 -0
  34. package/dist/src/components/AiChat/useAgentEngine.test.d.ts +1 -0
  35. package/dist/src/components/index.d.ts +4 -4
  36. package/dist/src/hooks/index.d.ts +1 -1
  37. package/dist/src/hooks/useContainerWidth.d.ts +0 -1
  38. package/dist/src/models/ArtifactData.d.ts +0 -7
  39. package/dist/src/models/ChatSession.d.ts +0 -32
  40. package/dist/src/models/ClientMessage.d.ts +0 -4
  41. package/dist/src/models/ServerEvent.d.ts +0 -36
  42. package/dist/src/models/enums.d.ts +0 -1
  43. package/dist/src/models/index.d.ts +1 -2
  44. package/dist/src/models/interactionPartUtils.test.d.ts +1 -0
  45. package/dist/src/models/semanticKernelModel/sanitizeJsonString.test.d.ts +0 -0
  46. package/dist/src/models/serverEventDecode.test.d.ts +0 -0
  47. package/dist/src/services/WebSocketConnection/webSocketConnectionV2.reconnect.test.d.ts +0 -0
  48. package/dist/src/services/interactionService.d.ts +11 -0
  49. package/dist/src/services/interactionServiceGrouping.test.d.ts +1 -0
  50. package/dist/src/services/servers/AgentGatewayService.d.ts +25 -18
  51. package/dist/src/services/servers/AgentGatewayWSAsync.d.ts +0 -1
  52. package/dist/src/services/servers/agentGatewayAgentContext.test.d.ts +1 -0
  53. package/dist/src/services/storageService.d.ts +16 -59
  54. package/dist/src/services/storageService.test.d.ts +1 -0
  55. package/dist/src/utils/index.d.ts +2 -6
  56. package/dist/src/utils/urlParser.d.ts +0 -1
  57. package/dist/tests/fakes/fakeRawWebSocket.d.ts +51 -0
  58. package/dist/tests/fakes/fakeStorage.d.ts +7 -0
  59. package/dist/tests/fakes/makeGateway.d.ts +24 -1
  60. package/dist/{useChatSessions-BQP7DhY1.js → useChatSessions-CpHq0e1n.js} +2 -2
  61. package/dist/{useChatSessions-BQP7DhY1.js.map → useChatSessions-CpHq0e1n.js.map} +1 -1
  62. package/dist/useContainerWidth-B40_i-NW.js +295 -0
  63. package/dist/{useContainerWidth-B3t1ZTlo.js.map → useContainerWidth-B40_i-NW.js.map} +1 -1
  64. package/dist/utils.js +340 -57
  65. package/dist/utils.js.map +1 -1
  66. package/package.json +1 -1
  67. package/dist/Memory-DjLZqgbF.js +0 -84
  68. package/dist/Memory-DjLZqgbF.js.map +0 -1
  69. package/dist/atMentions-C0dza8DD.js +0 -1000
  70. package/dist/atMentions-C0dza8DD.js.map +0 -1
  71. package/dist/auth-lluJZyQO.js +0 -524
  72. package/dist/auth-lluJZyQO.js.map +0 -1
  73. package/dist/environmentUtils-CUVZ6Dq1.js +0 -478
  74. package/dist/environmentUtils-CUVZ6Dq1.js.map +0 -1
  75. package/dist/httpArtifactService-CpbRpTHb.js.map +0 -1
  76. package/dist/serializer-BXSH9aYQ.js +0 -1360
  77. package/dist/serializer-BXSH9aYQ.js.map +0 -1
  78. package/dist/src/components/AiChat/useLiveSession.d.ts +0 -52
  79. package/dist/src/utils/jsonDetector.d.ts +0 -50
  80. package/dist/src/utils/jsonUtils.d.ts +0 -1
  81. package/dist/src/utils/materialIconsSvg.d.ts +0 -51
  82. package/dist/src/utils/objectUtils.d.ts +0 -31
  83. package/dist/src/utils/parseArtifact.d.ts +0 -3
  84. package/dist/src/utils/uriUtils.d.ts +0 -39
  85. package/dist/useContainerWidth-B3t1ZTlo.js +0 -309
@@ -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-BEQMIKfv.js";
4
+ import { H } from "./httpSessionService-CMT6k-Nu.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-BQP7DhY1.js.map
107
+ //# sourceMappingURL=useChatSessions-CpHq0e1n.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","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,IAA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A6DA,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-CpHq0e1n.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,aAAi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,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;"}
@@ -0,0 +1,295 @@
1
+ var Qt = Object.defineProperty;
2
+ var v = (u, i) => Qt(u, "name", { value: i, configurable: !0 });
3
+ import { useState as w, useRef as r, useCallback as x, useEffect as nt } from "react";
4
+ const mt = /* @__PURE__ */ v(() => ({
5
+ maxLocationConfidence: 0,
6
+ maxPersonConfidence: 0,
7
+ locationGateFired: !1,
8
+ suggestionAccepted: !1,
9
+ ghostShown: !1,
10
+ ghostAccepted: !1,
11
+ atOpened: !1,
12
+ atAccepted: null,
13
+ manualAt: !1
14
+ }), "emptyOutcome"), Pt = /* @__PURE__ */ v(() => typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `s-${Date.now()}-${Math.random()}`, "newSessionId"), Et = /* @__PURE__ */ v((u, i, k) => {
15
+ var $;
16
+ const s = u.length;
17
+ let c = i;
18
+ for (let g = 0; g < s; g++)
19
+ if (c = (c + k + s) % s, !(($ = u[c]) != null && $.disabled)) return c;
20
+ return i;
21
+ }, "nextEnabledIndex"), Xt = /* @__PURE__ */ v((u) => {
22
+ const i = /* @__PURE__ */ new Date();
23
+ i.setDate(i.getDate() + u);
24
+ const k = String(i.getDate()).padStart(2, "0"), s = String(i.getMonth() + 1).padStart(2, "0");
25
+ return `${k}/${s}/${i.getFullYear()}`;
26
+ }, "plusDaysBR");
27
+ function Vt(u, i, k = {}) {
28
+ const [s, c] = w(null), [$, g] = w(null), [rt, O] = w(0), [_, ot] = w(0), [F, ct] = w(!1), [st, L] = w(0), [It, $t] = w([]), [Lt, yt] = w([]), [Ht, it] = w(""), j = r(""), z = r(null), Q = r(u);
29
+ Q.current = u;
30
+ const H = r(i);
31
+ H.current = i;
32
+ const lt = r(k);
33
+ lt.current = k;
34
+ const U = r(null), B = r(null), Rt = r(0), wt = r(0), at = r(null), X = r(""), K = r(null), ut = r(null), ft = r(Pt()), M = r(null);
35
+ M.current = s;
36
+ const Y = r(null);
37
+ Y.current = $;
38
+ const Z = r(0), J = r(null), V = r(!1), qt = 8, Ot = 0.5, G = r(null), kt = r(""), Ct = r(() => {
39
+ }), S = r(mt()), I = r(!1), Ft = x(() => c(null), []), zt = x(() => {
40
+ $t([]), yt([]), it(""), j.current = "", K.current = null, ft.current = Pt(), S.current = mt(), I.current = !1, Z.current = 0, J.current = null, V.current = !1, g(null);
41
+ }, []), dt = x((t) => {
42
+ if (t.disabled) return;
43
+ S.current.suggestionAccepted = !0, t.kind === "location" && (I.current = !0), c(null);
44
+ const n = Q.current, f = n.getTextarea();
45
+ if (!f) return;
46
+ const h = f.selectionStart ?? f.value.length, p = f.value.slice(0, h), D = f.value.slice(h), T = t.kind === "namedLocation" || t.kind === "location";
47
+ let e;
48
+ if (T) {
49
+ const a = kt.current, y = p.replace(/\s+$/, "");
50
+ e = a && y.endsWith(a) ? y.slice(0, y.length - a.length) : p;
51
+ } else {
52
+ const a = p.search(/\S+$/);
53
+ e = a === -1 ? p : p.slice(0, a);
54
+ }
55
+ const d = e.length > 0 && !/\s$/.test(e);
56
+ if (t.kind === "date") {
57
+ const a = `${d ? " " : ""}${t.insert} `, y = `${e}${a}${D}`;
58
+ n.setDraft(y), n.focusCaret(e.length + a.length), X.current = y, K.current = null, Ct.current();
59
+ return;
60
+ }
61
+ if (t.kind === "namedLocation" && t.insert) {
62
+ const a = `@${t.insert.replace(/ /g, " ")}`, y = `${d ? " " : ""}${a} `;
63
+ n.setDraft(`${e}${y}${D}`), n.focusCaret(e.length + y.length);
64
+ return;
65
+ }
66
+ const l = t.kind === "location" ? "@" : "#", b = `${d ? " " : ""}${l}`;
67
+ n.setDraft(`${e}${b}${D}`), n.focusCaret(e.length + b.length), requestAnimationFrame(() => {
68
+ const a = n.getTextarea();
69
+ a && n.syncTrigger(a);
70
+ });
71
+ }, []), gt = x(async () => {
72
+ var p;
73
+ const t = H.current.resolveDates;
74
+ if (!t) return;
75
+ const n = X.current;
76
+ if (n.trim() === "") {
77
+ K.current = null;
78
+ return;
79
+ }
80
+ if (n === K.current || n.split(" ").length <= 2) return;
81
+ K.current = n, (p = ut.current) == null || p.abort();
82
+ const h = new AbortController();
83
+ ut.current = h;
84
+ try {
85
+ const { dates: D, locations: T } = await t(n, ft.current, h.signal);
86
+ if (X.current !== n) return;
87
+ const e = D.filter((l) => l.display).map((l) => ({ text: l.text, display: l.display }));
88
+ yt(e), $t(T.map((l) => l.text).filter((l) => l.trim().length > 0));
89
+ const d = e.map((l) => `${l.text}=${l.display}`).join("|");
90
+ e.length > 0 && d !== j.current && (j.current = d, it(e[e.length - 1].text), z.current != null && window.clearTimeout(z.current), z.current = window.setTimeout(() => it(""), 2e3)), e.length === 0 && (j.current = "");
91
+ } catch {
92
+ }
93
+ }, []);
94
+ Ct.current = gt;
95
+ const Ut = x((t, n, f) => {
96
+ if (X.current = t, Y.current !== null && (Z.current += 1, Z.current >= qt && (V.current = !0, g(null))), t.split(" ").length <= 2) return;
97
+ const p = H.current.analyze;
98
+ p && (!f || M.current !== null || Y.current !== null) && (U.current != null && window.clearTimeout(U.current), U.current = window.setTimeout(async () => {
99
+ var T;
100
+ const D = ++Rt.current;
101
+ try {
102
+ const e = await p(t, n);
103
+ if (D !== Rt.current) return;
104
+ const d = Q.current, l = d.getTextarea();
105
+ if (!l || l.value !== t) return;
106
+ ot(e.personConfidence ?? 0), O(e.locationConfidence ?? 0);
107
+ const b = S.current;
108
+ b.maxPersonConfidence = Math.max(b.maxPersonConfidence, e.personConfidence ?? 0), b.maxLocationConfidence = Math.max(b.maxLocationConfidence, e.locationConfidence ?? 0), g(null);
109
+ const a = (l.selectionStart ?? n) === t.length, y = d.hasAtQuery, bt = d.isPickerOpen(), vt = e.suggestions ?? [], { enableHashDatePicker: Nt = !1, datePresets: Wt = ["amanhã de manhã", "quarta-feira à noite"] } = lt.current;
110
+ let P = e.category === "location" ? "location" : e.category === "date" ? "date" : e.locationExpected ? "location" : e.dateExpected ? "date" : null;
111
+ if (P !== "location" && e.locationCount < 2 && H.current.suggest && M.current !== null && G.current === "location" && a && /\s$/.test(t) && (P = "location"), lt.current.promptHint && a && !bt) {
112
+ const o = e.personConfidence ?? 0, A = e.locationConfidence ?? 0, N = P === "location" && !(e.locationCount >= 2 && e.locationPartialEmpty), C = o >= Ot && o >= A ? "person" : N ? "location" : null;
113
+ if (C) {
114
+ V.current || (J.current = C, g(C), b.ghostShown = !0, C === "location" && (b.locationGateFired = !0)), c(null), G.current = null;
115
+ return;
116
+ }
117
+ J.current = null;
118
+ }
119
+ if (P === "location" && e.locationCount >= 2 && e.locationPartialEmpty) {
120
+ c(null), G.current = null;
121
+ return;
122
+ }
123
+ if (P === null || !(a && !bt && (P === "location" ? y : P === "date"))) {
124
+ c(null), G.current = null;
125
+ return;
126
+ }
127
+ const R = P;
128
+ G.current = R, R === "location" && (b.locationGateFired = !0);
129
+ const pt = /* @__PURE__ */ v(() => R === "date" && Nt ? [{ key: "cal", label: `📅 no dia #${Xt(2)}`, kind: "calendar" }] : [], "genericTail"), xt = vt.filter((o) => o.kind === "location"), Tt = vt.filter((o) => o.kind === "date").map((o) => o.value), E = [];
130
+ if (R === "location") {
131
+ for (const o of xt)
132
+ E.push({ key: `loc:${o.value}`, label: `📍 ${o.label}`, kind: "namedLocation", insert: o.value });
133
+ E.push(...pt());
134
+ } else {
135
+ for (const o of Tt.length > 0 ? Tt : Wt)
136
+ E.push({ key: `date:${o}`, label: `📅 ${o}`, kind: "date", insert: o });
137
+ E.push(...pt());
138
+ }
139
+ const tt = H.current.suggest, _t = R === "location" ? xt.length > 0 : !0;
140
+ if (R === "location" && !_t && !tt) {
141
+ if (!f && e.locationExpected && e.locationPartialEmpty && e.locationCount < 2 && y && d.currentTriggerChar() !== "@") {
142
+ const o = l.selectionStart ?? t.length, A = t.slice(0, o), N = A.length > 0 && !/\s$/.test(A);
143
+ if (!A.endsWith("@")) {
144
+ const C = N ? " @" : "@";
145
+ I.current = !0, c(null), d.setDraft(`${A}${C}${t.slice(o)}`), d.focusCaret(o + C.length), requestAnimationFrame(() => {
146
+ const et = d.getTextarea();
147
+ et && d.syncTrigger(et);
148
+ });
149
+ }
150
+ return;
151
+ }
152
+ c(null);
153
+ return;
154
+ }
155
+ if (tt ? M.current === null && E.length > 0 && (L(0), ct(!0), c(E)) : E.length > 0 ? (L(0), ct(!0), c(E)) : c(null), tt) {
156
+ const o = t.slice(0, l.selectionStart ?? t.length), A = o.search(/[ \t\r\n](?=[^ \t\r\n]*$)/), N = A === -1 ? o : o.slice(A + 1), C = R === "location" && e.locationPartial !== void 0 ? e.locationPartial : N;
157
+ R === "location" && (kt.current = C);
158
+ const et = R === "location" ? [...t.matchAll(/@\(([A-Za-z]{3})\)/g)].map((W) => W[1].toUpperCase()) : void 0, jt = ++wt.current;
159
+ (T = at.current) == null || T.abort();
160
+ const At = new AbortController();
161
+ at.current = At;
162
+ try {
163
+ const W = await tt(C, R, At.signal, et);
164
+ if (jt !== wt.current) return;
165
+ const St = d.getTextarea();
166
+ if (!St || St.value !== t || R === "location" && W.length === 0) return;
167
+ const q = [];
168
+ if (R === "location")
169
+ for (const m of W)
170
+ q.push({
171
+ key: `loc:${m.insert}`,
172
+ label: `📍 ${m.label}`,
173
+ kind: "namedLocation",
174
+ insert: m.insert,
175
+ hint: [m.iata, m.region, m.country].filter(Boolean).join(" · ") || void 0,
176
+ // parity with the `@` picker
177
+ disabled: m.disabled
178
+ // already in the prompt (same city) — greyed, not pickable
179
+ });
180
+ else
181
+ for (const m of W)
182
+ q.push({ key: `date:${m.insert}`, label: `📅 ${m.label}`, kind: "date", insert: m.insert });
183
+ if (q.push(...pt()), q.length === 0) {
184
+ c(null);
185
+ return;
186
+ }
187
+ const Dt = q.findIndex((m) => !m.disabled);
188
+ L(Dt < 0 ? 0 : Dt), ct(C.trim() === ""), c(q);
189
+ } catch {
190
+ }
191
+ }
192
+ } catch {
193
+ }
194
+ }, 200)), B.current != null && window.clearTimeout(B.current), B.current = window.setTimeout(() => {
195
+ gt();
196
+ }, 300);
197
+ }, [gt]), Bt = x((t) => {
198
+ var f, h;
199
+ const n = t.trim();
200
+ n && ((h = (f = H.current).commitIntent) == null || h.call(f, n, ft.current, S.current)), S.current = mt(), I.current = !1;
201
+ }, []), Kt = x(() => {
202
+ const t = S.current;
203
+ t.atOpened = !0, I.current ? I.current = !1 : Y.current === null && M.current === null && (t.manualAt = !0);
204
+ }, []), Mt = x((t) => {
205
+ S.current.atAccepted = t ?? "location";
206
+ }, []), ht = x(() => {
207
+ S.current.ghostAccepted = !0, I.current = !0, Z.current = 0, J.current = null, g(null);
208
+ const t = Q.current, n = t.getTextarea();
209
+ if (!n) return;
210
+ const f = n.selectionStart ?? n.value.length, h = n.value.slice(0, f), p = n.value.slice(f), T = `${h.length > 0 && !/\s$/.test(h) ? " " : ""}@`;
211
+ t.setDraft(`${h}${T}${p}`), t.focusCaret(f + T.length), requestAnimationFrame(() => {
212
+ const e = t.getTextarea();
213
+ e && t.syncTrigger(e);
214
+ });
215
+ }, []), Gt = x((t) => {
216
+ if ($ !== null && (!s || s.length === 0)) {
217
+ if (t.key === "Tab" || t.key === "ArrowRight")
218
+ return t.preventDefault(), ht(), !0;
219
+ if (t.key === "Escape")
220
+ return t.preventDefault(), V.current = !0, g(null), !0;
221
+ }
222
+ if (!s || s.length === 0) return !1;
223
+ if (t.key === "ArrowDown")
224
+ return t.preventDefault(), L((n) => Et(s, n, 1)), !0;
225
+ if (t.key === "ArrowUp")
226
+ return t.preventDefault(), L((n) => Et(s, n, -1)), !0;
227
+ if (t.key === "Enter" || t.key === "Tab") {
228
+ t.preventDefault();
229
+ const n = s[st];
230
+ return n && !n.disabled && dt(n), !0;
231
+ }
232
+ return t.key === "Escape" ? (t.preventDefault(), c(null), !0) : !1;
233
+ }, [s, st, dt, $, ht]);
234
+ return nt(() => () => {
235
+ var t, n;
236
+ U.current != null && window.clearTimeout(U.current), B.current != null && window.clearTimeout(B.current), z.current != null && window.clearTimeout(z.current), (t = ut.current) == null || t.abort(), (n = at.current) == null || n.abort();
237
+ }, []), {
238
+ predictions: s,
239
+ predictionsRecents: F,
240
+ predictionHighlight: st,
241
+ setPredictionHighlight: L,
242
+ applyPrediction: dt,
243
+ clearPredictions: Ft,
244
+ hint: $,
245
+ acceptHint: ht,
246
+ resolvedLocations: It,
247
+ resolvedDates: Lt,
248
+ forceTooltipText: Ht,
249
+ personConfidence: _,
250
+ locationConfidence: rt,
251
+ scheduleAssist: Ut,
252
+ commit: Bt,
253
+ onKeyDown: Gt,
254
+ resetSession: zt,
255
+ noteAtOpened: Kt,
256
+ noteAtAccepted: Mt
257
+ };
258
+ }
259
+ v(Vt, "usePromptAssist");
260
+ function te(u, i) {
261
+ const k = r(u), [s, c] = w(null);
262
+ return nt(() => {
263
+ k.current = u;
264
+ }, [u]), nt(() => {
265
+ function $() {
266
+ k.current();
267
+ }
268
+ if (v($, "tick"), i !== null) {
269
+ const g = setInterval($, i);
270
+ return c(g), () => {
271
+ clearInterval(g);
272
+ };
273
+ }
274
+ }, [i]), s;
275
+ }
276
+ v(te, "useInterval");
277
+ function ee(u, i, k = 0, s = 0) {
278
+ const [c, $] = w(k), [g, rt] = w(s);
279
+ return nt(() => {
280
+ const O = u.current;
281
+ if (!O) return;
282
+ const _ = new ResizeObserver((ot) => {
283
+ const F = ot[0];
284
+ F && (rt(F.contentRect.height), $(F.contentRect.width));
285
+ });
286
+ return _.observe(O), $(O.getBoundingClientRect().width), () => _.disconnect();
287
+ }, [u, i]), [c, g];
288
+ }
289
+ v(ee, "useContainerRectangle");
290
+ export {
291
+ te as a,
292
+ Vt as b,
293
+ ee as u
294
+ };
295
+ //# sourceMappingURL=useContainerWidth-B40_i-NW.js.map