@datagrok/grokky 1.0.4 → 1.1.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 (203) hide show
  1. package/.claude/skills/deploy-grokky/SKILL.md +193 -0
  2. package/.grokignore +2 -0
  3. package/.turbo/turbo-build.log +24 -0
  4. package/.vscode/settings.json +16 -0
  5. package/CHANGELOG.md +151 -8
  6. package/CLAUDE.md +284 -0
  7. package/CREDITS.md +173 -0
  8. package/LICENSE.md +16 -0
  9. package/README.md +24 -0
  10. package/bdd/bdd.config.json +1 -0
  11. package/bdd/bindings/elements.ts +9 -0
  12. package/bdd/bindings/steps.ts +787 -0
  13. package/bdd/features/ai-panel/platform-work.feature +63 -0
  14. package/bdd/features/ai-panel/session.feature +69 -0
  15. package/bdd/features/ai-panel/table-work.feature +99 -0
  16. package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
  17. package/bdd/generated/ai-panel/session.test.ts +100 -0
  18. package/bdd/generated/ai-panel/table-work.test.ts +150 -0
  19. package/bdd/package.json +1 -0
  20. package/bdd/tsconfig.json +13 -0
  21. package/css/ai.css +637 -49
  22. package/dist/package-test.js +4 -1707
  23. package/dist/package-test.js.map +1 -1
  24. package/dist/package.js +742 -92317
  25. package/dist/package.js.map +1 -1
  26. package/dockerfiles/claude-runtime/.dockerignore +1 -0
  27. package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
  28. package/dockerfiles/claude-runtime/Dockerfile +73 -13
  29. package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
  30. package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
  31. package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
  32. package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
  33. package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
  34. package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
  35. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
  36. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
  37. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
  38. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
  39. package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
  40. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
  41. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
  42. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
  43. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
  44. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
  45. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
  46. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
  47. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
  48. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
  49. package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
  50. package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
  51. package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
  52. package/dockerfiles/claude-runtime/container.json +2 -2
  53. package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
  54. package/dockerfiles/claude-runtime/package-lock.json +1721 -306
  55. package/dockerfiles/claude-runtime/package.json +20 -5
  56. package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
  57. package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
  58. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
  59. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
  60. package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
  61. package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
  62. package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
  63. package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
  64. package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
  65. package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
  66. package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
  67. package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
  68. package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
  69. package/dockerfiles/claude-runtime/pyproject.toml +18 -0
  70. package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
  71. package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
  72. package/dockerfiles/claude-runtime/src/constants.ts +20 -0
  73. package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
  74. package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
  75. package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
  76. package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
  77. package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
  78. package/dockerfiles/claude-runtime/src/server.ts +134 -234
  79. package/dockerfiles/claude-runtime/src/session.ts +328 -0
  80. package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
  81. package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
  82. package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
  83. package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
  84. package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
  85. package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
  86. package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
  87. package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
  88. package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
  89. package/dockerfiles/claude-runtime/src/types.ts +142 -23
  90. package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
  91. package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
  92. package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
  93. package/dockerfiles/claude-runtime/src/verify.ts +136 -0
  94. package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
  95. package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
  96. package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
  97. package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
  98. package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
  99. package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
  100. package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
  101. package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
  102. package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
  103. package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
  104. package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
  105. package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
  106. package/dockerfiles/mcp-server/.eslintrc.json +39 -0
  107. package/dockerfiles/mcp-server/Dockerfile +10 -2
  108. package/dockerfiles/mcp-server/package-lock.json +1743 -98
  109. package/dockerfiles/mcp-server/package.json +27 -5
  110. package/dockerfiles/mcp-server/src/api-client.ts +123 -66
  111. package/dockerfiles/mcp-server/src/format.ts +51 -0
  112. package/dockerfiles/mcp-server/src/index.ts +44 -113
  113. package/dockerfiles/mcp-server/src/ops.ts +325 -0
  114. package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
  115. package/dockerfiles/mcp-server/test/format.test.js +62 -0
  116. package/dockerfiles/mcp-server/test/ops.test.js +84 -0
  117. package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
  118. package/dockerfiles/queue/Dockerfile +2 -0
  119. package/dockerfiles/queue/container.json +7 -0
  120. package/docs/AUDIT-2026-08-03.md +1064 -0
  121. package/docs/BENCHMARK.md +292 -0
  122. package/docs/CLAUDE_CODE_FLOW.md +746 -0
  123. package/docs/EXAMPLES.md +82 -0
  124. package/docs/FEATURES.md +71 -0
  125. package/docs/IMPLEMENTATION.md +128 -0
  126. package/docs/LATENCY.md +170 -0
  127. package/docs/VISION.md +36 -0
  128. package/files/benchmark/suite.yaml +404 -0
  129. package/files/scripts/process-cro-results.md +14 -0
  130. package/files/suggestions.yaml +344 -0
  131. package/package.json +39 -97
  132. package/src/ai/ai-window.ts +157 -0
  133. package/src/ai/benchmark/benchmark.ts +737 -0
  134. package/src/ai/db-view-functions.ts +56 -0
  135. package/src/ai/engine.ts +98 -0
  136. package/src/ai/gemma-engine.ts +81 -0
  137. package/src/ai/panel.ts +1385 -0
  138. package/src/ai/prompt-suggestions.ts +209 -0
  139. package/src/ai/search/combined-search.ts +244 -0
  140. package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
  141. package/src/{llm-utils → ai}/storage.ts +0 -1
  142. package/src/ai/table-tools.ts +145 -0
  143. package/src/ai/ui.ts +720 -0
  144. package/src/ai/usage-limiter.ts +105 -0
  145. package/src/ai/view-tools.ts +352 -0
  146. package/src/claude/ai-feature.ts +16 -0
  147. package/src/claude/exec-blocks.ts +176 -0
  148. package/src/claude/queue-task.ts +84 -0
  149. package/src/claude/runtime-client.ts +310 -0
  150. package/src/claude/turn-log.ts +114 -0
  151. package/src/claude/undoable.ts +105 -0
  152. package/src/{llm-utils → db}/db-index-tools.ts +24 -32
  153. package/src/db/sql-tools.ts +336 -0
  154. package/src/depr/LLM-client.ts +251 -0
  155. package/src/depr/ai-panel.ts +174 -0
  156. package/src/depr/chatgpt-assistant.ts +257 -0
  157. package/src/depr/creds.ts +30 -0
  158. package/src/depr/deepwikiclient.ts +118 -0
  159. package/src/depr/indexes/dg-repository-index.ts +266 -0
  160. package/src/depr/interfaces.ts +170 -0
  161. package/src/depr/is-help-request.ts +39 -0
  162. package/src/depr/prompt-engine.ts +52 -0
  163. package/src/depr/rendering-tools.ts +103 -0
  164. package/src/depr/script-tools.ts +785 -0
  165. package/src/depr/tableview-tools.ts +746 -0
  166. package/src/depr/viewers-ai.ts +67 -0
  167. package/src/package-api.ts +87 -28
  168. package/src/package-test.ts +1 -0
  169. package/src/package.g.ts +98 -48
  170. package/src/package.ts +211 -157
  171. package/src/polyfills.ts +12 -0
  172. package/src/utils.ts +128 -0
  173. package/tsconfig.json +8 -70
  174. package/webpack.config.js +3 -49
  175. package/.eslintignore +0 -2
  176. package/src/ai-panel.ts +0 -174
  177. package/src/claude-code/claude-panel.ts +0 -34
  178. package/src/claude-code/claude-runtime-client.ts +0 -148
  179. package/src/llm-utils/LLM-client.ts +0 -251
  180. package/src/llm-utils/combined-search.ts +0 -162
  181. package/src/llm-utils/creds.ts +0 -30
  182. package/src/llm-utils/deepwikiclient.ts +0 -118
  183. package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
  184. package/src/llm-utils/panel.ts +0 -866
  185. package/src/llm-utils/script-tools.ts +0 -784
  186. package/src/llm-utils/sql-tools.ts +0 -840
  187. package/src/llm-utils/tableview-tools.ts +0 -704
  188. package/src/llm-utils/ui.ts +0 -315
  189. package/src/prompt-engine/chatgpt-assistant.ts +0 -257
  190. package/src/prompt-engine/interfaces.ts +0 -170
  191. package/src/prompt-engine/prompt-engine.ts +0 -52
  192. package/src/prompt-engine/rendering-tools.ts +0 -103
  193. package/src/prompts/is-help-request.ts +0 -26
  194. package/src/viewers-ai.ts +0 -67
  195. /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
  196. /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
  197. /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
  198. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
  199. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
  200. /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
  201. /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
  202. /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
  203. /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
