@gravity-ui/aikit 3.2.0 → 3.2.1-beta.62cd303ea62095304bfb52217eb70529a7dbaf96.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 (93) hide show
  1. package/build/cjs/components/organisms/Header/Header.css +25 -0
  2. package/build/cjs/components/organisms/Header/Header.js +21 -2
  3. package/build/cjs/components/organisms/Header/Header.js.map +1 -1
  4. package/build/cjs/components/organisms/Header/i18n/en.json +4 -1
  5. package/build/cjs/components/organisms/Header/i18n/index.d.ts +4 -4
  6. package/build/cjs/components/organisms/Header/i18n/ru.json +4 -1
  7. package/build/cjs/components/organisms/Header/types.d.ts +3 -0
  8. package/build/cjs/components/organisms/Header/types.js.map +1 -1
  9. package/build/cjs/components/pages/ChatContainer/ChatContainer.js +18 -9
  10. package/build/cjs/components/pages/ChatContainer/ChatContainer.js.map +1 -1
  11. package/build/cjs/components/pages/ChatContainer/types.d.ts +9 -0
  12. package/build/cjs/components/pages/ChatContainer/types.js.map +1 -1
  13. package/build/cjs/components/templates/History/ChatItem.d.ts +4 -1
  14. package/build/cjs/components/templates/History/ChatItem.js +2 -2
  15. package/build/cjs/components/templates/History/ChatItem.js.map +1 -1
  16. package/build/cjs/components/templates/History/History.css +14 -0
  17. package/build/cjs/components/templates/History/History.js +1 -1
  18. package/build/cjs/components/templates/History/History.js.map +1 -1
  19. package/build/cjs/components/templates/History/HistoryList.d.ts +5 -0
  20. package/build/cjs/components/templates/History/HistoryList.js +14 -4
  21. package/build/cjs/components/templates/History/HistoryList.js.map +1 -1
  22. package/build/cjs/components/templates/History/i18n/en.json +3 -1
  23. package/build/cjs/components/templates/History/i18n/index.d.ts +4 -4
  24. package/build/cjs/components/templates/History/i18n/ru.json +3 -1
  25. package/build/cjs/hooks/index.d.ts +1 -0
  26. package/build/cjs/hooks/index.js +1 -0
  27. package/build/cjs/hooks/index.js.map +1 -1
  28. package/build/cjs/hooks/useChatActivity.d.ts +10 -0
  29. package/build/cjs/hooks/useChatActivity.js +51 -0
  30. package/build/cjs/hooks/useChatActivity.js.map +1 -0
  31. package/build/cjs/package.json +1 -1
  32. package/build/cjs/utils/chatActivityPersistence.d.ts +21 -0
  33. package/build/cjs/utils/chatActivityPersistence.js +186 -0
  34. package/build/cjs/utils/chatActivityPersistence.js.map +1 -0
  35. package/build/cjs/utils/chatActivityStore.d.ts +59 -0
  36. package/build/cjs/utils/chatActivityStore.js +112 -0
  37. package/build/cjs/utils/chatActivityStore.js.map +1 -0
  38. package/build/cjs/utils/index.d.ts +2 -0
  39. package/build/cjs/utils/index.js +2 -0
  40. package/build/cjs/utils/index.js.map +1 -1
  41. package/build/cjs/utils/remoteChatActivityStore.d.ts +38 -0
  42. package/build/cjs/utils/remoteChatActivityStore.js +127 -0
  43. package/build/cjs/utils/remoteChatActivityStore.js.map +1 -0
  44. package/build/docs/INDEX.md +1 -0
  45. package/build/docs/components/organisms/Header.md +5 -0
  46. package/build/docs/components/pages/ChatContainer.md +5 -0
  47. package/build/docs/components/templates/History.md +6 -0
  48. package/build/docs/guides/chat-activity.md +158 -0
  49. package/build/esm/components/organisms/Header/Header.css +25 -0
  50. package/build/esm/components/organisms/Header/Header.js +22 -3
  51. package/build/esm/components/organisms/Header/Header.js.map +1 -1
  52. package/build/esm/components/organisms/Header/i18n/en.json +4 -1
  53. package/build/esm/components/organisms/Header/i18n/index.d.ts +4 -4
  54. package/build/esm/components/organisms/Header/i18n/ru.json +4 -1
  55. package/build/esm/components/organisms/Header/types.d.ts +3 -0
  56. package/build/esm/components/organisms/Header/types.js.map +1 -1
  57. package/build/esm/components/pages/ChatContainer/ChatContainer.js +18 -9
  58. package/build/esm/components/pages/ChatContainer/ChatContainer.js.map +1 -1
  59. package/build/esm/components/pages/ChatContainer/types.d.ts +9 -0
  60. package/build/esm/components/pages/ChatContainer/types.js.map +1 -1
  61. package/build/esm/components/templates/History/ChatItem.d.ts +4 -1
  62. package/build/esm/components/templates/History/ChatItem.js +3 -3
  63. package/build/esm/components/templates/History/ChatItem.js.map +1 -1
  64. package/build/esm/components/templates/History/History.css +14 -0
  65. package/build/esm/components/templates/History/History.js +1 -1
  66. package/build/esm/components/templates/History/History.js.map +1 -1
  67. package/build/esm/components/templates/History/HistoryList.d.ts +5 -0
  68. package/build/esm/components/templates/History/HistoryList.js +14 -4
  69. package/build/esm/components/templates/History/HistoryList.js.map +1 -1
  70. package/build/esm/components/templates/History/i18n/en.json +3 -1
  71. package/build/esm/components/templates/History/i18n/index.d.ts +4 -4
  72. package/build/esm/components/templates/History/i18n/ru.json +3 -1
  73. package/build/esm/hooks/index.d.ts +1 -0
  74. package/build/esm/hooks/index.js +1 -0
  75. package/build/esm/hooks/index.js.map +1 -1
  76. package/build/esm/hooks/useChatActivity.d.ts +10 -0
  77. package/build/esm/hooks/useChatActivity.js +48 -0
  78. package/build/esm/hooks/useChatActivity.js.map +1 -0
  79. package/build/esm/package.json +1 -1
  80. package/build/esm/utils/chatActivityPersistence.d.ts +21 -0
  81. package/build/esm/utils/chatActivityPersistence.js +183 -0
  82. package/build/esm/utils/chatActivityPersistence.js.map +1 -0
  83. package/build/esm/utils/chatActivityStore.d.ts +59 -0
  84. package/build/esm/utils/chatActivityStore.js +107 -0
  85. package/build/esm/utils/chatActivityStore.js.map +1 -0
  86. package/build/esm/utils/index.d.ts +2 -0
  87. package/build/esm/utils/index.js +2 -0
  88. package/build/esm/utils/index.js.map +1 -1
  89. package/build/esm/utils/remoteChatActivityStore.d.ts +38 -0
  90. package/build/esm/utils/remoteChatActivityStore.js +124 -0
  91. package/build/esm/utils/remoteChatActivityStore.js.map +1 -0
  92. package/docs/chat-activity.md +158 -0
  93. package/package.json +1 -1
