@gravity-ui/aikit 2.30.0 → 2.30.1-beta.67e463d2cd48ff4c1e32a2f22503c003d7bcc4e6.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 (115) hide show
  1. package/build/cjs/components/organisms/Header/Header.css +25 -0
  2. package/build/cjs/components/organisms/Header/Header.js +22 -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.css +16 -0
  10. package/build/cjs/components/pages/ChatContainer/ChatContainer.js +21 -10
  11. package/build/cjs/components/pages/ChatContainer/ChatContainer.js.map +1 -1
  12. package/build/cjs/components/pages/ChatContainer/types.d.ts +9 -0
  13. package/build/cjs/components/pages/ChatContainer/types.js.map +1 -1
  14. package/build/cjs/components/pages/ChatContainer/useChatExport.js +46 -17
  15. package/build/cjs/components/pages/ChatContainer/useChatExport.js.map +1 -1
  16. package/build/cjs/components/pages/ChatContainer/useChatExportFeedbackPosition.d.ts +3 -0
  17. package/build/cjs/components/pages/ChatContainer/useChatExportFeedbackPosition.js +35 -0
  18. package/build/cjs/components/pages/ChatContainer/useChatExportFeedbackPosition.js.map +1 -0
  19. package/build/cjs/components/templates/History/ChatItem.d.ts +4 -1
  20. package/build/cjs/components/templates/History/ChatItem.js +2 -2
  21. package/build/cjs/components/templates/History/ChatItem.js.map +1 -1
  22. package/build/cjs/components/templates/History/History.css +14 -0
  23. package/build/cjs/components/templates/History/History.js +1 -1
  24. package/build/cjs/components/templates/History/History.js.map +1 -1
  25. package/build/cjs/components/templates/History/HistoryList.d.ts +5 -0
  26. package/build/cjs/components/templates/History/HistoryList.js +17 -5
  27. package/build/cjs/components/templates/History/HistoryList.js.map +1 -1
  28. package/build/cjs/components/templates/History/i18n/en.json +3 -1
  29. package/build/cjs/components/templates/History/i18n/index.d.ts +4 -4
  30. package/build/cjs/components/templates/History/i18n/ru.json +3 -1
  31. package/build/cjs/hooks/index.d.ts +1 -0
  32. package/build/cjs/hooks/index.js +1 -0
  33. package/build/cjs/hooks/index.js.map +1 -1
  34. package/build/cjs/hooks/useChatActivity.d.ts +10 -0
  35. package/build/cjs/hooks/useChatActivity.js +52 -0
  36. package/build/cjs/hooks/useChatActivity.js.map +1 -0
  37. package/build/cjs/package.json +1 -1
  38. package/build/cjs/utils/chatActivity/chatActivityPersistence.d.ts +25 -0
  39. package/build/cjs/utils/chatActivity/chatActivityPersistence.js +202 -0
  40. package/build/cjs/utils/chatActivity/chatActivityPersistence.js.map +1 -0
  41. package/build/cjs/utils/chatActivity/chatActivityStore.d.ts +59 -0
  42. package/build/cjs/utils/chatActivity/chatActivityStore.js +119 -0
  43. package/build/cjs/utils/chatActivity/chatActivityStore.js.map +1 -0
  44. package/build/cjs/utils/chatActivity/index.d.ts +2 -0
  45. package/build/cjs/utils/chatActivity/index.js +7 -0
  46. package/build/cjs/utils/chatActivity/index.js.map +1 -0
  47. package/build/cjs/utils/chatActivity/remoteChatActivityStore.d.ts +38 -0
  48. package/build/cjs/utils/chatActivity/remoteChatActivityStore.js +137 -0
  49. package/build/cjs/utils/chatActivity/remoteChatActivityStore.js.map +1 -0
  50. package/build/cjs/utils/chatMarkdown.js +101 -2
  51. package/build/cjs/utils/chatMarkdown.js.map +1 -1
  52. package/build/cjs/utils/index.d.ts +1 -0
  53. package/build/cjs/utils/index.js +1 -0
  54. package/build/cjs/utils/index.js.map +1 -1
  55. package/build/docs/INDEX.md +1 -0
  56. package/build/docs/components/organisms/Header.md +5 -0
  57. package/build/docs/components/pages/ChatContainer.md +16 -4
  58. package/build/docs/components/templates/History.md +6 -0
  59. package/build/docs/guides/chat-activity.md +160 -0
  60. package/build/esm/components/organisms/Header/Header.css +25 -0
  61. package/build/esm/components/organisms/Header/Header.js +23 -3
  62. package/build/esm/components/organisms/Header/Header.js.map +1 -1
  63. package/build/esm/components/organisms/Header/i18n/en.json +4 -1
  64. package/build/esm/components/organisms/Header/i18n/index.d.ts +4 -4
  65. package/build/esm/components/organisms/Header/i18n/ru.json +4 -1
  66. package/build/esm/components/organisms/Header/types.d.ts +3 -0
  67. package/build/esm/components/organisms/Header/types.js.map +1 -1
  68. package/build/esm/components/pages/ChatContainer/ChatContainer.css +16 -0
  69. package/build/esm/components/pages/ChatContainer/ChatContainer.js +22 -11
  70. package/build/esm/components/pages/ChatContainer/ChatContainer.js.map +1 -1
  71. package/build/esm/components/pages/ChatContainer/types.d.ts +9 -0
  72. package/build/esm/components/pages/ChatContainer/types.js.map +1 -1
  73. package/build/esm/components/pages/ChatContainer/useChatExport.js +47 -18
  74. package/build/esm/components/pages/ChatContainer/useChatExport.js.map +1 -1
  75. package/build/esm/components/pages/ChatContainer/useChatExportFeedbackPosition.d.ts +3 -0
  76. package/build/esm/components/pages/ChatContainer/useChatExportFeedbackPosition.js +32 -0
  77. package/build/esm/components/pages/ChatContainer/useChatExportFeedbackPosition.js.map +1 -0
  78. package/build/esm/components/templates/History/ChatItem.d.ts +4 -1
  79. package/build/esm/components/templates/History/ChatItem.js +3 -3
  80. package/build/esm/components/templates/History/ChatItem.js.map +1 -1
  81. package/build/esm/components/templates/History/History.css +14 -0
  82. package/build/esm/components/templates/History/History.js +1 -1
  83. package/build/esm/components/templates/History/History.js.map +1 -1
  84. package/build/esm/components/templates/History/HistoryList.d.ts +5 -0
  85. package/build/esm/components/templates/History/HistoryList.js +17 -5
  86. package/build/esm/components/templates/History/HistoryList.js.map +1 -1
  87. package/build/esm/components/templates/History/i18n/en.json +3 -1
  88. package/build/esm/components/templates/History/i18n/index.d.ts +4 -4
  89. package/build/esm/components/templates/History/i18n/ru.json +3 -1
  90. package/build/esm/hooks/index.d.ts +1 -0
  91. package/build/esm/hooks/index.js +1 -0
  92. package/build/esm/hooks/index.js.map +1 -1
  93. package/build/esm/hooks/useChatActivity.d.ts +10 -0
  94. package/build/esm/hooks/useChatActivity.js +49 -0
  95. package/build/esm/hooks/useChatActivity.js.map +1 -0
  96. package/build/esm/package.json +1 -1
  97. package/build/esm/utils/chatActivity/chatActivityPersistence.d.ts +25 -0
  98. package/build/esm/utils/chatActivity/chatActivityPersistence.js +199 -0
  99. package/build/esm/utils/chatActivity/chatActivityPersistence.js.map +1 -0
  100. package/build/esm/utils/chatActivity/chatActivityStore.d.ts +59 -0
  101. package/build/esm/utils/chatActivity/chatActivityStore.js +114 -0
  102. package/build/esm/utils/chatActivity/chatActivityStore.js.map +1 -0
  103. package/build/esm/utils/chatActivity/index.d.ts +2 -0
  104. package/build/esm/utils/chatActivity/index.js +4 -0
  105. package/build/esm/utils/chatActivity/index.js.map +1 -0
  106. package/build/esm/utils/chatActivity/remoteChatActivityStore.d.ts +38 -0
  107. package/build/esm/utils/chatActivity/remoteChatActivityStore.js +134 -0
  108. package/build/esm/utils/chatActivity/remoteChatActivityStore.js.map +1 -0
  109. package/build/esm/utils/chatMarkdown.js +101 -2
  110. package/build/esm/utils/chatMarkdown.js.map +1 -1
  111. package/build/esm/utils/index.d.ts +1 -0
  112. package/build/esm/utils/index.js +1 -0
  113. package/build/esm/utils/index.js.map +1 -1
  114. package/docs/chat-activity.md +160 -0
  115. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remoteChatActivityStore.js","sourceRoot":"../../../../src","sources":["utils/chatActivity/remoteChatActivityStore.ts"],"names":[],"mappings":";;AAmDA,sEAkIC;AArLD,8DAM6B;AAyC7B;;;GAGG;AACH,SAAgB,6BAA6B,CACzC,OAAuC;IAEvC,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IACpE,CAAC;IACD,IAAI,QAAQ,GA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Content":["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) {\n throw new Error('Chat activity requires an account identifier');\n }\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) {\n return;\n }\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) {\n return loadingPromise;\n }\n if (!options.load) {\n return Promise.resolve();\n }\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) {\n applySnapshot(options.initialState);\n }\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) {\n return Promise.resolve();\n }\n const key = JSON.stringify([chatId, responseId]);\n const pending = acknowledgements.get(key);\n if (pending) {\n return pending;\n }\n const command = Promise.resolve()\n .then(() => {\n if (deletedChats.has(chatId)) {\n return undefined;\n }\n return options.markResponseViewed(chatId, responseId);\n })\n .then((state) => {\n if (state) {\n applySnapshot(state);\n }\n })\n .catch((cause: unknown) => {\n if (deletedChats.has(chatId)) {\n return;\n }\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"]}
@@ -3,6 +3,103 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getMessageMarkdown = getMessageMarkdown;
4
4
  exports.serializeChatMarkdown = serializeChatMarkdown;
5
5
  exports.downloadChatMarkdown = downloadChatMarkdown;
6
+ const marked_1 = require("marked");
7
+ function escapeMarkdownSyntax(text) {
8
+ return text.replace(/&/g, '&amp;').replace(/[\\`*_{}[\]()<>#+.!|~-]/g, '\\$&');
9
+ }
10
+ function escapePlainText(text) {
11
+ let cursor = 0;
12
+ let result = '';
13
+ for (const match of text.matchAll(/(?:https?:\/\/|www\.)[^\s<>]+/gi)) {
14
+ const token = marked_1.Lexer.lexInline(match[0])[0];
15
+ if ((token === null || token === void 0 ? void 0 : token.type) !== 'link')
16
+ continue;
17
+ const offset = match.index;
18
+ const href = token.href.replace(/&/g, '&amp;').replace(/</g, '%3C').replace(/>/g, '%3E');
19
+ result += escapeMarkdownSyntax(text.slice(cursor, offset));
20
+ result += `[${escapeMarkdownSyntax(token.raw)}](<${href}>)`;
21
+ cursor = offset + token.raw.length;
22
+ }
23
+ return result + escapeMarkdownSyntax(text.slice(cursor));
24
+ }
25
+ function rewriteChildren(raw, tokens, rewrite) {
26
+ let cursor = 0;
27
+ let result = '';
28
+ for (const token of tokens) {
29
+ const offset = raw.indexOf(token.raw, cursor);
30
+ if (offset < 0)
31
+ continue;
32
+ result += raw.slice(cursor, offset) + rewrite(token);
33
+ cursor = offset + token.raw.length;
34
+ }
35
+ return result + raw.slice(cursor);
36
+ }
37
+ function closeCodeFence(raw) {
38
+ const fence = raw.match(/^ {0,3}(`{3,}|~{3,})/);
39
+ if (!fence)
40
+ return raw;
41
+ const closing = new RegExp(`\\n {0,3}${fence[1][0]}{${fence[1].length},}[ \\t]*(?:\\n)?$`);
42
+ return closing.test(raw) ? raw : `${raw}\n${fence[1]}\n`;
43
+ }
44
+ /** Resolve references per message before joining independent Markdown documents. */
45
+ function isolateMarkdown(markdown) {
46
+ const rewrite = (token) => {
47
+ var _a, _b, _c, _d, _e, _f;
48
+ if (token.type === 'def')
49
+ return '';
50
+ if ((token.type === 'link' || token.type === 'image') &&
51
+ /^!?\[/.test(token.raw) &&
52
+ token.raw.endsWith(']')) {
53
+ const href = token.href
54
+ .replace(/</g, '%3C')
55
+ .replace(/>/g, '%3E')
56
+ .replace(/\s/g, encodeURIComponent);
57
+ const title = token.title
58
+ ? ` "${token.title.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
59
+ : '';
60
+ return `${token.type === 'image' ? '!' : ''}[${token.text}](<${href}>${title})`;
61
+ }
62
+ if (token.type === 'code') {
63
+ return closeCodeFence(token.raw);
64
+ }
65
+ if (token.type === 'blockquote') {
66
+ const text = ((_a = token.tokens) !== null && _a !== void 0 ? _a : []).map(rewrite).join('');
67
+ return text === token.text
68
+ ? token.raw
69
+ : text
70
+ .split('\n')
71
+ .map((line) => `> ${line}`)
72
+ .join('\n') + '\n';
73
+ }
74
+ if (token.type === 'list')
75
+ return rewriteChildren(token.raw, token.items, rewrite);
76
+ if (token.type === 'list_item') {
77
+ const text = ((_b = token.tokens) !== null && _b !== void 0 ? _b : []).map(rewrite).join('');
78
+ if (text === token.text)
79
+ return token.raw;
80
+ const prefix = (_d = (_c = token.raw.match(/^\s*(?:[-+*]|\d+[.)])\s+/)) === null || _c === void 0 ? void 0 : _c[0]) !== null && _d !== void 0 ? _d : '- ';
81
+ const checkbox = token.task ? `[${token.checked ? 'x' : ' '}] ` : '';
82
+ const trailingNewlines = (_f = (_e = token.raw.match(/\n+$/)) === null || _e === void 0 ? void 0 : _e[0]) !== null && _f !== void 0 ? _f : '';
83
+ const body = text.replace(/\n+$/, '');
84
+ return (prefix +
85
+ checkbox +
86
+ body.split('\n').join(`\n${' '.repeat(prefix.length)}`) +
87
+ trailingNewlines);
88
+ }
89
+ if (token.type === 'table') {
90
+ return rewriteChildren(token.raw, [...token.header, ...token.rows.flat()].map((cell) => ({
91
+ type: 'text',
92
+ raw: cell.text,
93
+ text: cell.text,
94
+ tokens: cell.tokens,
95
+ })), rewrite);
96
+ }
97
+ return 'tokens' in token && token.tokens
98
+ ? rewriteChildren(token.raw, token.tokens, rewrite)
99
+ : token.raw;
100
+ };
101
+ return marked_1.Lexer.lex(markdown).map(rewrite).join('');
102
+ }
6
103
  /** Extract public text only. Thinking, tool payloads and unknown content are excluded by default. */
7
104
  function getMessageMarkdown(message, options = {}) {
8
105
  var _a, _b, _c;
@@ -11,7 +108,9 @@ function getMessageMarkdown(message, options = {}) {
11
108
  }
12
109
  const parts = [];
13
110
  if (typeof message.content === 'string') {
14
- parts.push(message.content);
111
+ parts.push(message.role === 'user' && message.format !== 'markdown'
112
+ ? escapePlainText(message.content)
113
+ : message.content);
15
114
  }
16
115
  else {
17
116
  const content = Array.isArray(message.content) ? message.content : [message.content];
@@ -50,7 +149,7 @@ function serializeChatMarkdown(messages, options = {}) {
50
149
  const labels = (_a = options.roleLabels) !== null && _a !== void 0 ? _a : { user: 'User', assistant: 'Assistant' };
51
150
  return messages
52
151
  .flatMap((message) => {
53
- const text = getMessageMarkdown(message, options);
152
+ const text = isolateMarkdown(getMessageMarkdown(message, options));
54
153
  return text ? [`## ${labels[message.role]}\n\n${text}`] : [];
55
154
  })
56
155
  .join('\n\n');
@@ -1 +1 @@
1
- {"version":3,"file":"chatMarkdown.js","sourceRoot":"../../../src","sources":["utils/chatMarkdown.ts"],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E,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACjE,CAAC,CAAC;SACD,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC;AAED,SAAgB,oBAAoB,CAAC,QAAgB,EAAE,QAAQ,GAAG,SAAS;IACvE,MAAM,GAAG,GAAG,GAAG,CAAC,eAAe,CAAC,IAAI,IAAI,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAC,IAAI,EAAE,6BAA6B,EAAC,CAAC,CAAC,CAAC;IAC7F,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;IACzC,IAAI,CAAC;QACD,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;QAChB,4CAA4C;QAC5C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,qBAAqB,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;QAC1F,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAChC,IAAI,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;YAAS,CAAC;QACP,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,2EAA2E;QAC3E,UAAU,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IAClD,CAAC;AACL,CAAC","sourcesContent":["import type {TChatMessage, TMessageContent} from '../types/messages';\n\nexport interface ChatMarkdownOptions {\n /** Localized role labels used in Markdown headings. */\n roleLabels?: {user: string; assistant: string};\n /** Return only user-visible Markdown for custom content; never serialize raw payloads. */\n getContentMarkdown?: (\n content: TMessageContent,\n message: TChatMessage<TMessageContent>,\n ) => string | undefined;\n}\n\n/** Extract public text only. Thinking, tool payloads and unknown content are excluded by default. */\nexport function getMessageMarkdown(\n message: TChatMessage<TMessageContent>,\n options: ChatMarkdownOptions = {},\n): string {\n if (message.role !== 'user' && message.role !== 'assistant') {\n return '';\n }\n const parts: string[] = [];\n if (typeof message.content === 'string') {\n parts.push(message.content);\n } else {\n const content = Array.isArray(message.content) ? message.content : [message.content];\n for (const item of content) {\n if (item.type === 'text') {\n if (\n typeof item.data === 'object' &&\n item.data !== null &&\n 'text' in item.data &&\n typeof item.data.text === 'string'\n ) {\n parts.push(item.data.text);\n }\n } else if (item.type !== 'thinking' && item.type !== 'tool') {\n const text = options.getContentMarkdown?.(item, message);\n if (text) parts.push(text);\n }\n }\n }\n if (message.role === 'user') {\n for (const file of message.fileAttachments ?? []) {\n parts.push(file.name.replace(/[\\\\`*_{}[\\]()<>#+.!|~-]/g, '\\\\$&'));\n }\n for (const image of message.images ?? []) {\n // Inline image data can be large and is not a portable attachment link.\n if (/^https?:\\/\\//i.test(image)) {\n parts.push(\n `<${image.replace(/</g, '%3C').replace(/>/g, '%3E').replace(/\\s/g, encodeURIComponent)}>`,\n );\n }\n }\n }\n return parts.filter((part) => part.trim()).join('\\n\\n');\n}\n\n/** Preserve source order and Markdown, without reading rendered or virtualized DOM content. */\nexport function serializeChatMarkdown(\n messages: readonly TChatMessage<TMessageContent>[],\n options: ChatMarkdownOptions = {},\n): string {\n const labels = options.roleLabels ?? {user: 'User', assistant: 'Assistant'};\n return messages\n .flatMap((message) => {\n const text = getMessageMarkdown(message, options);\n return text ? [`## ${labels[message.role]}\\n\\n${text}`] : [];\n })\n .join('\\n\\n');\n}\n\nexport function downloadChatMarkdown(markdown: string, filename = 'chat.md'): void {\n const url = URL.createObjectURL(new Blob([markdown], {type: 'text/markdown;charset=utf-8'}));\n const link = document.createElement('a');\n try {\n link.href = url;\n // eslint-disable-next-line no-control-regex\n link.download = filename.replace(/[\\\\/\\u0000-\\u001f]/g, '_').replace(/(?:\\.md)?$/, '.md');\n document.body.appendChild(link);\n link.click();\n } finally {\n link.remove();\n // Allow the browser to start consuming the object URL before releasing it.\n setTimeout(() => URL.revokeObjectURL(url), 0);\n }\n}\n"]}
1
+ {"version":3,"file":"chatMarkdown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C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,qBAAqB,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;QAC1F,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAChC,IAAI,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;YAAS,CAAC;QACP,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,2EAA2E;QAC3E,UAAU,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IAClD,CAAC;AACL,CAAC","sourcesContent":["import {Lexer, type Token} from 'marked';\n\nimport type {TChatMessage, TMessageContent} from '../types/messages';\n\nexport interface ChatMarkdownOptions {\n /** Localized role labels used in Markdown headings. */\n roleLabels?: {user: string; assistant: string};\n /** Return only user-visible Markdown for custom content; never serialize raw payloads. */\n getContentMarkdown?: (\n content: TMessageContent,\n message: TChatMessage<TMessageContent>,\n ) => string | undefined;\n}\n\nfunction escapeMarkdownSyntax(text: string): string {\n return text.replace(/&/g, '&amp;').replace(/[\\\\`*_{}[\\]()<>#+.!|~-]/g, '\\\\$&');\n}\n\nfunction escapePlainText(text: string): string {\n let cursor = 0;\n let result = '';\n for (const match of text.matchAll(/(?:https?:\\/\\/|www\\.)[^\\s<>]+/gi)) {\n const token = Lexer.lexInline(match[0])[0];\n if (token?.type !== 'link') continue;\n const offset = match.index;\n const href = token.href.replace(/&/g, '&amp;').replace(/</g, '%3C').replace(/>/g, '%3E');\n result += escapeMarkdownSyntax(text.slice(cursor, offset));\n result += `[${escapeMarkdownSyntax(token.raw)}](<${href}>)`;\n cursor = offset + token.raw.length;\n }\n return result + escapeMarkdownSyntax(text.slice(cursor));\n}\n\nfunction rewriteChildren(raw: string, tokens: Token[], rewrite: (token: Token) => string): string {\n let cursor = 0;\n let result = '';\n for (const token of tokens) {\n const offset = raw.indexOf(token.raw, cursor);\n if (offset < 0) continue;\n result += raw.slice(cursor, offset) + rewrite(token);\n cursor = offset + token.raw.length;\n }\n return result + raw.slice(cursor);\n}\n\nfunction closeCodeFence(raw: string): string {\n const fence = raw.match(/^ {0,3}(`{3,}|~{3,})/);\n if (!fence) return raw;\n const closing = new RegExp(`\\\\n {0,3}${fence[1][0]}{${fence[1].length},}[ \\\\t]*(?:\\\\n)?$`);\n return closing.test(raw) ? raw : `${raw}\\n${fence[1]}\\n`;\n}\n\n/** Resolve references per message before joining independent Markdown documents. */\nfunction isolateMarkdown(markdown: string): string {\n const rewrite = (token: Token): string => {\n if (token.type === 'def') return '';\n if (\n (token.type === 'link' || token.type === 'image') &&\n /^!?\\[/.test(token.raw) &&\n token.raw.endsWith(']')\n ) {\n const href = token.href\n .replace(/</g, '%3C')\n .replace(/>/g, '%3E')\n .replace(/\\s/g, encodeURIComponent);\n const title = token.title\n ? ` \"${token.title.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`\n : '';\n return `${token.type === 'image' ? '!' : ''}[${token.text}](<${href}>${title})`;\n }\n if (token.type === 'code') {\n return closeCodeFence(token.raw);\n }\n if (token.type === 'blockquote') {\n const text = (token.tokens ?? []).map(rewrite).join('');\n return text === token.text\n ? token.raw\n : text\n .split('\\n')\n .map((line) => `> ${line}`)\n .join('\\n') + '\\n';\n }\n if (token.type === 'list') return rewriteChildren(token.raw, token.items, rewrite);\n if (token.type === 'list_item') {\n const text = (token.tokens ?? []).map(rewrite).join('');\n if (text === token.text) return token.raw;\n const prefix = token.raw.match(/^\\s*(?:[-+*]|\\d+[.)])\\s+/)?.[0] ?? '- ';\n const checkbox = token.task ? `[${token.checked ? 'x' : ' '}] ` : '';\n const trailingNewlines = token.raw.match(/\\n+$/)?.[0] ?? '';\n const body = text.replace(/\\n+$/, '');\n return (\n prefix +\n checkbox +\n body.split('\\n').join(`\\n${' '.repeat(prefix.length)}`) +\n trailingNewlines\n );\n }\n if (token.type === 'table') {\n return rewriteChildren(\n token.raw,\n [...token.header, ...token.rows.flat()].map((cell) => ({\n type: 'text',\n raw: cell.text,\n text: cell.text,\n tokens: cell.tokens,\n })),\n rewrite,\n );\n }\n return 'tokens' in token && token.tokens\n ? rewriteChildren(token.raw, token.tokens, rewrite)\n : token.raw;\n };\n return Lexer.lex(markdown).map(rewrite).join('');\n}\n\n/** Extract public text only. Thinking, tool payloads and unknown content are excluded by default. */\nexport function getMessageMarkdown(\n message: TChatMessage<TMessageContent>,\n options: ChatMarkdownOptions = {},\n): string {\n if (message.role !== 'user' && message.role !== 'assistant') {\n return '';\n }\n const parts: string[] = [];\n if (typeof message.content === 'string') {\n parts.push(\n message.role === 'user' && message.format !== 'markdown'\n ? escapePlainText(message.content)\n : message.content,\n );\n } else {\n const content = Array.isArray(message.content) ? message.content : [message.content];\n for (const item of content) {\n if (item.type === 'text') {\n if (\n typeof item.data === 'object' &&\n item.data !== null &&\n 'text' in item.data &&\n typeof item.data.text === 'string'\n ) {\n parts.push(item.data.text);\n }\n } else if (item.type !== 'thinking' && item.type !== 'tool') {\n const text = options.getContentMarkdown?.(item, message);\n if (text) parts.push(text);\n }\n }\n }\n if (message.role === 'user') {\n for (const file of message.fileAttachments ?? []) {\n parts.push(file.name.replace(/[\\\\`*_{}[\\]()<>#+.!|~-]/g, '\\\\$&'));\n }\n for (const image of message.images ?? []) {\n // Inline image data can be large and is not a portable attachment link.\n if (/^https?:\\/\\//i.test(image)) {\n parts.push(\n `<${image.replace(/</g, '%3C').replace(/>/g, '%3E').replace(/\\s/g, encodeURIComponent)}>`,\n );\n }\n }\n }\n return parts.filter((part) => part.trim()).join('\\n\\n');\n}\n\n/** Preserve source order and Markdown, without reading rendered or virtualized DOM content. */\nexport function serializeChatMarkdown(\n messages: readonly TChatMessage<TMessageContent>[],\n options: ChatMarkdownOptions = {},\n): string {\n const labels = options.roleLabels ?? {user: 'User', assistant: 'Assistant'};\n return messages\n .flatMap((message) => {\n const text = isolateMarkdown(getMessageMarkdown(message, options));\n return text ? [`## ${labels[message.role]}\\n\\n${text}`] : [];\n })\n .join('\\n\\n');\n}\n\nexport function downloadChatMarkdown(markdown: string, filename = 'chat.md'): void {\n const url = URL.createObjectURL(new Blob([markdown], {type: 'text/markdown;charset=utf-8'}));\n const link = document.createElement('a');\n try {\n link.href = url;\n // eslint-disable-next-line no-control-regex\n link.download = filename.replace(/[\\\\/\\u0000-\\u001f]/g, '_').replace(/(?:\\.md)?$/, '.md');\n document.body.appendChild(link);\n link.click();\n } finally {\n link.remove();\n // Allow the browser to start consuming the object URL before releasing it.\n setTimeout(() => URL.revokeObjectURL(url), 0);\n }\n}\n"]}
@@ -7,4 +7,5 @@ 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 "./chatActivity/index.js";
10
11
  export * from "./chatMarkdown.js";
@@ -11,5 +11,6 @@ tslib_1.__exportStar(require("./aiAgentContext/index.js"), exports);
11
11
  tslib_1.__exportStar(require("./toolset/index.js"), exports);
12
12
  tslib_1.__exportStar(require("./mascot.js"), exports);
13
13
  tslib_1.__exportStar(require("./pinnedChatsStore.js"), exports);
14
+ tslib_1.__exportStar(require("./chatActivity/index.js"), exports);
14
15
  tslib_1.__exportStar(require("./chatMarkdown.js"), exports);
15
16
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"../../../src","sources":["utils/index.ts"],"names":[],"mappings":";;;AAAA,mBAAmB;AACnB,yDAA4B;AAC5B,4DAA+B;AAC/B,0DAA6B;AAC7B,mEAAsC;AACtC,8DAAiC;AACjC,oEAAiC;AACjC,6DAA0B;AAC1B,sDAAyB;AACzB,gEAAmC;AACnC,4DAA+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,yDAA4B;AAC5B,4DAA+B;AAC/B,0DAA6B;AAC7B,mEAAsC;AACtC,8DAAiC;AACjC,oEAAiC;AACjC,6DAA0B;AAC1B,sDAAyB;AACzB,gEAAmC;AACnC,kEAA+B;AAC/B,4DAA+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 './chatActivity';\nexport * from './chatMarkdown';\n"]}
@@ -72,6 +72,7 @@ function App() {
72
72
  - [AIKit Library Architecture](./guides/ARCHITECTURE.md)
73
73
  - [AIKit Project Structure](./guides/PROJECT_STRUCTURE.md) — This document describes the layout of the @gravity-ui/aikit source tree.
74
74
  - [AIKit Themer](./guides/THEMER.md) — Open Theming → Themer → Playground in AIKit Storybook to edit a theme alongside a live AIKit chat. The editor uses the same @gravity-ui/uikit-themer generator as Gravity Themer and UIKit's current Storybook theme importer, with UIKit controls and chroma-js color validation.
75
+ - [Chat activity and unread responses](./guides/chat-activity.md) — 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.
75
76
  - [Code Style and Language Requirements](./guides/guidelines/code-style.md) — CRITICAL: All code documentation, comments, and JSDoc must be written in English.
76
77
  - [Components](./guides/COMPONENTS.md) — 49 components organized by Atomic Design level. Each component lives in src/components/<level>/<Name>/ and ships with its own README and Storybook stories.
77
78
  - [Documentation](./guides/README.md) — This directory contains all @gravity-ui/aikit documentation.
@@ -385,6 +385,7 @@ In mobile mode additional actions open in a `Sheet`. Its metrics are variables,
385
385
  | `actionQa` | `Partial<Record<HeaderAction, string>>` | - | - | Overrides `data-qa` for base actions (default `header-action-${id}`) |
386
386
  | `actionTooltipTexts` | `HeaderActionTooltipTexts` | - | - | Overrides tooltip texts for base actions |
387
387
  | `className` | `string` | - | - | Additional CSS class |
388
+ | `historyActivity` | `ChatActivitySnapshot` | - | - | Shared activity summary for the history action. |
388
389
 
389
390
  ### HeaderAction
390
391
 
@@ -423,3 +424,7 @@ Built-in actions, the menu, and additional actions can be placed on either side
423
424
  ```
424
425
 
425
426
  Unspecified groups and actions remain on the right.
427
+
428
+ ## Chat activity
429
+
430
+ See the [chat activity integration guide](../../guides/chat-activity.md) for request lifecycle, persistence and visibility handling.
@@ -447,6 +447,7 @@ Use the `texts` prop with type `ChatContainerTexts` for a **flat** API over user
447
447
  | `contentClassName` | `string` | - | - | Additional CSS class for content section |
448
448
  | `footerClassName` | `string` | - | - | Additional CSS class for footer section |
449
449
  | `qa` | `string \| ChatContainerQa` | - | - | QA/test identifiers: string = root only; object = map or `prefix` (see **QA**) |
450
+ | `chatActivity` | `ChatContainerProps['chatActivity']` | - | - | Shared activity and visibility of the response actually rendered for the selected chat. |
450
451
 
451
452
  ## Types
452
453
 
@@ -1029,7 +1030,9 @@ function App() {
1029
1030
 
1030
1031
  while (true) {
1031
1032
  const {done, value} = await reader!.read();
1032
- if (done) break;
1033
+ if (done) {
1034
+ break;
1035
+ }
1033
1036
 
1034
1037
  const chunk = decoder.decode(value);
1035
1038
  assistantMessage.content += chunk;
@@ -1388,6 +1391,7 @@ and selecting individual messages:
1388
1391
  activeChat={chat}
1389
1392
  messages={allMessages}
1390
1393
  status={status}
1394
+ onSendMessage={sendMessage}
1391
1395
  chatExport={{loading: isHistoryLoading, filename: 'conversation.md'}}
1392
1396
  />
1393
1397
  ```
@@ -1407,7 +1411,8 @@ older pages. Export is disabled for empty conversations and while a response is
1407
1411
  being generated. Keep `activeChat.id` stable and unique per conversation so pending
1408
1412
  clipboard results and message selection remain scoped to the originating chat.
1409
1413
 
1410
- Source Markdown is preserved. System messages, reasoning, tool calls, metadata,
1414
+ Markdown formatting is preserved; plain user messages are escaped. Open code fences
1415
+ are closed at message boundaries, and reference links keep their own destinations. System messages, reasoning, tool calls, metadata,
1411
1416
  and unknown content are excluded. File attachment names and HTTP(S) image links
1412
1417
  are included; inline image data and private attachment IDs are omitted. For custom
1413
1418
  cards, use `getContentMarkdown` to return their user-visible title, result, and link.
@@ -1415,9 +1420,12 @@ Do not return raw card payloads or private metadata. Built-in reasoning and tool
1415
1420
  content never invoke this callback.
1416
1421
 
1417
1422
  Copy and download feedback is localized in English and Russian and appears in the
1418
- chat or the selection dialog. Clipboard failures leave the action available for retry.
1423
+ bottom-right corner of the chat, above its content and the selection dialog. Clipboard failures leave the action available for retry.
1419
1424
  The same actions use the header's mobile menu on small screens. Updating message
1420
- history closes the selection dialog to prevent exporting a different selection.
1425
+ content or order closes the selection dialog to prevent exporting a different selection.
1426
+ Recreating an equivalent message array preserves the selection. Custom serializers run
1427
+ only when opening the message picker or exporting. Failed previews fall back to
1428
+ built-in text; exporting a failing message reports the serializer error.
1421
1429
 
1422
1430
  For custom integrations, `getMessageMarkdown`, `serializeChatMarkdown`,
1423
1431
  `downloadChatMarkdown`, and `ChatMarkdownOptions` are available from the package
@@ -1457,3 +1465,7 @@ Results are discarded after changing conversations, disabling export, or unmount
1457
1465
  Download success means the browser download was initiated, not that the file was saved.
1458
1466
  Notification callbacks should handle their own errors; they do not change the export
1459
1467
  outcome or leave the action pending.
1468
+
1469
+ ## Chat activity
1470
+
1471
+ See the [chat activity integration guide](../../guides/chat-activity.md) for request lifecycle, persistence and visibility handling.
@@ -195,6 +195,8 @@ are independent, so results from an old account cannot update the new store.
195
195
  | `showSheetTitle` | `boolean` | - | `true` | Show the mobile sheet title (stays in `aria-label`) |
196
196
  | `modal` | `boolean` | - | `true` | Keep the keyboard focus inside the desktop popup |
197
197
  | `initialFocus` | `PopupProps['initialFocus']` | - | - | Element to focus when the desktop popup opens |
198
+ | `activityStore` | `ChatActivityStore` | - | - | Shared activity and deletion cleanup. |
199
+ | `preserveOrder` | `boolean` | - | `false` | Freeze row order in standalone HistoryList. |
198
200
 
199
201
  Without an explicit `size` the list is `m` on desktop and `xl` in mobile mode, and the row delete
200
202
  button follows it: `s` on desktop, `xl` with a `20px` icon on mobile, so a row keeps a comfortable
@@ -568,3 +570,7 @@ The following types are exported from `@gravity-ui/aikit`:
568
570
  - **DateHeaderItem**: Date group header (exported from History)
569
571
  - **Header**: May contain the History trigger button
570
572
  - **PromptBox**: Often used alongside History in chat interfaces
573
+
574
+ ## Chat activity
575
+
576
+ See the [chat activity integration guide](../../guides/chat-activity.md) for request lifecycle, persistence and visibility handling.
@@ -0,0 +1,160 @@
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
+ The store module architecture describes file responsibilities, local persistence keys, cross-tab coordination, and the server adapter.
6
+
7
+ ## Local generation engine
8
+
9
+ ```tsx
10
+ import {createChatActivityStore} from '@gravity-ui/aikit';
11
+
12
+ const activity = createChatActivityStore({accountId: authenticatedAccount.id});
13
+ activity.load();
14
+ ```
15
+
16
+ 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.
17
+
18
+ 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.
19
+
20
+ ### Several tabs of the same account
21
+
22
+ 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.
23
+
24
+ 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.
25
+
26
+ 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.
27
+
28
+ ## Report the complete request lifecycle
29
+
30
+ ```tsx
31
+ const generation = activity.startGeneration(chatId);
32
+ try {
33
+ await runRequest({
34
+ onAssistantText: (response) => {
35
+ updateMessages(chatId, response);
36
+ generation.responseReceived(response.id);
37
+ },
38
+ });
39
+ } finally {
40
+ generation.finish();
41
+ }
42
+ ```
43
+
44
+ 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.
45
+
46
+ 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.
47
+
48
+ ## Acknowledge displayed content
49
+
50
+ ```tsx
51
+ <ChatContainer
52
+ {...chatProps}
53
+ chatActivity={{
54
+ store: activity,
55
+ isPanelVisible: panelIsOpen && !panelIsCollapsed,
56
+ renderedResponseId: displayedResponse?.id,
57
+ }}
58
+ />
59
+ ```
60
+
61
+ `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.
62
+
63
+ 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.
64
+
65
+ For custom assistant layouts, use the same `useChatActivity` hook with either store implementation:
66
+
67
+ ```tsx
68
+ const snapshot = useChatActivity(activity, {
69
+ chatId: selectedChat?.id,
70
+ renderedResponseId: displayedResponse?.id,
71
+ isPanelVisible: panelIsVisible,
72
+ });
73
+
74
+ <Header {...headerProps} historyActivity={snapshot} />;
75
+ <History {...historyProps} activityStore={activity} />;
76
+ ```
77
+
78
+ 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.
79
+
80
+ ## Server-backed state
81
+
82
+ 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.
83
+
84
+ Use `createRemoteChatActivityStore` when the backend owns activity and read markers:
85
+
86
+ ```tsx
87
+ import {createRemoteChatActivityStore} from '@gravity-ui/aikit';
88
+ import type {RemoteChatActivityState} from '@gravity-ui/aikit';
89
+
90
+ // Map the application's transport model into a full account-scoped snapshot.
91
+ const toActivityState = (data: ActivityResponse): RemoteChatActivityState => ({
92
+ accountId: data.accountId,
93
+ revision: data.revision,
94
+ chats: Object.fromEntries(
95
+ data.chats.map((chat) => [
96
+ chat.id,
97
+ {
98
+ isGenerating: chat.requestActive,
99
+ hasUnread: chat.answerUnread,
100
+ responseId: chat.completedResponseId,
101
+ },
102
+ ]),
103
+ ),
104
+ });
105
+
106
+ const activity = createRemoteChatActivityStore({
107
+ accountId: authenticatedAccount.id,
108
+ load: async () => toActivityState(await api.getChatActivity()),
109
+ markResponseViewed: async (chatId, responseId) =>
110
+ toActivityState(await api.markResponseViewed({chatId, responseId})),
111
+ onError: ({operation, cause}) => reportActivityError(operation, cause),
112
+ });
113
+
114
+ // Push messages or polling results can use the same path as request responses.
115
+ const unsubscribe = api.subscribeToChatActivity((data) => {
116
+ activity.applySnapshot(toActivityState(data));
117
+ });
118
+ ```
119
+
120
+ 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.
121
+
122
+ 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.
123
+
124
+ ### Revisions and acknowledgements
125
+
126
+ `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.
127
+
128
+ 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.
129
+
130
+ `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.
131
+
132
+ ### Existing query caches and subscriptions
133
+
134
+ 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:
135
+
136
+ ```tsx
137
+ const activity = createRemoteChatActivityStore({
138
+ accountId,
139
+ initialState: toActivityState(cachedActivity),
140
+ markResponseViewed: async (chatId, responseId) => {
141
+ await api.markResponseViewed({chatId, responseId});
142
+ await queryClient.invalidateQueries({queryKey: ['chatActivity', accountId]});
143
+ },
144
+ });
145
+
146
+ // Run when the account-scoped query result changes.
147
+ activity.applySnapshot(toActivityState(queryResult));
148
+ ```
149
+
150
+ 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.
151
+
152
+ ## Indicators and deletion
153
+
154
+ 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.
155
+
156
+ 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.
157
+
158
+ ## Interactive example
159
+
160
+ 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.
@@ -7,6 +7,31 @@
7
7
  box-sizing: border-box;
8
8
  background: var(--g-aikit-header-background);
9
9
  }
10
+ .g-aikit-header__action-icon {
11
+ position: relative;
12
+ display: inline-flex;
13
+ }
14
+ .g-aikit-header__activity {
15
+ position: absolute;
16
+ top: -6px;
17
+ right: -8px;
18
+ display: flex;
19
+ width: 12px;
20
+ height: 12px;
21
+ align-items: center;
22
+ justify-content: center;
23
+ }
24
+ .g-aikit-header__activity-spinner {
25
+ width: 12px;
26
+ height: 12px;
27
+ flex-shrink: 0;
28
+ }
29
+ .g-aikit-header__unread-dot {
30
+ width: 8px;
31
+ height: 8px;
32
+ border-radius: 50%;
33
+ background: var(--g-color-text-info);
34
+ }
10
35
  .g-aikit-header__icon {
11
36
  display: flex;
12
37
  align-items: center;
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import React, { useCallback, useMemo, useState } from 'react';
3
3
  import { ChevronsCollapseUpRight, ChevronsExpandUpRight, ClockArrowRotateLeft, Ellipsis, Plus, Sparkles, Xmark, } from '@gravity-ui/icons';
4
- import { DropdownMenu, Icon, Menu, Sheet, Text, useUniqId } from '@gravity-ui/uikit';
4
+ import { Button, DropdownMenu, Icon, Menu, Sheet, Spin, Text, useUniqId } from '@gravity-ui/uikit';
5
5
  import { getControlIconSize } from "../../../hooks/useMobileControlSize.js";
6
6
  import { isActionConfig } from "../../../utils/actionUtils.js";
7
7
  import { block } from "../../../utils/cn.js";
@@ -36,6 +36,7 @@ function getNormalizedMenuItem(item, menuItemQa) {
36
36
  */
37
37
  export function Header(props) {
38
38
  const { title, preview, icon, baseActions, additionalActions, actionsPlacement, actionsOrder, actionSize, isMobile, actionIcons, menuItems, menuButtonTooltip, menuButtonIcon, menuButtonQa, menuItemQa, showSheetTitle, titlePosition, withIcon, showTitle = true, className, historyButtonRef, qa, actionQa, actionTooltipTexts, } = useHeader(props);
39
+ const historyActivity = props.historyActivity;
39
40
  const [isMenuSheetVisible, setIsMenuSheetVisible] = useState(false);
40
41
  const menuSheetId = useUniqId();
41
42
  const iconSize = getControlIconSize(actionSize);
@@ -65,8 +66,27 @@ export function Header(props) {
65
66
  }
66
67
  // Determine ref for history button
67
68
  const buttonRef = action.id === HeaderAction.History ? ref : undefined;
68
- return (_jsx(ActionButton, { ref: buttonRef, tooltipTitle: tooltipOverride !== null && tooltipOverride !== void 0 ? tooltipOverride : i18n(tooltipKey), size: actionSize, view: "flat", onClick: action.onClick, className: b('action-button'), qa: (_c = actionQa === null || actionQa === void 0 ? void 0 : actionQa[action.id]) !== null && _c !== void 0 ? _c : `header-action-${action.id}`, children: _jsx(Icon, { data: IconComponent, size: iconSize }) }, action.id));
69
- }, [actionIcons, actionQa, actionSize, actionTooltipTexts, iconSize]);
69
+ const isHistory = actionId === HeaderAction.History;
70
+ let activityText;
71
+ if (isHistory && historyActivity) {
72
+ if (historyActivity.isGenerating) {
73
+ activityText = i18n('activity-generating');
74
+ if (historyActivity.hasUnread) {
75
+ activityText = i18n('activity-generating-unread');
76
+ }
77
+ }
78
+ else if (historyActivity.hasUnread) {
79
+ activityText = i18n('activity-unread');
80
+ }
81
+ }
82
+ const label = [
83
+ tooltipOverride !== null && tooltipOverride !== void 0 ? tooltipOverride : i18n(tooltipKey),
84
+ activityText,
85
+ ]
86
+ .filter(Boolean)
87
+ .join('. ');
88
+ return (_jsx(ActionButton, { ref: buttonRef, tooltipTitle: label, "aria-label": label, size: actionSize, view: "flat", onClick: action.onClick, className: b('action-button'), qa: (_c = actionQa === null || actionQa === void 0 ? void 0 : actionQa[action.id]) !== null && _c !== void 0 ? _c : `header-action-${action.id}`, children: _jsx(Button.Icon, { children: _jsxs("span", { className: b('action-icon'), children: [_jsx(Icon, { data: IconComponent, size: iconSize }), isHistory && historyActivity && (_jsxs("span", { className: b('activity'), "aria-hidden": true, children: [historyActivity.isGenerating && (_jsx(Spin, { size: "xs", className: b('activity-spinner') })), !historyActivity.isGenerating && historyActivity.hasUnread && (_jsx("span", { className: b('unread-dot') }))] }))] }) }) }, action.id));
89
+ }, [actionIcons, actionQa, actionSize, actionTooltipTexts, historyActivity, iconSize]);
70
90
  // Render additional action
71
91
  const renderAdditionalAction = useCallback((action, index) => {
72
92
  var _a;