@@ -1,866 +0,0 @@
1
- /* eslint-disable max-len */
2
- import * as grok from 'datagrok-api/grok';
3
- import * as ui from 'datagrok-api/ui';
4
- import * as DG from 'datagrok-api/dg';
5
- import * as rxjs from 'rxjs';
6
- // @ts-ignore .... idk why it does not like it
7
- import '../../css/ai.css';
8
- import {dartLike, fireAIAbortEvent, getAIPanelToggleSubscription} from '../utils';
9
- import {buildViewContext, executeDatagrokBlocks} from '../claude-code/claude-panel';
10
- import {ConversationStorage, StoredConversationWithContext} from './storage';
11
- import {ModelOption, ModelType} from './LLM-client';
12
- import {LanguageModelV3Message, LanguageModelV3Content} from '@ai-sdk/provider';
13
-
14
- // in future might extend it with other types for response API
15
- export type MessageType = LanguageModelV3Message;
16
-
17
- export type AIEngine = 'DeepGROK' | 'Claude';
18
-
19
- type AIPanelInputs = {
20
- prompt: string,
21
- model: ModelOption,
22
- }
23
-
24
- type DBAIPanelInputs = AIPanelInputs & {
25
- catalogName: string,
26
- }
27
-
28
- export type ScriptingAIPanelInputs = AIPanelInputs & {
29
- language: DG.ScriptingLanguage
30
- };
31
-
32
-
33
- type TVAIPanelInputs = AIPanelInputs & {
34
- mode: 'agent' | 'ask',
35
- }
36
-
37
- const actionButtionValues = {
38
- run: 'Run AI Prompt',
39
- stop: 'Stop AI Generation',
40
- } as const;
41
-
42
- export type UIMessageOptions = {
43
- /** if set, will add feedback buttons to the message*/
44
- finalResult?: string,
45
- /** if set, will show a confirmation dialog with the given message before adding the message */
46
- confirm?: {confirmResult?: boolean, message?: string},
47
- }
48
-
49
- export interface UIMessage {
50
- fromUser: boolean;
51
- text: string;
52
- title?: string;
53
- messageOptions?: UIMessageOptions;
54
- }
55
-
56
- export type PanelMessageRet = {
57
- confirmPromise: Promise<boolean>,
58
- }
59
-
60
- export type AIPanelFuncs<T extends MessageType = LanguageModelV3Message> = {
61
- /** Adds @aiMsg to the message stack (from user) and @msg to the UI panel */
62
- addUserMessage: (aiMsg: T, msg: string) => void,
63
- /** Adds @aiMsg to the message stack (from AI) and @msg with @title to the UI panel*/
64
- addAIMessage: (aiMsg: T, title: string, msg: string) => void,
65
- /** Adds @aiMsg to the message stack without showing it to the ui */
66
- addEngineMessage: (aiMsg: T) => void,
67
- /** Adds @msg to the UI without adding it to the AI message stack */
68
- addUiMessage: (msg: string, fromUser: boolean, messageOptions?: UIMessageOptions) => void
69
- /**Adds confirmation section to the panel and awaits result */
70
- addConfirmMessage: (msg?: string) => Promise<boolean>,
71
-
72
- }
73
-
74
- export class AIPanel<T extends MessageType = LanguageModelV3Message, K extends AIPanelInputs = AIPanelInputs> {
75
- private root: HTMLElement;
76
- private view: DG.View | DG.ViewBase;
77
- private inputArea: HTMLElement;
78
- protected header: HTMLElement;
79
- protected outputArea: HTMLElement;
80
- protected textArea: HTMLTextAreaElement;
81
- private textAreaDiv: HTMLElement;
82
- private runButton: HTMLElement;
83
- protected modelInput: DG.InputBase<ModelOption>;
84
- private newChatButton: HTMLElement;
85
- private copyConversationButton: HTMLElement;
86
- private historyButton: HTMLElement;
87
- private tryAgainButton: HTMLElement;
88
- private micButton: HTMLElement;
89
- private recognition: SpeechRecognition | null = null;
90
- private isRecognizing: boolean = false;
91
- private _onRunRequest = new rxjs.Subject<{prevMessages: T[], currentPrompt: K}>();
92
- private _messages: T[] = [];
93
- protected _uiMessages: UIMessage[] = [];
94
- protected get placeHolder() { return 'Type your prompt here...'; }
95
- public get onRunRequest() {
96
- return this._onRunRequest.asObservable();
97
- }
98
- private _onClearChatRequest: rxjs.Subject<void> = new rxjs.Subject<void>();
99
- public get onClearChatRequest(): rxjs.Observable<void> {
100
- return this._onClearChatRequest.asObservable();
101
- }
102
- private runButtonTooltip: typeof actionButtionValues[keyof typeof actionButtionValues] = actionButtionValues.run;
103
- public inputControlsDiv: HTMLElement;
104
- protected get contextId(): string {
105
- return this._contextID;// these should be overriden in subclasses
106
- }
107
-
108
-
109
- private currentConversationId: string | null = null;
110
- constructor(private _contextID: string = 'global-ai-panel', view: DG.View | DG.ViewBase) {
111
- this.view = view;
112
- this.root = ui.divV([], 'd4-ai-generation-panel');
113
- this.inputArea = ui.divV([], 'd4-ai-panel-input-area');
114
- this.outputArea = ui.divV([], 'd4-ai-panel-output-area');
115
- this.header = ui.divH([], 'd4-ai-panel-header');
116
- this.textArea = dartLike(document.createElement('textarea'))
117
- .set('className', 'd4-ai-input-textarea').set('placeholder', this.placeHolder).value;
118
- this.runButton = ui.iconFA('paper-plane', () => {
119
- if (this.runButtonTooltip === actionButtionValues.stop) {
120
- this.terminate();
121
- return;
122
- }
123
- this.handleRun();
124
- });
125
- this.textArea.addEventListener('keydown', (event: KeyboardEvent) => {
126
- if (event.key === 'Enter' && (!event.ctrlKey && !event.metaKey)) {
127
- event.preventDefault();
128
- event.stopImmediatePropagation();
129
- this.handleRun();
130
- }
131
- });
132
- ui.tooltip.bind(this.runButton, () => this.runButtonTooltip, 'left');
133
- this.tryAgainButton = ui.icons.sync(() => this.tryAgain(), 'Try Again');
134
- this.historyButton = ui.iconFA('history', () => this.showHistory(), 'Chat History...');
135
- this.micButton = ui.iconFA('microphone', () => this.toggleSpeechRecognition(), 'Voice Input');
136
- this.copyConversationButton = ui.iconFA('copy', async () => {
137
- const success = await this.copyConversationToClipboard();
138
- if (success)
139
- grok.shell.info('Conversation copied to clipboard');
140
- else
141
- grok.shell.error('Failed to copy conversation to clipboard');
142
- }, 'Copy Conversation to Clipboard');
143
-
144
- this.newChatButton = ui.icons.add(async () => {
145
- ui.setUpdateIndicator(this.root, true, 'Saving conversation...');
146
- try {
147
- await this.saveCurrentConversation(); // will always be first user message
148
- } catch (error) {
149
- grok.shell.error('Failed to save conversation before clearing.');
150
- console.error('Failed to save conversation before clearing:', error);
151
- } finally {
152
- ui.setUpdateIndicator(this.root, false);
153
- }
154
- this.handleClear();
155
- this.currentConversationId = null;
156
- }, 'Start New Chat');
157
- this.modelInput = ui.input.choice('Model', {
158
- items: Object.keys(ModelType) as ModelOption[],
159
- value: 'Deep Research',
160
- nullable: false,
161
- tooltipText: 'Select AI model to use',
162
- }) as DG.InputBase<ModelOption>;
163
- this.hideContentIcons();
164
- this.inputControlsDiv = ui.divH([
165
- this.micButton,
166
- this.modelInput.input
167
- ], 'd4-ai-panel-input-controls');
168
- this.runButton.style.color = 'var(--blue-1)';
169
- const inputControlsRight = ui.divH([this.tryAgainButton, this.runButton], 'd4-ai-panel-run-controls');
170
- inputControlsRight.style.marginLeft = 'auto';
171
- const controlsDiv = ui.divH([this.inputControlsDiv, inputControlsRight], 'd4-ai-panel-controls-container');
172
- this.textAreaDiv = ui.divV([this.textArea], {classes: 'd4-ai-input-textarea-div', style: {position: 'relative'}});
173
- this.inputArea.appendChild(this.textAreaDiv);
174
- this.inputArea.appendChild(controlsDiv);
175
- this.root.appendChild(this.header);
176
- this.root.appendChild(this.outputArea);
177
- this.root.appendChild(this.inputArea);
178
-
179
- const headerTitle = ui.h2('Chat', 'd4-ai-panel-header-title');
180
- dartLike(headerTitle.style).set('margin', '0px').set('userSelect', 'none').set('cursor', 'pointer');
181
- headerTitle.addEventListener('click', () => this.textArea.focus());
182
- this.header.appendChild(headerTitle);
183
- const rightHeaderDiv = ui.divH([], 'd4-ai-panel-header-right-buttons');
184
- rightHeaderDiv.appendChild(this.newChatButton);
185
- rightHeaderDiv.appendChild(this.copyConversationButton);
186
- rightHeaderDiv.appendChild(this.historyButton);
187
- this.header.appendChild(rightHeaderDiv);
188
- this.setupSubscriptions();
189
- }
190
-
191
- protected setupSubscriptions() {
192
- // do some subscriptions
193
- let wasShown = false;
194
- const sub = grok.events.onCurrentViewChanged.subscribe(() => {
195
- if (grok.shell.v != this.view) {
196
- wasShown = this.isShown;
197
- if (wasShown)
198
- this.hide();
199
- } else {
200
- if (wasShown)
201
- this.show();
202
- }
203
- });
204
-
205
- const toggleSub = getAIPanelToggleSubscription().subscribe((rv) => {
206
- if (rv == this.view)
207
- this.toggle();
208
- });
209
- const that = this;
210
- function onKeyDownHandler(event: KeyboardEvent) {
211
- if (grok.shell.v === that.view && event.ctrlKey && event.key === 'i') {
212
- event.preventDefault();
213
- event.stopImmediatePropagation();
214
- that.toggle();
215
- }
216
- }
217
- document.addEventListener('keydown', onKeyDownHandler);
218
-
219
- const closeSub = grok.events.onViewRemoved.subscribe((view) => {
220
- if (view == this.view) {
221
- sub.unsubscribe();
222
- closeSub.unsubscribe();
223
- this.hide();
224
- this.dispose();
225
- toggleSub.unsubscribe();
226
- document.removeEventListener('keydown', onKeyDownHandler);
227
- }
228
- });
229
- }
230
-
231
- private static _lastDockedPanel: DG.DockNode | null = null;
232
- show() {
233
- grok.shell.windows.showHelp = false;
234
- // grok.shell.windows.context.root?.style
235
- // grok.shell.o = this.root;
236
- // grok.shell.setCurrentObject(this.root, true, true);
237
- if (AIPanel._lastDockedPanel) {
238
- if (AIPanel._lastDockedPanel.container.containerElement.contains(this.root) && document.contains(this.root))
239
- return;
240
- grok.shell.dockManager.close(AIPanel._lastDockedPanel);
241
- }
242
- const contextRoot = grok.shell.windows.context?.root;
243
- const contextNode = contextRoot && document.contains(contextRoot) ? grok.shell.dockManager.findNode(contextRoot) : null;
244
- AIPanel._lastDockedPanel = grok.shell.dockManager.dock(this.root, contextNode ? 'down' : 'right', contextNode, '', contextNode ? 0.5 : 0.25);
245
- }
246
-
247
- hide() {
248
- // save history before hiding
249
- grok.shell.dockManager.close(this.root);
250
- }
251
-
252
- formatConversation() {
253
- let previousFromAI = false;
254
- return this._uiMessages.map((msg) => {
255
- const prefix = msg.fromUser ? 'USER:' : 'Datagrok AI:';
256
- const separator = '-'.repeat(50);
257
- const isContinuation = !msg.fromUser && previousFromAI;
258
- previousFromAI = !msg.fromUser;
259
- const actualPrefix = isContinuation ? '\n' : `${separator}\n${prefix}\n`;
260
- return `${actualPrefix}${msg.text}\n`;
261
- }).join('\n');
262
- }
263
-
264
- async copyConversationToClipboard() {
265
- const formattedText = this.formatConversation();
266
-
267
- try {
268
- await navigator.clipboard.writeText(formattedText);
269
- return true;
270
- } catch (err) {
271
- console.error('Failed to copy:', err);
272
- return false;
273
- }
274
- }
275
-
276
- toggle() {
277
- document.contains(this.root) ? this.hide() : this.show();
278
- }
279
-
280
- dispose() {
281
- this.stopRecognition();
282
- this.root.remove();
283
- this._messages = [];
284
- this._uiMessages = [];
285
- }
286
-
287
-
288
- public getCurrentInputs(): K {
289
- return {
290
- prompt: this.textArea.value,
291
- model: this.modelInput.value!,
292
- } as K;
293
- }
294
-
295
- protected _aiMessagesAccordionPane: HTMLElement | null = null;
296
-
297
- protected ensureAccordionPane(): void {
298
- if (this._aiMessagesAccordionPane)
299
- return;
300
- const acord = ui.accordion();
301
- this._aiMessagesAccordionPane = ui.divV([], 'd4-ai-messages-accordion-pane');
302
- const pane = acord.addPane('Responses', () => this._aiMessagesAccordionPane!, true, undefined, false);
303
- pane.expanded = true;
304
- acord.root.style.width = 'calc(100% - 35px)';
305
- this.outputArea.appendChild(acord.root);
306
- }
307
-
308
- protected createStyledMarkdown(content: string): HTMLElement {
309
- const markDown = ui.markdown(content);
310
- markDown.style.position = 'relative';
311
- dartLike(markDown.style).set('userSelect', 'text').set('maxWidth', '100%');
312
- if (markDown.querySelector('pre > code')) {
313
- const copyButton = ui.icons.copy(() => {}, 'Copy Code');
314
- copyButton.classList.add('d4-ai-copy-code-button');
315
- markDown.appendChild(copyButton);
316
- copyButton.addEventListener('click', () => {
317
- const codeElement = markDown.querySelector('pre > code');
318
- if (codeElement) {
319
- const header = markDown.children[0];
320
- if (header && header.tagName?.toLowerCase() !== 'pre')
321
- (header as HTMLElement).style.marginRight = '16px';
322
- navigator.clipboard.writeText(codeElement.textContent || '').then(() => {
323
- copyButton.classList.add('d4-ai-copy-code-button-copied');
324
- setTimeout(() => copyButton.classList.remove('d4-ai-copy-code-button-copied'), 600);
325
- }).catch(() => grok.shell.error('Failed to copy code to clipboard.'));
326
- }
327
- });
328
- }
329
- return markDown;
330
- }
331
-
332
- protected appendFeedbackButtons(markDown: HTMLElement, onFeedback?: (helpful: boolean) => void): void {
333
- const feedbackDiv = ui.divH([], 'd4-ai-panel-feedback-div');
334
- const thumbsUp = ui.iconFA('thumbs-up', () => {
335
- grok.shell.info('Thanks for your feedback!');
336
- handleFeedback(true);
337
- }, 'Helpful');
338
- const thumbsDown = ui.iconFA('thumbs-down', () => {
339
- grok.shell.info('Thanks for your feedback!');
340
- handleFeedback(false);
341
- }, 'Not Helpful');
342
- [thumbsUp, thumbsDown].forEach((el) => dartLike(el.style).set('padding', '2px').set('borderRadius', '6px'));
343
- function handleFeedback(helpful: boolean) {
344
- [thumbsUp, thumbsDown].forEach((el) => { el.style.backgroundColor = ''; });
345
- (helpful ? thumbsUp : thumbsDown).style.backgroundColor = helpful ? 'rgba(0, 150, 30, 0.2)' : 'rgba(200, 0, 0, 0.2)';
346
- onFeedback?.(helpful);
347
- }
348
- feedbackDiv.appendChild(thumbsUp);
349
- feedbackDiv.appendChild(thumbsDown);
350
- dartLike(feedbackDiv.style).set('gap', '8px').set('alignItems', 'center').set('width', '100%').set('paddingBottom', '8px').set('paddingLeft', '4px');
351
- markDown.appendChild(feedbackDiv);
352
- }
353
-
354
- protected appendMessage(
355
- aiMessage: T, uiMessage: {
356
- title: string, content: string, fromUser: boolean, onlyAddToMessages?: boolean, uiOnly?: boolean, messageOptions?: UIMessageOptions
357
- }, loader?: HTMLElement
358
- ): PanelMessageRet | undefined {
359
- let ret: PanelMessageRet | undefined = undefined;
360
- if (!uiMessage.uiOnly)
361
- this._messages.push(aiMessage);
362
- if (uiMessage.onlyAddToMessages)
363
- return;
364
- // from this point we know that message is also in the ui.
365
- this._uiMessages.push({fromUser: !!uiMessage.fromUser, text: uiMessage.content, title: uiMessage.title, messageOptions: uiMessage.messageOptions});
366
- if (uiMessage.fromUser) {
367
- const userDiv = ui.div(ui.divText(uiMessage.content, 'd4-ai-user-prompt-divtext'), 'd4-ai-user-prompt-container');
368
- this.outputArea.appendChild(userDiv);
369
- this._aiMessagesAccordionPane = null; // reset accordion pane so that next AI message creates a new one
370
- } else {
371
- this.ensureAccordionPane();
372
- const markDown = this.createStyledMarkdown(uiMessage.content);
373
-
374
- if (uiMessage?.messageOptions?.finalResult && !uiMessage.fromUser) {
375
- this.appendFeedbackButtons(markDown, (helpful) => {
376
- receiveFeedback(
377
- this._uiMessages[0]?.text ?? '',
378
- uiMessage?.messageOptions?.finalResult!,
379
- this.contextId,
380
- helpful
381
- );
382
- });
383
- }
384
-
385
- if (uiMessage?.messageOptions?.confirm && !uiMessage.fromUser) {
386
- let resolve: (value: boolean) => void = () => {};
387
- const confirmPromise = new Promise<boolean>((res) => { resolve = res; });
388
- ret = {confirmPromise: confirmPromise};
389
- const confirmDiv = ui.divV([], 'd4-ai-panel-confirmation-div');
390
- const confirmText = ui.divText(uiMessage?.messageOptions?.confirm.message ?? 'Allow Datagrok to proceed?', 'd4-ai-panel-confirmation-text');
391
- const buttonsDiv = ui.divH([], 'd4-ai-panel-confirmation-buttons-div');
392
- const confirmButton = ui.iconFA('check', null, 'Confirm');
393
- const cancelButton = ui.iconFA('times', null, 'Cancel');
394
- dartLike(confirmButton.style).set('padding', '2px').set('borderRadius', '6px').set('marginRight', '2px').set('textAlign', 'center').set('width', '14px');
395
- dartLike(cancelButton.style).set('padding', '2px').set('borderRadius', '6px').set('textAlign', 'center').set('width', '14px');
396
- // if the result of confirmation is already set, do not subscribe to changes
397
- const handleConfirmResult = (confirmed: boolean) => {
398
- // make sure the reference of the result is also marked
399
- uiMessage?.messageOptions?.confirm && (uiMessage.messageOptions.confirm.confirmResult = confirmed);
400
- resolve(confirmed);
401
- [confirmButton, cancelButton].forEach((el) => {
402
- el.onclick = null;
403
- dartLike(el.style).set('backgroundColor', '').set('cursor', 'default').set('opacity', '0.6').set('pointerEvents', 'none');
404
- });
405
- (confirmed ? confirmButton : cancelButton).style.backgroundColor = confirmed ? 'rgba(0, 150, 30, 0.3)' : 'rgba(200, 0, 0, 0.3)';
406
- };
407
- confirmButton.onclick = () => handleConfirmResult(true);
408
- cancelButton.onclick = () => handleConfirmResult(false);
409
- buttonsDiv.appendChild(confirmButton);
410
- buttonsDiv.appendChild(cancelButton);
411
- confirmDiv.appendChild(confirmText);
412
- confirmDiv.appendChild(buttonsDiv);
413
- markDown.appendChild(confirmDiv);
414
- if (uiMessage?.messageOptions?.confirm.confirmResult != undefined)
415
- handleConfirmResult(uiMessage?.messageOptions?.confirm.confirmResult); // already have a result
416
- }
417
-
418
- const titleText = uiMessage.title ? [ui.h3(uiMessage.title, 'd4-ai-assistant-response-title')] : [];
419
- const assistantDiv = ui.divV([...titleText, markDown], 'd4-ai-assistant-response-container');
420
- this._aiMessagesAccordionPane!.appendChild(assistantDiv);
421
- }
422
- // reapend loader to the end
423
- if (loader)
424
- this.outputArea.appendChild(loader);
425
- this.outputArea.scrollTop = this.outputArea.scrollHeight;
426
- this.showContentIcons();
427
- return ret;
428
- }
429
-
430
- public startChatSession(): {session: AIPanelFuncs<T>, endSession: () => void, loader: HTMLElement} {
431
- const loader = ui.icons.loader();
432
- dartLike(loader.style).set('alignSelf', 'center').set('height', '20px').set('marginTop', '8px');
433
- this.runButton.classList.remove('fal', 'fa-paper-plane');
434
- this.runButton.classList.add('fas', 'fa-stop');
435
- this.runButton.style.color = 'orangered';
436
- this.runButtonTooltip = actionButtionValues.stop;
437
- return {
438
- loader,
439
- session: {
440
- addAIMessage: (aiMessage, title, content) => this.appendMessage(aiMessage, {title: title, content: content, fromUser: false}, loader),
441
- addEngineMessage: (aiMessage) => this.appendMessage(aiMessage, {title: '', content: '', fromUser: false, onlyAddToMessages: true}, loader),
442
- addUiMessage: (msg: string, fromUser: boolean, messageOptions?: UIMessageOptions) => this.appendMessage('' as any, {title: '', content: msg, fromUser: fromUser, uiOnly: true, messageOptions: messageOptions}, loader),
443
- addUserMessage: (aiMsg, content) => this.appendMessage(aiMsg, {title: '', content: content, fromUser: true}, loader),
444
- addConfirmMessage: (msg?: string) => this.appendMessage('' as any, {title: '', content: '', fromUser: false, uiOnly: true, messageOptions: {confirm: {message: msg}}}, loader)!.confirmPromise,
445
- },
446
- endSession: () => {
447
- this.runButton.classList.remove('fas', 'fa-stop');
448
- this.runButton.classList.add('fal', 'fa-paper-plane');
449
- this.runButton.style.color = 'var(--blue-1)';
450
- this.runButtonTooltip = actionButtionValues.run;
451
- this.saveCurrentConversation().catch((e) => console.error('Failed to save conversation before hiding panel:', e));
452
- loader.remove();
453
- }
454
- };
455
- }
456
-
457
- get isShown(): boolean {
458
- return document.contains(this.root);
459
- }
460
-
461
- private tryAgain() {
462
- if (this._messages.length === 0)
463
- return; // should never happen, but just in case
464
- const inputs = this.getCurrentInputs();
465
- inputs.prompt = 'Please try again. ';
466
- this._onRunRequest.next({
467
- prevMessages: [...this._messages],
468
- currentPrompt: inputs,
469
- });
470
- }
471
-
472
- private terminate() {
473
- fireAIAbortEvent();
474
- }
475
-
476
- private handleRun() {
477
- const inputs = this.getCurrentInputs();
478
- this.textArea.value = '';
479
- this._onRunRequest.next({
480
- prevMessages: this._messages,
481
- currentPrompt: inputs,
482
- });
483
- }
484
-
485
- protected showContentIcons() {
486
- this.newChatButton.style.display = 'flex';
487
- this.tryAgainButton.style.display = 'flex';
488
- this.copyConversationButton.style.display = 'flex';
489
- }
490
-
491
- protected hideContentIcons() {
492
- this.newChatButton.style.display = 'none';
493
- this.tryAgainButton.style.display = 'none';
494
- this.copyConversationButton.style.display = 'none';
495
- }
496
-
497
- private handleClear() {
498
- this._messages = [];
499
- this._uiMessages = [];
500
- this.outputArea.innerHTML = '';
501
- this._onClearChatRequest.next();
502
- this.hideContentIcons();
503
- }
504
-
505
- private async showHistory() {
506
- try {
507
- const conversations = await ConversationStorage.listConversations(
508
- this.contextId,
509
- 10
510
- ) as StoredConversationWithContext<T>[];
511
-
512
- if (conversations.length === 0) {
513
- grok.shell.info('No conversation history found');
514
- return;
515
- }
516
-
517
- const menu = DG.Menu.popup();
518
- for (const conv of conversations) {
519
- if (this.currentConversationId && conv.id === this.currentConversationId)
520
- continue;
521
- const date = new Date(conv.timestamp).toLocaleString();
522
- const preview = conv.initialPrompt.substring(0, 40);
523
- const displayText = `${preview}${conv.initialPrompt.length > 40 ? '...' : ''} (${date})`;
524
-
525
- menu.item(displayText, () => this.loadConversation(conv.id));
526
- }
527
-
528
- menu.separator();
529
- menu.item('Clear All History', async () => {
530
- // if (await grok.shell.('Delete all conversation history?')) {
531
- // await ConversationStorage.clearAll();
532
- // grok.shell.info('History cleared');
533
- // }
534
- ui.dialog('Delete all conversation history').add(ui.divText('This action will permanently delete all saved conversations. Are you sure you want to proceed?'))
535
- .onOK(async () => {
536
- await ConversationStorage.clearAll();
537
- grok.shell.info('History cleared');
538
- }).show();
539
- });
540
-
541
- menu.show();
542
- } catch (error) {
543
- console.error('Failed to load history:', error);
544
- grok.shell.error('Failed to load conversation history');
545
- }
546
- }
547
- private async loadConversation(conversationId: string) {
548
- try {
549
- const conv = (await ConversationStorage.getConversation(conversationId)) as StoredConversationWithContext<T> | null;
550
- if (!conv) {
551
- grok.shell.error('Conversation not found');
552
- return;
553
- }
554
-
555
- this.currentConversationId = conversationId;
556
- this._messages = conv.messages;
557
-
558
- // Clear and rebuild UI from messages
559
- this.outputArea.innerHTML = '';
560
- this._uiMessages = [];
561
- conv.uiMessages.forEach((msg) => {
562
- this.appendMessage(null as any, {title: msg.title ?? '', content: msg.text, fromUser: msg.fromUser, uiOnly: true, messageOptions: msg.messageOptions}); // no loader
563
- });
564
- this.afterConversationLoad(conv);
565
- //grok.shell.info(`Loaded conversation: ${conv.initialPrompt.substring(0, 50)}...`);
566
- } catch (error) {
567
- console.error('Failed to load conversation:', error);
568
- grok.shell.error('Failed to load conversation');
569
- }
570
- }
571
-
572
- protected afterConversationLoad(conversation: StoredConversationWithContext<T>) {
573
- // do nothing in base class
574
- }
575
-
576
- protected getConversationMeta(): any {
577
- return undefined;
578
- }
579
-
580
- public async saveCurrentConversation(initialPrompt?: string) {
581
- if (this._messages.length === 0) return;
582
-
583
- try {
584
- if (this.currentConversationId)
585
- await ConversationStorage.updateConversation(this.currentConversationId, this._messages, this._uiMessages, this.getConversationMeta());
586
- else {
587
- this.currentConversationId = await ConversationStorage.saveConversation(
588
- this._messages, this._uiMessages, initialPrompt ?? this._uiMessages[0]?.text ?? 'No Title', this.contextId, this.getConversationMeta()
589
- );
590
- }
591
- } catch (error) {
592
- console.error('Failed to save conversation:', error);
593
- }
594
- }
595
-
596
- private toggleSpeechRecognition() {
597
- if (this.isRecognizing)
598
- this.stopRecognition();
599
- else
600
- this.startRecognition();
601
- }
602
-
603
- private startRecognition() {
604
- try {
605
- this.recognition = new SpeechRecognition();
606
- this.recognition.continuous = false;
607
- this.recognition.interimResults = false;
608
- this.recognition.lang = 'en-US';
609
-
610
- // Update UI to show recording state
611
- this.isRecognizing = true;
612
- this.micButton.classList.remove('fa-microphone');
613
- this.micButton.classList.add('fa-stop');
614
- this.micButton.style.color = 'orangered';
615
- ui.setUpdateIndicator(this.textAreaDiv, true, 'Listening...');
616
-
617
- this.recognition.onresult = (event) => {
618
- const transcript = event.results[0][0].transcript;
619
- this.textArea.value = transcript;
620
- this.textArea.focus();
621
- ui.setUpdateIndicator(this.textAreaDiv, false);
622
- };
623
-
624
- this.recognition.onerror = (event) => {
625
- console.error('Speech recognition error:', event.error);
626
- ui.setUpdateIndicator(this.textAreaDiv, false);
627
-
628
- let errorMessage = 'Speech recognition error';
629
- switch (event.error) {
630
- case 'no-speech':
631
- errorMessage = 'No speech detected. Please try again.';
632
- break;
633
- case 'audio-capture':
634
- errorMessage = 'No microphone found or access denied';
635
- break;
636
- case 'not-allowed':
637
- errorMessage = 'Microphone access denied. Please enable microphone permissions.';
638
- break;
639
- case 'network':
640
- errorMessage = 'Network error during speech recognition';
641
- break;
642
- case 'aborted':
643
- // User stopped intentionally, no error message needed
644
- break;
645
- default:
646
- errorMessage = `Speech recognition error: ${event.error}`;
647
- }
648
-
649
- if (event.error !== 'aborted')
650
- grok.shell.error(errorMessage);
651
-
652
-
653
- this.stopRecognition();
654
- };
655
-
656
- this.recognition.onend = () => {
657
- this.isRecognizing = false;
658
- this.micButton.classList.remove('fa-stop');
659
- this.micButton.classList.add('fa-microphone');
660
- this.micButton.style.color = '';
661
- ui.setUpdateIndicator(this.textAreaDiv, false);
662
- };
663
-
664
- this.recognition.start();
665
- } catch (error) {
666
- console.error('Failed to start speech recognition:', error);
667
- grok.shell.error('Failed to start speech recognition');
668
- this.stopRecognition();
669
- }
670
- }
671
-
672
- private stopRecognition() {
673
- if (this.recognition) {
674
- try {
675
- this.recognition.stop();
676
- } catch (error) {
677
- console.error('Error stopping recognition:', error);
678
- }
679
- this.recognition = null;
680
- }
681
-
682
- this.isRecognizing = false;
683
- this.micButton.classList.remove('fa-stop');
684
- this.micButton.classList.add('fa-microphone');
685
- this.micButton.style.color = '';
686
- ui.setUpdateIndicator(this.textAreaDiv, false);
687
- }
688
- }
689
-
690
-
691
- function receiveFeedback(userPrompt: string, aiResponse: string, contextId: string, helpful: boolean) {
692
- // not implemented yet
693
- }
694
-
695
-
696
- export class DBAIPanel extends AIPanel<MessageType, DBAIPanelInputs> {
697
- protected get placeHolder() { return 'Ask your database, like "Total sales by regions"'; }
698
- protected catalogInput: DG.InputBase<string>;
699
- constructor(catalogs: string[], defaultCatalog: string, connectionID: string, view: DG.View | DG.ViewBase) {
700
- super(connectionID, view); // context ID is connection ID
701
- this.catalogInput = ui.input.choice('Catalog', {
702
- items: catalogs,
703
- value: defaultCatalog,
704
- nullable: false,
705
- tooltipText: 'Select the database catalog to use for AI-assisted query generation.',
706
- }) as DG.InputBase<string>;
707
- this.inputControlsDiv.appendChild(this.catalogInput.input);
708
- ui.tooltip.bind(this.catalogInput.input, 'Select the database catalog to use for AI-assisted query generation.');
709
- }
710
-
711
- public getCurrentInputs(): DBAIPanelInputs {
712
- const baseInputs = super.getCurrentInputs();
713
- return {
714
- ...baseInputs,
715
- catalogName: this.catalogInput.value!,
716
- };
717
- }
718
- }
719
-
720
- export class TVAIPanel extends AIPanel<MessageType, TVAIPanelInputs> {
721
- protected get placeHolder() {
722
- return this._engine === 'Claude' ? 'Ask Claude about your data...' : 'Ask about your table data...';
723
- }
724
- protected tableView: DG.TableView;
725
-
726
- private _engine: AIEngine = 'DeepGROK';
727
- private _engineInput: DG.InputBase<AIEngine>;
728
-
729
- private _streamingContainer: HTMLElement | null = null;
730
- private _streamingMarkdownEl: HTMLElement | null = null;
731
- private _sessionId: string;
732
- private _contextSent = false;
733
-
734
- get currentEngine(): AIEngine { return this._engine; }
735
- get sessionId(): string { return this._sessionId; }
736
-
737
- constructor(view: DG.TableView) {
738
- super(view.dataFrame?.name ?? view.name ?? 'AI-Table-context', view); // context ID is table name
739
- this.tableView = view;
740
- this._sessionId = `claude-${view.dataFrame?.name ?? 'view'}-${crypto.randomUUID()}`;
741
-
742
- this._engineInput = ui.input.choice('Engine', {
743
- items: ['DeepGROK', 'Claude'] as AIEngine[],
744
- value: 'DeepGROK' as AIEngine,
745
- nullable: false,
746
- }) as DG.InputBase<AIEngine>;
747
- this._engineInput.input.style.marginBottom = '0';
748
- this._engineInput.input.classList.add('d4-ai-engine-selector');
749
-
750
- const rightButtons = this.header.querySelector('.d4-ai-panel-header-right-buttons');
751
- if (rightButtons)
752
- this.header.insertBefore(this._engineInput.input, rightButtons);
753
- else
754
- this.header.appendChild(this._engineInput.input);
755
-
756
- this._engineInput.onChanged.subscribe(() => {
757
- this._engine = this._engineInput.value!;
758
- this._onEngineChanged();
759
- });
760
- }
761
-
762
- private _onEngineChanged(): void {
763
- this.modelInput.input.style.display = this._engine === 'Claude' ? 'none' : '';
764
- this.textArea.placeholder = this.placeHolder;
765
- this._clearAndReset();
766
- }
767
-
768
- private _clearAndReset(): void {
769
- this.outputArea.innerHTML = '';
770
- this._uiMessages = [];
771
- this.resetSession();
772
- }
773
-
774
- resetSession(): void {
775
- this._sessionId = `claude-${crypto.randomUUID()}`;
776
- this._contextSent = false;
777
- this._streamingContainer = null;
778
- this._streamingMarkdownEl = null;
779
- }
780
-
781
- prependViewContext(prompt: string, view: DG.ViewBase): string {
782
- if (this._contextSent)
783
- return prompt;
784
- const ctx = buildViewContext(view);
785
- if (!ctx)
786
- return prompt;
787
- this._contextSent = true;
788
- return ctx + '\n---\n\n' + prompt;
789
- }
790
-
791
- updateStreaming(content: string, loader: HTMLElement): void {
792
- if (!this._streamingContainer) {
793
- loader.style.display = 'none';
794
- this.ensureAccordionPane();
795
- this._streamingMarkdownEl = ui.markdown(content);
796
- dartLike(this._streamingMarkdownEl.style).set('userSelect', 'text').set('maxWidth', '100%');
797
- this._streamingContainer = ui.divV([this._streamingMarkdownEl], 'd4-ai-assistant-response-container');
798
- this._aiMessagesAccordionPane!.appendChild(this._streamingContainer);
799
- } else {
800
- const md = ui.markdown(content);
801
- dartLike(md.style).set('userSelect', 'text').set('maxWidth', '100%');
802
- this._streamingMarkdownEl!.replaceWith(md);
803
- this._streamingMarkdownEl = md;
804
- }
805
- this.outputArea.scrollTop = this.outputArea.scrollHeight;
806
- }
807
-
808
- finalizeStreaming(content: string, view: DG.ViewBase): void {
809
- if (!this._streamingContainer || !this._streamingMarkdownEl)
810
- return;
811
-
812
- const markDown = this.createStyledMarkdown(content);
813
- this.appendFeedbackButtons(markDown);
814
-
815
- this._streamingMarkdownEl.replaceWith(markDown);
816
- this._streamingMarkdownEl = null;
817
- this._streamingContainer = null;
818
-
819
- this._uiMessages.push({fromUser: false, text: content, messageOptions: {finalResult: content}});
820
-
821
- executeDatagrokBlocks(content, view);
822
- }
823
-
824
- clearStreaming(): void {
825
- this._streamingContainer?.remove();
826
- this._streamingContainer = null;
827
- this._streamingMarkdownEl = null;
828
- }
829
-
830
- protected getConversationMeta() {
831
- return this.tableView.saveLayout().viewState;
832
- }
833
-
834
- protected afterConversationLoad(conversation: StoredConversationWithContext<MessageType>) {
835
- const currentViewers = Array.from(this.tableView.viewers);
836
- if (!!conversation.meta && currentViewers.length === 1 && currentViewers[0].type === DG.VIEWER.GRID) {
837
- const layout = DG.ViewLayout.fromViewState(conversation.meta);
838
- this.tableView.loadLayout(layout, true);
839
- }
840
- }
841
- }
842
-
843
- export class ScriptingAIPanel extends AIPanel<MessageType, ScriptingAIPanelInputs> {
844
- protected get placeHolder() { return 'Ask AI to generate a script...'; }
845
- protected languageInput: DG.InputBase<string>;
846
-
847
- constructor(view: DG.View | DG.ViewBase) {
848
- super('scripting-ai-panel', view); // context ID is fixed for scripting panel
849
- this.languageInput = ui.input.choice('Language', {
850
- items: Object.values(DG.SCRIPT_LANGUAGE),
851
- value: DG.SCRIPT_LANGUAGE.JAVASCRIPT,
852
- nullable: false,
853
- tooltipText: 'Select scripting language for the generated script.',
854
- }) as DG.InputBase<string>;
855
- this.inputControlsDiv.appendChild(this.languageInput.input);
856
- ui.tooltip.bind(this.languageInput.input, 'Select scripting language for the generated script.');
857
- }
858
-
859
- public getCurrentInputs(): ScriptingAIPanelInputs {
860
- const baseInputs = super.getCurrentInputs();
861
- return {
862
- ...baseInputs,
863
- language: this.languageInput.value as DG.ScriptingLanguage,
864
- };
865
- }
866
- }