@@ -0,0 +1,107 @@
1
+ import { createChatActivityPersistence } from "./chatActivityPersistence.js";
2
+ export const EMPTY_CHAT_ACTIVITY = Object.freeze({
3
+ chats: Object.freeze({}),
4
+ isGenerating: false,
5
+ hasUnread: false,
6
+ });
7
+ /** Normalize immutable rows and derive the history summary for local or external stores. */
8
+ export function createChatActivitySnapshot(chats) {
9
+ const rows = Object.fromEntries(Object.entries(chats).map(([id, chat]) => [id, Object.freeze(Object.assign({}, chat))]));
10
+ const values = Object.values(rows);
11
+ return Object.freeze({
12
+ chats: Object.freeze(rows),
13
+ isGenerating: values.some((chat) => chat.isGenerating),
14
+ hasUnread: values.some((chat) => chat.hasUnread),
15
+ });
16
+ }
17
+ /**
18
+ * Create once per account, outside the panel's lifecycle. Persist response/read markers and request
19
+ * ownership, but keep generation activity in memory. Restore live requests from the backend with
20
+ * startGeneration; history loading must
21
+ * never replay completion events. Response IDs must be unique across requests and stable on reload.
22
+ */
23
+ export function createChatActivityStore(options) {
24
+ if (!options.accountId)
25
+ throw new Error('Chat activity requires an account identifier');
26
+ const persistence = createChatActivityPersistence(options);
27
+ let snapshot = EMPTY_CHAT_ACTIVITY;
28
+ const listeners = new Set();
29
+ const generations = new Map();
30
+ const load = () => {
31
+ var _a, _b;
32
+ const { chats, requestIds } = persistence.readState();
33
+ const activities = new Map(Object.entries(chats).map(([id, response]) => [id, Object.assign(Object.assign({}, response), { isGenerating: false })]));
34
+ for (const [chatId, id] of generations) {
35
+ if (requestIds.get(chatId) === id) {
36
+ activities.set(chatId, Object.assign(Object.assign({}, activities.get(chatId)), { isGenerating: true, hasUnread: (_b = (_a = activities.get(chatId)) === null || _a === void 0 ? void 0 : _a.hasUnread) !== null && _b !== void 0 ? _b : false }));
37
+ }
38
+ else {
39
+ generations.delete(chatId);
40
+ }
41
+ }
42
+ snapshot = createChatActivitySnapshot(Object.fromEntries(activities));
43
+ listeners.forEach((listener) => listener());
44
+ };
45
+ const handleStorage = (event) => {
46
+ if (persistence.isStorageEvent(event))
47
+ load();
48
+ };
49
+ return {
50
+ getSnapshot: () => snapshot,
51
+ subscribe: (listener) => {
52
+ if (!listeners.size && typeof window !== 'undefined') {
53
+ window.addEventListener('storage', handleStorage);
54
+ }
55
+ listeners.add(listener);
56
+ return () => {
57
+ listeners.delete(listener);
58
+ if (!listeners.size && typeof window !== 'undefined') {
59
+ window.removeEventListener('storage', handleStorage);
60
+ }
61
+ };
62
+ },
63
+ load,
64
+ startGeneration: (chatId) => {
65
+ load();
66
+ const id = Array.from(crypto.getRandomValues(new Uint32Array(4)), (value) => value.toString(36)).join('-');
67
+ let responseId;
68
+ if (!persistence.isDeleted(chatId)) {
69
+ const current = snapshot.chats[chatId];
70
+ persistence.start(chatId, id, (current === null || current === void 0 ? void 0 : current.responseId) === undefined
71
+ ? undefined
72
+ : { responseId: current.responseId, hasUnread: current.hasUnread });
73
+ generations.set(chatId, id);
74
+ load();
75
+ }
76
+ return {
77
+ responseReceived: (response) => {
78
+ if (generations.get(chatId) === id && response)
79
+ responseId = response;
80
+ },
81
+ finish: () => {
82
+ load();
83
+ if (generations.get(chatId) !== id)
84
+ return;
85
+ generations.delete(chatId);
86
+ if (responseId !== undefined)
87
+ persistence.finish(chatId, id, responseId);
88
+ load();
89
+ },
90
+ };
91
+ },
92
+ markResponseViewed: (chatId, responseId) => {
93
+ load();
94
+ const current = snapshot.chats[chatId];
95
+ if ((current === null || current === void 0 ? void 0 : current.hasUnread) && current.responseId === responseId) {
96
+ persistence.markViewed(chatId, responseId);
97
+ load();
98
+ }
99
+ },
100
+ deleteChat: (chatId) => {
101
+ persistence.deleteChat(chatId);
102
+ generations.delete(chatId);
103
+ load();
104
+ },
105
+ };
106
+ }
107
+ //# sourceMappingURL=chatActivityStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chatActivityStore.js","sourceRoot":"../../../src","sources":["utils/chatActivityStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,6BAA6B,EAAC,qCAAkC;AA0DxE,MAAM,CAAC,MAAM,mBAAmB,GAAyB,MAAM,CAAC,MAAM,CAAC;IACnE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;IACxB,YAAY,EAAE,KAAK;IACnB,SAAS,EAAE,KAAK;CACnB,CAAC,CAAC;AAEH,4F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AAI,EAAE,CAAC;oBACP,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE;wBAAE,OAAO;oBAC3C,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;oBAC3B,IAAI,UAAU,KAAK,SAAS;wBAAE,WAAW,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,EAAE,UAAU,CAAC,CAAC;oBACzE,IAAI,EAAE,CAAC;gBACX,CAAC;aACJ,CAAC;QACN,CAAC;QACD,kBAAkB,EAAE,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE;YACvC,IAAI,EAAE,CAAC;YACP,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YACvC,IAAI,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,KAAI,OAAO,CAAC,UAAU,KAAK,UAAU,EAAE,CAAC;gBAC1D,WAAW,CAAC,UAAU,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;gBAC3C,IAAI,EAAE,CAAC;YACX,CAAC;QACL,CAAC;QACD,UAAU,EAAE,CAAC,MAAM,EAAE,EAAE;YACnB,WAAW,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;YAC/B,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC3B,IAAI,EAAE,CAAC;QACX,CAAC;KACJ,CAAC;AACN,CAAC","sourcesContent":["import {createChatActivityPersistence} from './chatActivityPersistence';\n\n/** Activity is independent of the currently selected chat and survives panel unmounts. */\nexport interface ChatActivity {\n readonly isGenerating: boolean;\n readonly hasUnread: boolean;\n /** Identifier of the latest completed response containing user-visible assistant text. */\n readonly responseId?: string;\n}\n\nexport interface ChatActivityError {\n readonly operation: 'load' | 'markResponseViewed';\n readonly cause: unknown;\n readonly chatId?: string;\n readonly responseId?: string;\n}\n\nexport interface ChatActivitySnapshot {\n readonly chats: Readonly<Record<string, ChatActivity>>;\n readonly isGenerating: boolean;\n readonly hasUnread: boolean;\n /** Async adapters expose loading and command failures without changing unread state. */\n readonly isLoading?: boolean;\n readonly error?: ChatActivityError;\n}\n\nexport interface ChatGeneration {\n /** Report assistant text only, excluding tool output, reasoning and error messages. */\n responseReceived: (responseId: string) => void;\n /** Call on success, cancellation or failure, including failures before the first text. */\n finish: () => void;\n}\n\nexport interface ChatActivityStore {\n getSnapshot: () => ChatActivitySnapshot;\n subscribe: (listener: () => void) => () => void;\n /** Optional initial loading; components consume rejected promises, stores report errors. */\n load?: () => void | Promise<void>;\n markResponseViewed: (chatId: string, responseId: string) => void | Promise<void>;\n /** Evict local state after the host has successfully deleted the chat. */\n deleteChat: (chatId: string) => void;\n}\n\n/** Local request lifecycle is independent of the contract consumed by components. */\nexport interface LocalChatActivityStore extends ChatActivityStore {\n load: () => void;\n /** Starting a new request invalidates all handles for the previous request in this chat. */\n startGeneration: (chatId: string) => ChatGeneration;\n}\n\nexport interface ChatActivityStoreOptions {\n /** Stable authenticated account identifier. Create a separate store on account change. */\n accountId: string;\n /** Storage must enumerate keys via key/length. Defaults to localStorage; null uses memory. */\n storage?: Pick<Storage, 'getItem' | 'setItem' | 'key' | 'length'> | null;\n onPersistenceError?: (error: unknown) => void;\n}\n\nexport const EMPTY_CHAT_ACTIVITY: ChatActivitySnapshot = Object.freeze({\n chats: Object.freeze({}),\n isGenerating: false,\n hasUnread: false,\n});\n\n/** Normalize immutable rows and derive the history summary for local or external stores. */\nexport function createChatActivitySnapshot(\n chats: ChatActivitySnapshot['chats'],\n): ChatActivitySnapshot {\n const rows = Object.fromEntries(\n Object.entries(chats).map(([id, chat]) => [id, Object.freeze({...chat})]),\n );\n const values = Object.values(rows);\n return Object.freeze({\n chats: Object.freeze(rows),\n isGenerating: values.some((chat) => chat.isGenerating),\n hasUnread: values.some((chat) => chat.hasUnread),\n });\n}\n\n/**\n * Create once per account, outside the panel's lifecycle. Persist response/read markers and request\n * ownership, but keep generation activity in memory. Restore live requests from the backend with\n * startGeneration; history loading must\n * never replay completion events. Response IDs must be unique across requests and stable on reload.\n */\nexport function createChatActivityStore(options: ChatActivityStoreOptions): LocalChatActivityStore {\n if (!options.accountId) throw new Error('Chat activity requires an account identifier');\n const persistence = createChatActivityPersistence(options);\n let snapshot = EMPTY_CHAT_ACTIVITY;\n const listeners = new Set<() => void>();\n const generations = new Map<string, string>();\n const load = () => {\n const {chats, requestIds} = persistence.readState();\n const activities = new Map<string, ChatActivity>(\n Object.entries(chats).map(([id, response]) => [id, {...response, isGenerating: false}]),\n );\n for (const [chatId, id] of generations) {\n if (requestIds.get(chatId) === id) {\n activities.set(chatId, {\n ...activities.get(chatId),\n isGenerating: true,\n hasUnread: activities.get(chatId)?.hasUnread ?? false,\n });\n } else {\n generations.delete(chatId);\n }\n }\n snapshot = createChatActivitySnapshot(Object.fromEntries(activities));\n listeners.forEach((listener) => listener());\n };\n const handleStorage = (event: StorageEvent) => {\n if (persistence.isStorageEvent(event)) load();\n };\n return {\n getSnapshot: () => snapshot,\n subscribe: (listener) => {\n if (!listeners.size && typeof window !== 'undefined') {\n window.addEventListener('storage', handleStorage);\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (!listeners.size && typeof window !== 'undefined') {\n window.removeEventListener('storage', handleStorage);\n }\n };\n },\n load,\n startGeneration: (chatId) => {\n load();\n const id = Array.from(crypto.getRandomValues(new Uint32Array(4)), (value) =>\n value.toString(36),\n ).join('-');\n let responseId: string | undefined;\n if (!persistence.isDeleted(chatId)) {\n const current = snapshot.chats[chatId];\n persistence.start(\n chatId,\n id,\n current?.responseId === undefined\n ? undefined\n : {responseId: current.responseId, hasUnread: current.hasUnread},\n );\n generations.set(chatId, id);\n load();\n }\n return {\n responseReceived: (response) => {\n if (generations.get(chatId) === id && response) responseId = response;\n },\n finish: () => {\n load();\n if (generations.get(chatId) !== id) return;\n generations.delete(chatId);\n if (responseId !== undefined) persistence.finish(chatId, id, responseId);\n load();\n },\n };\n },\n markResponseViewed: (chatId, responseId) => {\n load();\n const current = snapshot.chats[chatId];\n if (current?.hasUnread && current.responseId === responseId) {\n persistence.markViewed(chatId, responseId);\n load();\n }\n },\n deleteChat: (chatId) => {\n persistence.deleteChat(chatId);\n generations.delete(chatId);\n load();\n },\n };\n}\n"]}
@@ -7,4 +7,6 @@ export * from "./aiAgentContext/index.js";
7
7
  export * from "./toolset/index.js";
