@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.
- package/build/cjs/components/organisms/Header/Header.css +25 -0
- package/build/cjs/components/organisms/Header/Header.js +21 -2
- package/build/cjs/components/organisms/Header/Header.js.map +1 -1
- package/build/cjs/components/organisms/Header/i18n/en.json +4 -1
- package/build/cjs/components/organisms/Header/i18n/index.d.ts +4 -4
- package/build/cjs/components/organisms/Header/i18n/ru.json +4 -1
- package/build/cjs/components/organisms/Header/types.d.ts +3 -0
- package/build/cjs/components/organisms/Header/types.js.map +1 -1
- package/build/cjs/components/pages/ChatContainer/ChatContainer.js +18 -9
- package/build/cjs/components/pages/ChatContainer/ChatContainer.js.map +1 -1
- package/build/cjs/components/pages/ChatContainer/types.d.ts +9 -0
- package/build/cjs/components/pages/ChatContainer/types.js.map +1 -1
- package/build/cjs/components/templates/History/ChatItem.d.ts +4 -1
- package/build/cjs/components/templates/History/ChatItem.js +2 -2
- package/build/cjs/components/templates/History/ChatItem.js.map +1 -1
- package/build/cjs/components/templates/History/History.css +14 -0
- package/build/cjs/components/templates/History/History.js +1 -1
- package/build/cjs/components/templates/History/History.js.map +1 -1
- package/build/cjs/components/templates/History/HistoryList.d.ts +5 -0
- package/build/cjs/components/templates/History/HistoryList.js +14 -4
- package/build/cjs/components/templates/History/HistoryList.js.map +1 -1
- package/build/cjs/components/templates/History/i18n/en.json +3 -1
- package/build/cjs/components/templates/History/i18n/index.d.ts +4 -4
- package/build/cjs/components/templates/History/i18n/ru.json +3 -1
- package/build/cjs/hooks/index.d.ts +1 -0
- package/build/cjs/hooks/index.js +1 -0
- package/build/cjs/hooks/index.js.map +1 -1
- package/build/cjs/hooks/useChatActivity.d.ts +10 -0
- package/build/cjs/hooks/useChatActivity.js +51 -0
- package/build/cjs/hooks/useChatActivity.js.map +1 -0
- package/build/cjs/package.json +1 -1
- package/build/cjs/utils/chatActivityPersistence.d.ts +21 -0
- package/build/cjs/utils/chatActivityPersistence.js +186 -0
- package/build/cjs/utils/chatActivityPersistence.js.map +1 -0
- package/build/cjs/utils/chatActivityStore.d.ts +59 -0
- package/build/cjs/utils/chatActivityStore.js +112 -0
- package/build/cjs/utils/chatActivityStore.js.map +1 -0
- package/build/cjs/utils/index.d.ts +2 -0
- package/build/cjs/utils/index.js +2 -0
- package/build/cjs/utils/index.js.map +1 -1
- package/build/cjs/utils/remoteChatActivityStore.d.ts +38 -0
- package/build/cjs/utils/remoteChatActivityStore.js +127 -0
- package/build/cjs/utils/remoteChatActivityStore.js.map +1 -0
- package/build/docs/INDEX.md +1 -0
- package/build/docs/components/organisms/Header.md +5 -0
- package/build/docs/components/pages/ChatContainer.md +5 -0
- package/build/docs/components/templates/History.md +6 -0
- package/build/docs/guides/chat-activity.md +158 -0
- package/build/esm/components/organisms/Header/Header.css +25 -0
- package/build/esm/components/organisms/Header/Header.js +22 -3
- package/build/esm/components/organisms/Header/Header.js.map +1 -1
- package/build/esm/components/organisms/Header/i18n/en.json +4 -1
- package/build/esm/components/organisms/Header/i18n/index.d.ts +4 -4
- package/build/esm/components/organisms/Header/i18n/ru.json +4 -1
- package/build/esm/components/organisms/Header/types.d.ts +3 -0
- package/build/esm/components/organisms/Header/types.js.map +1 -1
- package/build/esm/components/pages/ChatContainer/ChatContainer.js +18 -9
- package/build/esm/components/pages/ChatContainer/ChatContainer.js.map +1 -1
- package/build/esm/components/pages/ChatContainer/types.d.ts +9 -0
- package/build/esm/components/pages/ChatContainer/types.js.map +1 -1
- package/build/esm/components/templates/History/ChatItem.d.ts +4 -1
- package/build/esm/components/templates/History/ChatItem.js +3 -3
- package/build/esm/components/templates/History/ChatItem.js.map +1 -1
- package/build/esm/components/templates/History/History.css +14 -0
- package/build/esm/components/templates/History/History.js +1 -1
- package/build/esm/components/templates/History/History.js.map +1 -1
- package/build/esm/components/templates/History/HistoryList.d.ts +5 -0
- package/build/esm/components/templates/History/HistoryList.js +14 -4
- package/build/esm/components/templates/History/HistoryList.js.map +1 -1
- package/build/esm/components/templates/History/i18n/en.json +3 -1
- package/build/esm/components/templates/History/i18n/index.d.ts +4 -4
- package/build/esm/components/templates/History/i18n/ru.json +3 -1
- package/build/esm/hooks/index.d.ts +1 -0
- package/build/esm/hooks/index.js +1 -0
- package/build/esm/hooks/index.js.map +1 -1
- package/build/esm/hooks/useChatActivity.d.ts +10 -0
- package/build/esm/hooks/useChatActivity.js +48 -0
- package/build/esm/hooks/useChatActivity.js.map +1 -0
- package/build/esm/package.json +1 -1
- package/build/esm/utils/chatActivityPersistence.d.ts +21 -0
- package/build/esm/utils/chatActivityPersistence.js +183 -0
- package/build/esm/utils/chatActivityPersistence.js.map +1 -0
- package/build/esm/utils/chatActivityStore.d.ts +59 -0
- package/build/esm/utils/chatActivityStore.js +107 -0
- package/build/esm/utils/chatActivityStore.js.map +1 -0
- package/build/esm/utils/index.d.ts +2 -0
- package/build/esm/utils/index.js +2 -0
- package/build/esm/utils/index.js.map +1 -1
- package/build/esm/utils/remoteChatActivityStore.d.ts +38 -0
- package/build/esm/utils/remoteChatActivityStore.js +124 -0
- package/build/esm/utils/remoteChatActivityStore.js.map +1 -0
- package/docs/chat-activity.md +158 -0
- package/package.json +1 -1
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EMPTY_CHAT_ACTIVITY = void 0;
|
|
4
|
+
exports.createChatActivitySnapshot = createChatActivitySnapshot;
|
|
5
|
+
exports.createChatActivityStore = createChatActivityStore;
|
|
6
|
+
const chatActivityPersistence_1 = require("./chatActivityPersistence.js");
|
|
7
|
+
exports.EMPTY_CHAT_ACTIVITY = Object.freeze({
|
|
8
|
+
chats: Object.freeze({}),
|
|
9
|
+
isGenerating: false,
|
|
10
|
+
hasUnread: false,
|
|
11
|
+
});
|
|
12
|
+
/** Normalize immutable rows and derive the history summary for local or external stores. */
|
|
13
|
+
function createChatActivitySnapshot(chats) {
|
|
14
|
+
const rows = Object.fromEntries(Object.entries(chats).map(([id, chat]) => [id, Object.freeze(Object.assign({}, chat))]));
|
|
15
|
+
const values = Object.values(rows);
|
|
16
|
+
return Object.freeze({
|
|
17
|
+
chats: Object.freeze(rows),
|
|
18
|
+
isGenerating: values.some((chat) => chat.isGenerating),
|
|
19
|
+
hasUnread: values.some((chat) => chat.hasUnread),
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Create once per account, outside the panel's lifecycle. Persist response/read markers and request
|
|
24
|
+
* ownership, but keep generation activity in memory. Restore live requests from the backend with
|
|
25
|
+
* startGeneration; history loading must
|
|
26
|
+
* never replay completion events. Response IDs must be unique across requests and stable on reload.
|
|
27
|
+
*/
|
|
28
|
+
function createChatActivityStore(options) {
|
|
29
|
+
if (!options.accountId)
|
|
30
|
+
throw new Error('Chat activity requires an account identifier');
|
|
31
|
+
const persistence = (0, chatActivityPersistence_1.createChatActivityPersistence)(options);
|
|
32
|
+
let snapshot = exports.EMPTY_CHAT_ACTIVITY;
|
|
33
|
+
const listeners = new Set();
|
|
34
|
+
const generations = new Map();
|
|
35
|
+
const load = () => {
|
|
36
|
+
var _a, _b;
|
|
37
|
+
const { chats, requestIds } = persistence.readState();
|
|
38
|
+
const activities = new Map(Object.entries(chats).map(([id, response]) => [id, Object.assign(Object.assign({}, response), { isGenerating: false })]));
|
|
39
|
+
for (const [chatId, id] of generations) {
|
|
40
|
+
if (requestIds.get(chatId) === id) {
|
|
41
|
+
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 }));
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
generations.delete(chatId);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
snapshot = createChatActivitySnapshot(Object.fromEntries(activities));
|
|
48
|
+
listeners.forEach((listener) => listener());
|
|
49
|
+
};
|
|
50
|
+
const handleStorage = (event) => {
|
|
51
|
+
if (persistence.isStorageEvent(event))
|
|
52
|
+
load();
|
|
53
|
+
};
|
|
54
|
+
return {
|
|
55
|
+
getSnapshot: () => snapshot,
|
|
56
|
+
subscribe: (listener) => {
|
|
57
|
+
if (!listeners.size && typeof window !== 'undefined') {
|
|
58
|
+
window.addEventListener('storage', handleStorage);
|
|
59
|
+
}
|
|
60
|
+
listeners.add(listener);
|
|
61
|
+
return () => {
|
|
62
|
+
listeners.delete(listener);
|
|
63
|
+
if (!listeners.size && typeof window !== 'undefined') {
|
|
64
|
+
window.removeEventListener('storage', handleStorage);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
},
|
|
68
|
+
load,
|
|
69
|
+
startGeneration: (chatId) => {
|
|
70
|
+
load();
|
|
71
|
+
const id = Array.from(crypto.getRandomValues(new Uint32Array(4)), (value) => value.toString(36)).join('-');
|
|
72
|
+
let responseId;
|
|
73
|
+
if (!persistence.isDeleted(chatId)) {
|
|
74
|
+
const current = snapshot.chats[chatId];
|
|
75
|
+
persistence.start(chatId, id, (current === null || current === void 0 ? void 0 : current.responseId) === undefined
|
|
76
|
+
? undefined
|
|
77
|
+
: { responseId: current.responseId, hasUnread: current.hasUnread });
|
|
78
|
+
generations.set(chatId, id);
|
|
79
|
+
load();
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
responseReceived: (response) => {
|
|
83
|
+
if (generations.get(chatId) === id && response)
|
|
84
|
+
responseId = response;
|
|
85
|
+
},
|
|
86
|
+
finish: () => {
|
|
87
|
+
load();
|
|
88
|
+
if (generations.get(chatId) !== id)
|
|
89
|
+
return;
|
|
90
|
+
generations.delete(chatId);
|
|
91
|
+
if (responseId !== undefined)
|
|
92
|
+
persistence.finish(chatId, id, responseId);
|
|
93
|
+
load();
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
},
|
|
97
|
+
markResponseViewed: (chatId, responseId) => {
|
|
98
|
+
load();
|
|
99
|
+
const current = snapshot.chats[chatId];
|
|
100
|
+
if ((current === null || current === void 0 ? void 0 : current.hasUnread) && current.responseId === responseId) {
|
|
101
|
+
persistence.markViewed(chatId, responseId);
|
|
102
|
+
load();
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
deleteChat: (chatId) => {
|
|
106
|
+
persistence.deleteChat(chatId);
|
|
107
|
+
generations.delete(chatId);
|
|
108
|
+
load();
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
//# sourceMappingURL=chatActivityStore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chatActivityStore.js","sourceRoot":"../../../src","sources":["utils/chatActivityStore.ts"],"names":[],"mappings":";;;AAiEA,gEAYC;AAQD,0DAwFC;AA7KD,0EAAwE;AA0D3D,QAAA,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,4FAA4F;AAC5F,SAAgB,0BAA0B,CACtC,KAAoC;IAEpC,MAAM,IAAI,GAAG,MAAM,CAAC,WAAW,CAC3B,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,MAAM,CAAC,MAAM,mBAAK,IAAI,EAAE,CAAC,CAAC,CAC5E,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACnC,OAAO,MAAM,CAAC,MAAM,CAAC;QACjB,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC;QAC1B,YAAY,EAAE,MAAM,CAAC,IAA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,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";
|
package/build/cjs/utils/index.js
CHANGED
|
@@ -11,5 +11,7 @@ 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("./chatActivityStore.js"), exports);
|
|
15
|
+
tslib_1.__exportStar(require("./remoteChatActivityStore.js"), exports);
|
|
14
16
|
tslib_1.__exportStar(require("./chatMarkdown.js"), exports);
|
|
15
17
|
//# 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,iEAAoC;AACpC,uEAA0C;AAC1C,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 './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,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createRemoteChatActivityStore = createRemoteChatActivityStore;
|
|
4
|
+
const chatActivityStore_1 = require("./chatActivityStore.js");
|
|
5
|
+
/**
|
|
6
|
+
* Adapts application-provided backend data without running the local generation engine or using
|
|
7
|
+
* localStorage. Keep one instance per account and replace it when the account changes.
|
|
8
|
+
*/
|
|
9
|
+
function createRemoteChatActivityStore(options) {
|
|
10
|
+
if (!options.accountId)
|
|
11
|
+
throw new Error('Chat activity requires an account identifier');
|
|
12
|
+
let activity = chatActivityStore_1.EMPTY_CHAT_ACTIVITY;
|
|
13
|
+
let revision;
|
|
14
|
+
let isLoading = false;
|
|
15
|
+
let error;
|
|
16
|
+
let snapshot = Object.freeze(Object.assign(Object.assign({}, activity), { isLoading }));
|
|
17
|
+
let loaded = false;
|
|
18
|
+
let loadingPromise;
|
|
19
|
+
const acknowledgements = new Map();
|
|
20
|
+
// Chat IDs must not be reused within an account. Tombstones also filter late command results.
|
|
21
|
+
const deletedChats = new Set();
|
|
22
|
+
const listeners = new Set();
|
|
23
|
+
const publish = () => {
|
|
24
|
+
snapshot = Object.freeze(Object.assign(Object.assign({}, activity), { revision, isLoading, error }));
|
|
25
|
+
listeners.forEach((listener) => listener());
|
|
26
|
+
};
|
|
27
|
+
const reportError = (failure) => {
|
|
28
|
+
var _a;
|
|
29
|
+
error = failure;
|
|
30
|
+
publish();
|
|
31
|
+
(_a = options.onError) === null || _a === void 0 ? void 0 : _a.call(options, failure);
|
|
32
|
+
};
|
|
33
|
+
const applySnapshot = (state) => {
|
|
34
|
+
if (state.accountId !== options.accountId) {
|
|
35
|
+
throw new Error('Chat activity snapshot belongs to another account');
|
|
36
|
+
}
|
|
37
|
+
if (!Number.isSafeInteger(state.revision) || state.revision < 0) {
|
|
38
|
+
throw new Error('Chat activity revision must be a nonnegative safe integer');
|
|
39
|
+
}
|
|
40
|
+
if (revision !== undefined && state.revision <= revision)
|
|
41
|
+
return;
|
|
42
|
+
if (Object.values(state.chats).some((chat) => chat.hasUnread && !chat.responseId)) {
|
|
43
|
+
throw new Error('Unread chat activity requires a response identifier');
|
|
44
|
+
}
|
|
45
|
+
activity = (0, chatActivityStore_1.createChatActivitySnapshot)(Object.fromEntries(Object.entries(state.chats).filter(([id]) => !deletedChats.has(id))));
|
|
46
|
+
revision = state.revision;
|
|
47
|
+
loaded = true;
|
|
48
|
+
publish();
|
|
49
|
+
};
|
|
50
|
+
const refresh = () => {
|
|
51
|
+
if (loadingPromise)
|
|
52
|
+
return loadingPromise;
|
|
53
|
+
if (!options.load)
|
|
54
|
+
return Promise.resolve();
|
|
55
|
+
const load = options.load;
|
|
56
|
+
loadingPromise = Promise.resolve()
|
|
57
|
+
.then(load)
|
|
58
|
+
.then(applySnapshot)
|
|
59
|
+
.catch((cause) => {
|
|
60
|
+
reportError({ operation: 'load', cause });
|
|
61
|
+
throw cause;
|
|
62
|
+
})
|
|
63
|
+
.finally(() => {
|
|
64
|
+
loadingPromise = undefined;
|
|
65
|
+
isLoading = false;
|
|
66
|
+
publish();
|
|
67
|
+
});
|
|
68
|
+
isLoading = true;
|
|
69
|
+
error = undefined;
|
|
70
|
+
publish();
|
|
71
|
+
return loadingPromise;
|
|
72
|
+
};
|
|
73
|
+
if (options.initialState)
|
|
74
|
+
applySnapshot(options.initialState);
|
|
75
|
+
return {
|
|
76
|
+
getSnapshot: () => snapshot,
|
|
77
|
+
subscribe: (listener) => {
|
|
78
|
+
listeners.add(listener);
|
|
79
|
+
return () => {
|
|
80
|
+
listeners.delete(listener);
|
|
81
|
+
};
|
|
82
|
+
},
|
|
83
|
+
load: () => (loaded ? Promise.resolve() : refresh()),
|
|
84
|
+
refresh,
|
|
85
|
+
applySnapshot,
|
|
86
|
+
markResponseViewed: (chatId, responseId) => {
|
|
87
|
+
const current = activity.chats[chatId];
|
|
88
|
+
if (!(current === null || current === void 0 ? void 0 : current.hasUnread) || current.responseId !== responseId)
|
|
89
|
+
return Promise.resolve();
|
|
90
|
+
const key = JSON.stringify([chatId, responseId]);
|
|
91
|
+
const pending = acknowledgements.get(key);
|
|
92
|
+
if (pending)
|
|
93
|
+
return pending;
|
|
94
|
+
const command = Promise.resolve()
|
|
95
|
+
.then(() => {
|
|
96
|
+
if (deletedChats.has(chatId))
|
|
97
|
+
return undefined;
|
|
98
|
+
return options.markResponseViewed(chatId, responseId);
|
|
99
|
+
})
|
|
100
|
+
.then((state) => {
|
|
101
|
+
if (state)
|
|
102
|
+
applySnapshot(state);
|
|
103
|
+
})
|
|
104
|
+
.catch((cause) => {
|
|
105
|
+
if (deletedChats.has(chatId))
|
|
106
|
+
return;
|
|
107
|
+
reportError({ operation: 'markResponseViewed', chatId, responseId, cause });
|
|
108
|
+
throw cause;
|
|
109
|
+
})
|
|
110
|
+
.finally(() => {
|
|
111
|
+
acknowledgements.delete(key);
|
|
112
|
+
});
|
|
113
|
+
acknowledgements.set(key, command);
|
|
114
|
+
error = undefined;
|
|
115
|
+
publish();
|
|
116
|
+
return command;
|
|
117
|
+
},
|
|
118
|
+
deleteChat: (chatId) => {
|
|
119
|
+
deletedChats.add(chatId);
|
|
120
|
+
const chats = Object.assign({}, activity.chats);
|
|
121
|
+
delete chats[chatId];
|
|
122
|
+
activity = (0, chatActivityStore_1.createChatActivitySnapshot)(chats);
|
|
123
|
+
publish();
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=remoteChatActivityStore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remoteChatActivityStore.js","sourceRoot":"../../../src","sources":["utils/rem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;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"]}
|
package/build/docs/INDEX.md
CHANGED
|
@@ -77,6 +77,7 @@ function App() {
|
|
|
77
77
|
- [AIKit Library Architecture](./guides/ARCHITECTURE.md)
|
|
78
78
|
- [AIKit Project Structure](./guides/PROJECT_STRUCTURE.md) — This document describes the layout of the @gravity-ui/aikit source tree.
|
|
79
79
|
- [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.
|
|
80
|
+
- [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.
|
|
80
81
|
- [Code Style and Language Requirements](./guides/guidelines/code-style.md) — CRITICAL: All code documentation, comments, and JSDoc must be written in English.
|
|
81
82
|
- [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.
|
|
82
83
|
- [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
|
|
|
@@ -1457,3 +1458,7 @@ Results are discarded after changing conversations, disabling export, or unmount
|
|
|
1457
1458
|
Download success means the browser download was initiated, not that the file was saved.
|
|
1458
1459
|
Notification callbacks should handle their own errors; they do not change the export
|
|
1459
1460
|
outcome or leave the action pending.
|
|
1461
|
+
|
|
1462
|
+
## Chat activity
|
|
1463
|
+
|
|
1464
|
+
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,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.
|
|
@@ -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;
|