8
8
  export * from "./mascot.js";
9
9
  export * from "./pinnedChatsStore.js";
10
+ export * from "./chatActivityStore.js";
11
+ export * from "./remoteChatActivityStore.js";
10
12
  export * from "./chatMarkdown.js";
@@ -8,5 +8,7 @@ export * from "./aiAgentContext/index.js";
8
8
  export * from "./toolset/index.js";
9
9
  export * from "./mascot.js";
10
10
  export * from "./pinnedChatsStore.js";
11
+ export * from "./chatActivityStore.js";
12
+ export * from "./remoteChatActivityStore.js";
11
13
  export * from "./chatMarkdown.js";
12
14
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"../../../src","sources":["utils/index.ts"],"names":[],"mappings":"AAAA,mBAAmB;AACnB,+BAA4B;AAC5B,kCAA+B;AAC/B,gCAA6B;AAC7B,yCAAsC;AACtC,oCAAiC;AACjC,0CAAiC;AACjC,mCAA0B;AAC1B,4BAAyB;AACzB,sCAAmC;AACnC,kCAA+B","sourcesContent":["// Export utilities\nexport * from './chatUtils';\nexport * from './messageUtils';\nexport * from './validation';\nexport * from './messageTypeRegistry';\nexport * from './clipboardUtils';\nexport * from './aiAgentContext';\nexport * from './toolset';\nexport * from './mascot';\nexport * from './pinnedChatsStore';\nexport * from './chatMarkdown';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"../../../src","sources":["utils/index.ts"],"names":[],"mappings":"AAAA,mBAAmB;AACnB,+BAA4B;AAC5B,kCAA+B;AAC/B,gCAA6B;AAC7B,yCAAsC;AACtC,oCAAiC;AACjC,0CAAiC;AACjC,mCAA0B;AAC1B,4BAAyB;AACzB,sCAAmC;AACnC,uCAAoC;AACpC,6CAA0C;AAC1C,kCAA+B","sourcesContent":["// Export utilities\nexport * from './chatUtils';\nexport * from './messageUtils';\nexport * from './validation';\nexport * from './messageTypeRegistry';\nexport * from './clipboardUtils';\nexport * from './aiAgentContext';\nexport * from './toolset';\nexport * from './mascot';\nexport * from './pinnedChatsStore';\nexport * from './chatActivityStore';\nexport * from './remoteChatActivityStore';\nexport * from './chatMarkdown';\n"]}
@@ -0,0 +1,38 @@
1
+ import { type ChatActivityError, type ChatActivitySnapshot, type ChatActivityStore } from "./chatActivityStore.js";
2
+ /** Full account-scoped server state. Revisions must increase for every state change. */
3
+ export interface RemoteChatActivityState {
4
+ readonly accountId: string;
5
+ readonly revision: number;
6
+ readonly chats: ChatActivitySnapshot['chats'];
7
+ }
8
+ export interface RemoteChatActivityStoreOptions {
9
+ accountId: string;
10
+ initialState?: RemoteChatActivityState;
11
+ /** Omit when the application feeds its query cache or pushed updates through applySnapshot. */
12
+ load?: () => Promise<RemoteChatActivityState>;
13
+ /**
14
+ * Acknowledge this exact response. Return authoritative state, or feed it separately through
15
+ * applySnapshot after query invalidation/push. A resolved command alone never clears a dot.
16
+ */
17
+ markResponseViewed: (chatId: string, responseId: string) => void | RemoteChatActivityState | Promise<void | RemoteChatActivityState>;
18
+ onError?: (error: ChatActivityError) => void;
19
+ }
20
+ export interface RemoteChatActivitySnapshot extends ChatActivitySnapshot {
21
+ readonly revision?: number;
22
+ readonly isLoading: boolean;
23
+ }
24
+ export interface RemoteChatActivityStore extends ChatActivityStore {
25
+ getSnapshot: () => RemoteChatActivitySnapshot;
26
+ markResponseViewed: (chatId: string, responseId: string) => Promise<void>;
27
+ /** Idempotent initial load; concurrent calls share the same request. */
28
+ load: () => Promise<void>;
29
+ /** Explicit retry/refresh. Rejections are also exposed through error and onError. */
30
+ refresh: () => Promise<void>;
31
+ /** Accept a full authoritative snapshot, ignoring equal or older revisions. */
32
+ applySnapshot: (state: RemoteChatActivityState) => void;
33
+ }
34
+ /**
35
+ * Adapts application-provided backend data without running the local generation engine or using
36
+ * localStorage. Keep one instance per account and replace it when the account changes.
37
+ */
38
+ export declare function createRemoteChatActivityStore(options: RemoteChatActivityStoreOptions): RemoteChatActivityStore;
@@ -0,0 +1,124 @@
1
+ import { EMPTY_CHAT_ACTIVITY, createChatActivitySnapshot, } from "./chatActivityStore.js";
2
+ /**
3
+ * Adapts application-provided backend data without running the local generation engine or using
4
+ * localStorage. Keep one instance per account and replace it when the account changes.
5
+ */
6
+ export function createRemoteChatActivityStore(options) {
7
+ if (!options.accountId)
8
+ throw new Error('Chat activity requires an account identifier');
9
+ let activity = EMPTY_CHAT_ACTIVITY;
10
+ let revision;
11
+ let isLoading = false;
12
+ let error;
13
+ let snapshot = Object.freeze(Object.assign(Object.assign({}, activity), { isLoading }));
14
+ let loaded = false;
15
+ let loadingPromise;
16
+ const acknowledgements = new Map();
17
+ // Chat IDs must not be reused within an account. Tombstones also filter late command results.
18
+ const deletedChats = new Set();
19
+ const listeners = new Set();
20
+ const publish = () => {
21
+ snapshot = Object.freeze(Object.assign(Object.assign({}, activity), { revision, isLoading, error }));
22
+ listeners.forEach((listener) => listener());
23
+ };
24
+ const reportError = (failure) => {
25
+ var _a;
26
+ error = failure;
27
+ publish();
28
+ (_a = options.onError) === null || _a === void 0 ? void 0 : _a.call(options, failure);
29
+ };
30
+ const applySnapshot = (state) => {
31
+ if (state.accountId !== options.accountId) {
32
+ throw new Error('Chat activity snapshot belongs to another account');
33
+ }
34
+ if (!Number.isSafeInteger(state.revision) || state.revision < 0) {
35
+ throw new Error('Chat activity revision must be a nonnegative safe integer');
36
+ }
37
+ if (revision !== undefined && state.revision <= revision)
38
+ return;
39
+ if (Object.values(state.chats).some((chat) => chat.hasUnread && !chat.responseId)) {
40
+ throw new Error('Unread chat activity requires a response identifier');
41
+ }
42
+ activity = createChatActivitySnapshot(Object.fromEntries(Object.entries(state.chats).filter(([id]) => !deletedChats.has(id))));
43
+ revision = state.revision;
44
+ loaded = true;
45
+ publish();
46
+ };
47
+ const refresh = () => {
48
+ if (loadingPromise)
49
+ return loadingPromise;
50
+ if (!options.load)
51
+ return Promise.resolve();
52
+ const load = options.load;
53
+ loadingPromise = Promise.resolve()
54
+ .then(load)
55
+ .then(applySnapshot)
56
+ .catch((cause) => {
57
+ reportError({ operation: 'load', cause });
58
+ throw cause;
59
+ })
60
+ .finally(() => {
61
+ loadingPromise = undefined;
62
+ isLoading = false;
63
+ publish();
64
+ });
65
+ isLoading = true;
66
+ error = undefined;
67
+ publish();
68
+ return loadingPromise;
69
+ };
70
+ if (options.initialState)
71
+ applySnapshot(options.initialState);
72
+ return {
73
+ getSnapshot: () => snapshot,
74
+ subscribe: (listener) => {
75
+ listeners.add(listener);
76
+ return () => {
77
+ listeners.delete(listener);
78
+ };
79
+ },
80
+ load: () => (loaded ? Promise.resolve() : refresh()),
81
+ refresh,
82
+ applySnapshot,
83
+ markResponseViewed: (chatId, responseId) => {
84
+ const current = activity.chats[chatId];
85
+ if (!(current === null || current === void 0 ? void 0 : current.hasUnread) || current.responseId !== responseId)
86
+ return Promise.resolve();
87
+ const key = JSON.stringify([chatId, responseId]);
88
+ const pending = acknowledgements.get(key);
89
+ if (pending)
90
+ return pending;
91
+ const command = Promise.resolve()
92
+ .then(() => {
93
+ if (deletedChats.has(chatId))
94
+ return undefined;
95
+ return options.markResponseViewed(chatId, responseId);
96
+ })
97
+ .then((state) => {
98
+ if (state)
99
+ applySnapshot(state);
100
+ })
101
+ .catch((cause) => {
102
+ if (deletedChats.has(chatId))
103
+ return;
104
+ reportError({ operation: 'markResponseViewed', chatId, responseId, cause });
105
+ throw cause;
106
+ })
107
+ .finally(() => {
108
+ acknowledgements.delete(key);
109
+ });
110
+ acknowledgements.set(key, command);
111
+ error = undefined;
112
+ publish();
113
+ return command;
114
+ },
115
+ deleteChat: (chatId) => {
116
+ deletedChats.add(chatId);
117
+ const chats = Object.assign({}, activity.chats);
118
+ delete chats[chatId];
119
+ activity = createChatActivitySnapshot(chats);
120
+ publish();
121
+ },
122
+ };
123
+ }
124
+ //# sourceMappingURL=remoteChatActivityStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remoteChatActivityStore.js","sourceRoot":"../../../src","sources":["utils/remoteChatActivityStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAIH,mBAAmB,EACnB,0BAA0B,GAC7B,+BAA4B;AAyC7B;;;GAGG;AACH,MAAM,UAAU,6BAA6B,CACzC,OAAuC;IAEvC,IAAI,CAAC,OAAO,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IACxF,IAAI,QAAQ,GAAG,mBAAmB,CAAC;IACnC,IAAI,QAA4B,CAAC;IACjC,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,KAAoC,CAAC;IACzC,IAAI,QAAQ,GAA+B,MAAM,CAAC,MAAM,iCAAK,QAAQ,KAAE,SAAS,IAAE,CAAC;IACnF,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,cAAyC,CAAC;IAC9C,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC1D,8FAA8F;IAC9F,MAAM,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IACvC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAc,CAAC;IACxC,MAAM,OAAO,GAAG,GAAG,EAAE;QACjB,QAAQ,GAAG,MAAM,CAAC,MAAM,iCAAK,QAAQ,KAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAE,CAAC;QACpE,SAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC;IAChD,CAAC,CAAC;IACF,MAAM,WAAW,GAAG,CAAC,OAA0B,EAAE,EAAE;;QAC/C,KAAK,GAAG,OAAO,CAAC;QAChB,OAAO,EAAE,CAAC;QACV,MAAA,OAAO,CAAC,OAAO,wDAAG,OAAO,CAAC,CAAC;IAC/B,CAAC,CAAC;IACF,MAAM,aAAa,GAAG,CAAC,KAA8B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AAK,CAAC,MAAM,CAAC,CAAC;YACrB,QAAQ,GAAG,0BAA0B,CAAC,KAAK,CAAC,CAAC;YAC7C,OAAO,EAAE,CAAC;QACd,CAAC;KACJ,CAAC;AACN,CAAC","sourcesContent":["import {\n type ChatActivityError,\n type ChatActivitySnapshot,\n type ChatActivityStore,\n EMPTY_CHAT_ACTIVITY,\n createChatActivitySnapshot,\n} from './chatActivityStore';\n\n/** Full account-scoped server state. Revisions must increase for every state change. */\nexport interface RemoteChatActivityState {\n readonly accountId: string;\n readonly revision: number;\n readonly chats: ChatActivitySnapshot['chats'];\n}\n\nexport interface RemoteChatActivityStoreOptions {\n accountId: string;\n initialState?: RemoteChatActivityState;\n /** Omit when the application feeds its query cache or pushed updates through applySnapshot. */\n load?: () => Promise<RemoteChatActivityState>;\n /**\n * Acknowledge this exact response. Return authoritative state, or feed it separately through\n * applySnapshot after query invalidation/push. A resolved command alone never clears a dot.\n */\n markResponseViewed: (\n chatId: string,\n responseId: string,\n ) => void | RemoteChatActivityState | Promise<void | RemoteChatActivityState>;\n onError?: (error: ChatActivityError) => void;\n}\n\nexport interface RemoteChatActivitySnapshot extends ChatActivitySnapshot {\n readonly revision?: number;\n readonly isLoading: boolean;\n}\n\nexport interface RemoteChatActivityStore extends ChatActivityStore {\n getSnapshot: () => RemoteChatActivitySnapshot;\n markResponseViewed: (chatId: string, responseId: string) => Promise<void>;\n /** Idempotent initial load; concurrent calls share the same request. */\n load: () => Promise<void>;\n /** Explicit retry/refresh. Rejections are also exposed through error and onError. */\n refresh: () => Promise<void>;\n /** Accept a full authoritative snapshot, ignoring equal or older revisions. */\n applySnapshot: (state: RemoteChatActivityState) => void;\n}\n\n/**\n * Adapts application-provided backend data without running the local generation engine or using\n * localStorage. Keep one instance per account and replace it when the account changes.\n */\nexport function createRemoteChatActivityStore(\n options: RemoteChatActivityStoreOptions,\n): RemoteChatActivityStore {\n if (!options.accountId) throw new Error('Chat activity requires an account identifier');\n let activity = EMPTY_CHAT_ACTIVITY;\n let revision: number | undefined;\n let isLoading = false;\n let error: ChatActivityError | undefined;\n let snapshot: RemoteChatActivitySnapshot = Object.freeze({...activity, isLoading});\n let loaded = false;\n let loadingPromise: Promise<void> | undefined;\n const acknowledgements = new Map<string, Promise<void>>();\n // Chat IDs must not be reused within an account. Tombstones also filter late command results.\n const deletedChats = new Set<string>();\n const listeners = new Set<() => void>();\n const publish = () => {\n snapshot = Object.freeze({...activity, revision, isLoading, error});\n listeners.forEach((listener) => listener());\n };\n const reportError = (failure: ChatActivityError) => {\n error = failure;\n publish();\n options.onError?.(failure);\n };\n const applySnapshot = (state: RemoteChatActivityState) => {\n if (state.accountId !== options.accountId) {\n throw new Error('Chat activity snapshot belongs to another account');\n }\n if (!Number.isSafeInteger(state.revision) || state.revision < 0) {\n throw new Error('Chat activity revision must be a nonnegative safe integer');\n }\n if (revision !== undefined && state.revision <= revision) return;\n if (Object.values(state.chats).some((chat) => chat.hasUnread && !chat.responseId)) {\n throw new Error('Unread chat activity requires a response identifier');\n }\n activity = createChatActivitySnapshot(\n Object.fromEntries(Object.entries(state.chats).filter(([id]) => !deletedChats.has(id))),\n );\n revision = state.revision;\n loaded = true;\n publish();\n };\n const refresh = (): Promise<void> => {\n if (loadingPromise) return loadingPromise;\n if (!options.load) return Promise.resolve();\n const load = options.load;\n loadingPromise = Promise.resolve()\n .then(load)\n .then(applySnapshot)\n .catch((cause: unknown) => {\n reportError({operation: 'load', cause});\n throw cause;\n })\n .finally(() => {\n loadingPromise = undefined;\n isLoading = false;\n publish();\n });\n isLoading = true;\n error = undefined;\n publish();\n return loadingPromise;\n };\n if (options.initialState) applySnapshot(options.initialState);\n return {\n getSnapshot: () => snapshot,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n load: () => (loaded ? Promise.resolve() : refresh()),\n refresh,\n applySnapshot,\n markResponseViewed: (chatId, responseId) => {\n const current = activity.chats[chatId];\n if (!current?.hasUnread || current.responseId !== responseId) return Promise.resolve();\n const key = JSON.stringify([chatId, responseId]);\n const pending = acknowledgements.get(key);\n if (pending) return pending;\n const command = Promise.resolve()\n .then(() => {\n if (deletedChats.has(chatId)) return undefined;\n return options.markResponseViewed(chatId, responseId);\n })\n .then((state) => {\n if (state) applySnapshot(state);\n })\n .catch((cause: unknown) => {\n if (deletedChats.has(chatId)) return;\n reportError({operation: 'markResponseViewed', chatId, responseId, cause});\n throw cause;\n })\n .finally(() => {\n acknowledgements.delete(key);\n });\n acknowledgements.set(key, command);\n error = undefined;\n publish();\n return command;\n },\n deleteChat: (chatId) => {\n deletedChats.add(chatId);\n const chats = {...activity.chats};\n delete chats[chatId];\n activity = createChatActivitySnapshot(chats);\n publish();\n },\n };\n}\n"]}
@@ -0,0 +1,158 @@
1
+ # Chat activity and unread responses
2
+
3
+ AIKit supports both a local generation engine and application-provided server state. The local engine owns generation tracking, unread markers and browser persistence. With a backend, the server owns generation and unread state, and AIKit adapts its snapshots. In both modes, AIKit owns indicator priority and confirms that a specific response is actually visible before requesting an acknowledgement. `ChatContainer` connects the store to `Header`, desktop history and mobile history. Existing consumers remain unchanged until activity is configured.
4
+
5
+ ## Local generation engine
6
+
7
+ ```tsx
8
+ import {createChatActivityStore} from '@gravity-ui/aikit';
9
+
10
+ const activity = createChatActivityStore({accountId: authenticatedAccount.id});
11
+ activity.load();
12
+ ```
13
+
14
+ Keep one stable store for the authenticated account outside the panel's lifecycle. On logout/account change, disconnect the old store and create the next account's store. The account identifier is required and becomes part of the localStorage key. Storage is accessed lazily and creation is safe during server rendering. Optionally pass `storage` implementing `getItem`, `setItem`, `key` and `length`, or `null` for memory-only usage. `onPersistenceError` reports unavailable storage, malformed data and quota failures; activity remains usable in memory.
15
+
16
+ Completed response IDs, per-response viewed markers and request ownership metadata are persisted. Generation activity flags remain in memory. Loading history does not mark old answers unread. Active requests are never persisted: after reload, use current backend request state to resume their lifecycle. Keep the returned handles with the request objects, independently of chat selection. Call `startGeneration` only at dispatch or for a confirmed active request, never for a historical completion. Starting another generation for the same chat supersedes its previous handle.
17
+
18
+ ### Several tabs of the same account
19
+
20
+ Local persistence uses separate account-scoped keys for each chat's request owner, each completed response, each viewed response, and deletion tombstones. Operations read current shared data and write only their own keys; starting a request in another chat never replaces an account-wide snapshot. Acknowledging one response cannot overwrite a newer response, and deletion keeps late completion writes from bringing a chat back. Chat IDs must not be reused after deletion.
21
+
22
+ Subscribed stores refresh on browser `storage` events while preserving their own active requests. A newer dispatch in the same chat or deletion invalidates older local handles. Initial loading never restores an active flag from stored request ownership. Custom storage adapters must enumerate their keys through `key(index)` and `length`; call `load()` to refresh data after an external update when the adapter does not emit browser storage events.
23
+
24
+ Existing version-one account snapshots remain readable as baselines. Per-chat records, viewed markers and tombstones take precedence, and the old account snapshot is never rewritten. Different accounts use different key namespaces. This coordinates browser tabs; it does not synchronize devices.
25
+
26
+ ## Report the complete request lifecycle
27
+
28
+ ```tsx
29
+ const generation = activity.startGeneration(chatId);
30
+ try {
31
+ await runRequest({
32
+ onAssistantText: (response) => {
33
+ updateMessages(chatId, response);
34
+ generation.responseReceived(response.id);
35
+ },
36
+ });
37
+ } finally {
38
+ generation.finish();
39
+ }
40
+ ```
41
+
42
+ Start before waiting for network data. Do not stop tracking during tools, reasoning, inter-chunk pauses or a chat switch. Report `responseReceived` only for nonempty user-visible assistant text, including partial text received before cancellation/error. Tool output, reasoning, errors and cancellation notices do not count as answers. Response IDs must be stable after reload and unique across requests; if your backend reuses message IDs, supply a response revision as the identifier.
43
+
44
+ Call `finish()` on every terminal path: success, cancellation and failure. A terminal event without new text does not create an unread marker; any previous unread marker is retained. Handles ignore output and completion after finish, deletion or a superseding generation. Do not route late events through a newer handle. If the host's transport outlives the panel, it must also keep these handles alive.
45
+
46
+ ## Acknowledge displayed content
47
+
48
+ ```tsx
49
+ <ChatContainer
50
+ {...chatProps}
51
+ chatActivity={{
52
+ store: activity,
53
+ isPanelVisible: panelIsOpen && !panelIsCollapsed,
54
+ renderedResponseId: displayedResponse?.id,
55
+ }}
56
+ />
57
+ ```
58
+
59
+ `renderedResponseId` identifies the latest answer successfully displayed in `activeChat`. Omit it during chat loading or failed rendering. Update the messages and this identifier together. Use the same response revision passed to `responseReceived`. When a request completes in the visible current chat, AIKit acknowledges that exact revision after React commits it. Document visibility is checked automatically and rechecked when the browser tab becomes visible. A collapsed panel must pass `isPanelVisible: false` even if it stays mounted.
60
+
61
+ Opening history, scrolling and selecting a row do not acknowledge anything. A late acknowledgement of an older response cannot clear a newer marker. Opening one chat leaves other markers intact. A new response can mark a previously viewed chat unread again.
62
+
63
+ For custom assistant layouts, use the same `useChatActivity` hook with either store implementation:
64
+
65
+ ```tsx
66
+ const snapshot = useChatActivity(activity, {
67
+ chatId: selectedChat?.id,
68
+ renderedResponseId: displayedResponse?.id,
69
+ isPanelVisible: panelIsVisible,
70
+ });
71
+
72
+ <Header {...headerProps} historyActivity={snapshot} />;
73
+ <History {...historyProps} activityStore={activity} />;
74
+ ```
75
+
76
+ A subscription without the second argument only observes activity; it never acknowledges responses. `Header.historyActivity` also accepts a plain `{isGenerating, hasUnread}` summary. `History` and `HistoryList` accept `activityStore`; no per-row status calculation is needed in the host.
77
+
78
+ ## Server-backed state
79
+
80
+ The component contract `ChatActivityStore` contains `getSnapshot`, `subscribe`, optional `load`, `markResponseViewed` and `deleteChat`. It has no local request lifecycle methods. `createChatActivityStore` returns `LocalChatActivityStore`, which adds `startGeneration`. Components accept either implementation through the same `chatActivity.store` prop.
81
+
82
+ Use `createRemoteChatActivityStore` when the backend owns activity and read markers:
83
+
84
+ ```tsx
85
+ import {createRemoteChatActivityStore} from '@gravity-ui/aikit';
86
+ import type {RemoteChatActivityState} from '@gravity-ui/aikit';
87
+
88
+ // Map the application's transport model into a full account-scoped snapshot.
89
+ const toActivityState = (data: ActivityResponse): RemoteChatActivityState => ({
90
+ accountId: data.accountId,
91
+ revision: data.revision,
92
+ chats: Object.fromEntries(
93
+ data.chats.map((chat) => [
94
+ chat.id,
95
+ {
96
+ isGenerating: chat.requestActive,
97
+ hasUnread: chat.answerUnread,
98
+ responseId: chat.completedResponseId,
99
+ },
100
+ ]),
101
+ ),
102
+ });
103
+
104
+ const activity = createRemoteChatActivityStore({
105
+ accountId: authenticatedAccount.id,
106
+ load: async () => toActivityState(await api.getChatActivity()),
107
+ markResponseViewed: async (chatId, responseId) =>
108
+ toActivityState(await api.markResponseViewed({chatId, responseId})),
109
+ onError: ({operation, cause}) => reportActivityError(operation, cause),
110
+ });
111
+
112
+ // Push messages or polling results can use the same path as request responses.
113
+ const unsubscribe = api.subscribeToChatActivity((data) => {
114
+ activity.applySnapshot(toActivityState(data));
115
+ });
116
+ ```
117
+
118
+ Pass `activity` to `ChatContainer` exactly as in the local example. Do not call `startGeneration`, replay request events or duplicate summary calculations in this mode. AIKit computes the global spinner/unread summary from the supplied chat rows. All server snapshots contain the complete account state; an omitted chat is removed. `getSnapshot()` returns a stable immutable value until the state or request status changes, and the adapter copies incoming rows so caller mutations cannot change an already published snapshot.
119
+
120
+ The transport mapping above is application code: AIKit does not prescribe REST endpoints, request authorization or the backend's DTO shape. The application scopes loaders and subscriptions to the authenticated account, and must unsubscribe old account subscriptions on logout/switch. Create a new adapter per account. Snapshots with a different `accountId` are rejected, and a pending result in the old adapter cannot alter the new account's store.
121
+
122
+ ### Revisions and acknowledgements
123
+
124
+ `revision` is a nonnegative safe integer generated by the backend, monotonically increasing per account whenever activity/read state changes. Equal or older revisions are ignored. Loading, polling, push messages and acknowledgement responses must use the same revision sequence. Do not invent a new revision from a client response's arrival order: an old network response must remain old. An unread completed response must have its own stable `responseId`; the backend must acknowledge that exact ID rather than marking the whole chat read unconditionally.
125
+
126
+ Acknowledgements for the same response are coalesced while pending. The dot stays visible until authoritative server state marks it viewed. Failures preserve the existing snapshot's activity, expose `{operation, cause, chatId?, responseId?}` through `getSnapshot().error` / `useChatActivity(...).error`, call `onError` when provided, and reject the command promise. The hook consumes those rejections and does not continuously retry a failed command on every render. Reopening the panel, returning to the browser tab or explicitly calling `markResponseViewed` can retry the visible response. Late acknowledgements cannot overwrite a newer server revision.
127
+
128
+ `load()` is an idempotent initial load and concurrent loads share a request. Optional `initialState` supplies an already loaded snapshot, including during application hydration. `refresh()` explicitly reloads/retries and exposes `isLoading`. Callers that invoke these async commands themselves must handle their rejections; component hooks already do so.
129
+
130
+ ### Existing query caches and subscriptions
131
+
132
+ If the application already loads server state with a query library or external subscription, omit `load` and feed snapshots through `applySnapshot`. The acknowledgement callback may return no state when query invalidation or push will supply the confirmation later:
133
+
134
+ ```tsx
135
+ const activity = createRemoteChatActivityStore({
136
+ accountId,
137
+ initialState: toActivityState(cachedActivity),
138
+ markResponseViewed: async (chatId, responseId) => {
139
+ await api.markResponseViewed({chatId, responseId});
140
+ await queryClient.invalidateQueries({queryKey: ['chatActivity', accountId]});
141
+ },
142
+ });
143
+
144
+ // Run when the account-scoped query result changes.
145
+ activity.applySnapshot(toActivityState(queryResult));
146
+ ```
147
+
148
+ Resolving an acknowledgement callback without returning state does not optimistically clear the marker. Apply the refreshed query result or pushed confirmation. An existing application store can also implement `ChatActivityStore` directly; use `createChatActivitySnapshot(chats)` to copy its rows and calculate the common summary, then keep that snapshot stable until the underlying data changes. Its async methods should expose/report errors and reject on failure; components handle the promise lifecycle. It does not need `startGeneration` or browser storage.
149
+
150
+ ## Indicators and deletion
151
+
152
+ The history button retains its clock icon and remains clickable. It displays a spinner if any request is active, otherwise a blue dot if any response is unread. Its localized accessible name and tooltip describe both states when both exist. Each row reserves space for a dot before its title and a spinner after it. Generation takes priority within a row without erasing the unread state. The dot has an accessible text alternative and tooltip. History freezes the existing chat order while its popup/sheet is open. Standalone `HistoryList` exposes `preserveOrder` for the same behavior.
153
+
154
+ Successful deletion through `History` clears the chat's activity. For deletion elsewhere, call `activity.deleteChat(chatId)` only after deletion succeeds. For local stores this removes persisted markers and invalidates the request handle. The remote adapter evicts cached state and keeps a tombstone for that ID, filtering even newer in-flight server snapshots that still contain the deleted chat. Chat IDs must not be reused within the account; remote chat deletion itself remains the host's `onDeleteChat` responsibility. In custom rendering flows, `markResponseViewed(chatId, responseId)` is available, but should only be called after that exact response becomes visible.
155
+
156
+ ## Interactive example
157
+
158
+ Storybook's **pages / ChatContainer / Background Activity** provides explicit start/finish controls for two chats and a hidden-panel toggle. Start requests in both chats, finish one in the background, and open history to inspect spinner/dot priority. Complete the remaining request, then open the unread chat. Repeat with a hidden panel or background tab, stop without text, delete a generating chat, and send another response in an already viewed chat.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gravity-ui/aikit",
3
- "version": "3.2.0",
3
+ "version": "3.2.1-beta.62cd303ea62095304bfb52217eb70529a7dbaf96.0",
4
4
  "description": "Gravity UI base kit for building ai assistant chats",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",