@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
@@ -0,0 +1,1385 @@
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, createStyledMarkdown, codeCard, tryMarkdown, plainTextEl,
9
+ copyToClipboard} from '../utils';
10
+ import {buildWorkspaceContext, executeSingleBlock} from '../claude/exec-blocks';
11
+ import {ConversationStorage, StoredConversationWithContext} from './storage';
12
+ import {ClaudeRuntimeClient} from '../claude/runtime-client';
13
+ import {resolveScopes, showSuggestionsMenu, runSuggestionAction, Suggestion, Block, ChoiceOption} from './prompt-suggestions';
14
+ import {AiFeature} from '../claude/ai-feature';
15
+
16
+ export type MessageType = {role: string; content: any};
17
+
18
+ type AIPanelInputs = {
19
+ prompt: string,
20
+ isAnswer?: boolean,
21
+ }
22
+
23
+
24
+ export interface AskUserOption {
25
+ label: string;
26
+ description?: string;
27
+ }
28
+
29
+ export interface AskUserQuestion {
30
+ question: string;
31
+ header?: string;
32
+ options: AskUserOption[];
33
+ multiSelect?: boolean;
34
+ }
35
+
36
+ interface AskUserInput {
37
+ questions: AskUserQuestion[];
38
+ }
39
+
40
+ interface QuestionSection {
41
+ strip: HTMLElement;
42
+ body: HTMLElement;
43
+ }
44
+
45
+ export type StripStyle = 'success' | 'muted';
46
+
47
+ const actionButtionValues = {
48
+ run: 'Run AI Prompt',
49
+ stop: 'Stop AI Generation',
50
+ } as const;
51
+
52
+ /** Silence after which a spoken phrase is sent as the prompt. */
53
+ const VOICE_SUBMIT_DELAY_MS = 1500;
54
+
55
+ const micTooltips = {
56
+ default: 'Voice Input',
57
+ accessDenied: 'Microphone access denied. Please enable microphone permissions.',
58
+ noDevice: 'No microphone found or access denied',
59
+ notSupported: 'Voice input is not supported in this browser',
60
+ } as const;
61
+
62
+ export type UIMessageOptions = {
63
+ /** if set, will add feedback buttons to the message*/
64
+ finalResult?: string,
65
+ /** if set, will show a confirmation dialog with the given message before adding the message */
66
+ confirm?: {confirmResult?: boolean, message?: string},
67
+ /** if set on a user message, shows a small green check ("Handled natively") instead of a response block */
68
+ handledNatively?: boolean,
69
+ /** if set, renders the message as a centered system event (retry notice, workflow header, etc.) */
70
+ system?: boolean,
71
+ }
72
+
73
+ export interface UIMessage {
74
+ fromUser: boolean;
75
+ text: string;
76
+ title?: string;
77
+ messageOptions?: UIMessageOptions;
78
+ execCode?: string[];
79
+ }
80
+
81
+ type ExecInfo = {codes: string[], ranThisSession: boolean, view?: DG.ViewBase};
82
+ const ExecState = {idle: 'idle', ran: 'ran', error: 'error'} as const;
83
+ type ExecState = typeof ExecState[keyof typeof ExecState];
84
+ const EXEC_TOOLTIPS: Record<ExecState, string> = {
85
+ idle: 'Show code — not run this session',
86
+ ran: 'Show code — already executed',
87
+ error: 'Show code — last re-run failed',
88
+ };
89
+
90
+ export type PanelMessageRet = {
91
+ confirmPromise: Promise<boolean>,
92
+ }
93
+
94
+ export type AIPanelFuncs<T extends MessageType = MessageType> = {
95
+ /** Adds @aiMsg to the message stack (from user) and @msg to the UI panel */
96
+ addUserMessage: (aiMsg: T, msg: string) => void,
97
+ /** Adds @aiMsg to the message stack (from AI) and @msg with @title to the UI panel*/
98
+ addAIMessage: (aiMsg: T, title: string, msg: string) => void,
99
+ /** Adds @aiMsg to the message stack without showing it to the ui */
100
+ addEngineMessage: (aiMsg: T) => void,
101
+ /** Adds @msg to the UI without adding it to the AI message stack */
102
+ addUiMessage: (msg: string, fromUser: boolean, messageOptions?: UIMessageOptions) => void
103
+ /** Marks the last user prompt as handled by Datagrok's built-in handler: shows a green check, no response block */
104
+ markHandledNatively: () => void,
105
+ /**Adds confirmation section to the panel and awaits result */
106
+ addConfirmMessage: (msg?: string) => Promise<boolean>,
107
+ /** Shows options to the user and returns their selection */
108
+ showInputRequest?: (input: AskUserInput) => void,
109
+ }
110
+
111
+ export interface StreamingPanel<T extends MessageType = MessageType> {
112
+ sessionId: string;
113
+ startChatSession(): {session: AIPanelFuncs<T>, endSession: () => void};
114
+ prependViewContext(prompt: string, view: DG.ViewBase): string;
115
+ prependEntityContext(prompt: string): string;
116
+ updateStreaming(content: string): void;
117
+ setStatus(text: string): void;
118
+ showError(text: string): void;
119
+ finalizeStreaming(displayContent: string, execCodes: string[], view: DG.ViewBase): Promise<void>;
120
+ appendStreamedElement(el: HTMLElement): void;
121
+ appendUiMessage(content: string): void;
122
+ clearStreaming(): void;
123
+ showInputRequest(input: AskUserInput): void;
124
+ dismissQuestion(): void;
125
+ restoredTranscript(): string;
126
+ get rawRender(): boolean;
127
+ get noPrompt(): boolean;
128
+ enableNoPrompt(): void;
129
+ pushNativeContext(prompt: string): void;
130
+ flushNativeContext(): string;
131
+ }
132
+
133
+ export class AIPanel<T extends MessageType = MessageType, K extends AIPanelInputs = AIPanelInputs> implements StreamingPanel<T> {
134
+ readonly root: HTMLElement;
135
+ protected view: DG.View | DG.ViewBase;
136
+ private inputArea: HTMLElement;
137
+ protected header: HTMLElement;
138
+ protected outputArea: HTMLElement;
139
+ protected textArea: HTMLTextAreaElement;
140
+ private textAreaDiv: HTMLElement;
141
+ private runButton: HTMLElement;
142
+ private newChatButton: HTMLElement;
143
+ private copyConversationButton: HTMLElement;
144
+ private historyButton: HTMLElement;
145
+ private tryAgainButton: HTMLElement;
146
+ private micButton: HTMLElement;
147
+ private rawRenderButton: HTMLElement;
148
+ private wandButton: HTMLElement;
149
+ private _rawRender: boolean = false;
150
+ private _noPrompt: boolean = false;
151
+ private _pendingNativeContext: string[] = [];
152
+ private recognition: SpeechRecognition | null = null;
153
+ private isRecognizing: boolean = false;
154
+ /** The final results of the phrase being spoken, not yet submitted. */
155
+ private voiceTranscript: string = '';
156
+ private voiceSubmitTimer?: number;
157
+ /** `Say "cancel" to stop` caption shown next to the loader while the AI is working in voice mode. */
158
+ private _voiceCancelHint: HTMLElement | null = null;
159
+ private micAccessDenied: boolean = false;
160
+ private _onRunRequest = new rxjs.Subject<{prevMessages: T[], currentPrompt: K}>();
161
+ protected _messages: T[] = [];
162
+ protected _uiMessages: UIMessage[] = [];
163
+ protected get placeHolder() { return 'Type your prompt here...'; }
164
+ public get onRunRequest() {
165
+ return this._onRunRequest.asObservable();
166
+ }
167
+ private _onClearChatRequest: rxjs.Subject<void> = new rxjs.Subject<void>();
168
+ public get onClearChatRequest(): rxjs.Observable<void> {
169
+ return this._onClearChatRequest.asObservable();
170
+ }
171
+ private runButtonTooltip: typeof actionButtionValues[keyof typeof actionButtionValues] = actionButtionValues.run;
172
+ private get isBusy(): boolean { return this.runButtonTooltip === actionButtionValues.stop; }
173
+
174
+ private syncConversationButtons(): void {
175
+ const buttons: [HTMLElement, string][] = [[this.newChatButton, 'Start New Chat'], [this.historyButton, 'Chat History...']];
176
+ for (const [b, tooltip] of buttons) {
177
+ ui.setDisabled(b, this.isBusy, this.isBusy ? 'Wait for response or press Stop' : null);
178
+ if (!this.isBusy)
179
+ ui.tooltip.bind(b, tooltip);
180
+ }
181
+ }
182
+ public inputControlsDiv: HTMLElement;
183
+ protected attachedEntities: DG.Entity[] = [];
184
+ protected attachmentsRow: HTMLElement = ui.divH([], {style: {flexWrap: 'wrap'}});
185
+ private _pendingEntityContext = '';
186
+ private _pendingAttachmentsForRender: DG.Entity[] = [];
187
+ protected get contextId(): string {
188
+ return this._contextID;// these should be overriden in subclasses
189
+ }
190
+
191
+ protected _streamingContainer: HTMLElement | null = null;
192
+ protected _streamingMarkdownEl: HTMLElement | null = null;
193
+ private statusBar: HTMLElement = ui.divH([], 'grokky-status-bar');
194
+ private statusLabel: HTMLElement = ui.divText('', 'grokky-status-label');
195
+ private statusRepeats = 0;
196
+ private followOutput = true;
197
+ private _sessionId: string;
198
+ private _inline: boolean = false;
199
+ private _feature: AiFeature;
200
+ /** Guards async {@link renderEmptyState} against out-of-order completion on rapid view switches. */
201
+ private _emptyStateSeq = 0;
202
+ /** Index into {@link promptHistory} while recalling prompts with the arrow keys; `null` means the live draft is shown. */
203
+ private _promptHistoryIndex: number | null = null;
204
+ /** The unsubmitted draft saved when the user starts cycling, restored when they cycle back past the newest entry. */
205
+ private _promptDraft: string = '';
206
+ private _dismissQuestion: (() => void) | null = null;
207
+
208
+ get sessionId(): string { return this._sessionId; }
209
+
210
+
211
+ private currentConversationId: string | null = null;
212
+ constructor(private _contextID: string = 'global-ai-panel', view: DG.View | DG.ViewBase, opts: {inline?: boolean, feature?: AiFeature} = {}) {
213
+ this.view = view;
214
+ this._feature = opts.feature ?? AiFeature.Chat;
215
+ this._sessionId = `${this._feature}-${_contextID}-${crypto.randomUUID()}`;
216
+ this._inline = !!opts.inline;
217
+ this.root = ui.divV([], 'd4-ai-generation-panel');
218
+ this.inputArea = ui.divV([], 'd4-ai-panel-input-area');
219
+ this.outputArea = ui.divV([], 'd4-ai-panel-output-area');
220
+ this.header = ui.divH([], 'd4-ai-panel-header');
221
+ this.textArea = dartLike(document.createElement('textarea'))
222
+ .set('className', 'd4-ai-input-textarea').set('placeholder', this.placeHolder).value;
223
+ this.runButton = ui.iconFA('paper-plane', () => {
224
+ if (this.runButtonTooltip === actionButtionValues.stop) {
225
+ this.terminate();
226
+ return;
227
+ }
228
+ this.handleRun();
229
+ }, 'Send');
230
+ this.textArea.addEventListener('keydown', (event: KeyboardEvent) => {
231
+ if (event.isComposing)
232
+ return;
233
+ if (event.key === 'Escape' && this._promptHistoryIndex !== null) {
234
+ this.textArea.value = this._promptDraft;
235
+ this._promptHistoryIndex = null;
236
+ return;
237
+ }
238
+ const up = event.key === 'ArrowUp';
239
+ if ((up || event.key === 'ArrowDown') && !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey &&
240
+ (this._promptHistoryIndex !== null || (up && this.textArea.selectionEnd === 0)) &&
241
+ this.navigatePromptHistory(up ? -1 : 1))
242
+ event.preventDefault();
243
+ if (event.key === 'Enter' && (!event.ctrlKey && !event.metaKey)) {
244
+ event.preventDefault();
245
+ event.stopImmediatePropagation();
246
+ this.handleRun();
247
+ }
248
+ });
249
+ this.textArea.addEventListener('input', () => this._promptHistoryIndex = null);
250
+ this.textArea.addEventListener('blur', (e) => {
251
+ if (this.isBusy && (e as any).sourceCapabilities === null)
252
+ Promise.resolve().then(() => this.textArea.focus());
253
+ });
254
+ ui.tooltip.bind(this.runButton, () => this.runButtonTooltip, 'left');
255
+ this.tryAgainButton = ui.icons.sync(() => this.tryAgain(), 'Try Again');
256
+ this.historyButton = ui.iconFA('history', () => this.showHistory());
257
+ this.micButton = ui.iconFA('microphone', () => this.toggleSpeechRecognition(), micTooltips.default);
258
+ if (typeof SpeechRecognition === 'undefined')
259
+ this.setMicDisabled(micTooltips.notSupported);
260
+ else
261
+ this.checkMicPermission();
262
+ this.copyConversationButton = ui.iconFA('copy', async () => {
263
+ const success = await this.copyConversationToClipboard();
264
+ if (success)
265
+ grok.shell.info('Conversation copied to clipboard');
266
+ else
267
+ grok.shell.error('Failed to copy conversation to clipboard');
268
+ }, 'Copy Conversation to Clipboard');
269
+
270
+ this.newChatButton = ui.icons.add(async () => {
271
+ if (this.isBusy)
272
+ return;
273
+ ui.setUpdateIndicator(this.root, true, 'Saving conversation...');
274
+ try {
275
+ await this.saveCurrentConversation(); // will always be first user message
276
+ } catch (error) {
277
+ grok.shell.error('Failed to save conversation before clearing.');
278
+ console.error('Failed to save conversation before clearing:', error);
279
+ } finally {
280
+ ui.setUpdateIndicator(this.root, false);
281
+ }
282
+ this.resetSession();
283
+ this.handleClear();
284
+ this.textArea.value = '';
285
+ this.clearAttachments();
286
+ this.currentConversationId = null;
287
+ });
288
+ this.syncConversationButtons();
289
+ this.rawRenderButton = ui.iconFA('terminal', () => {
290
+ this._rawRender = !this._rawRender;
291
+ this.rawRenderButton.style.color = this._rawRender ? 'var(--blue-1)' : '';
292
+ this.root.classList.toggle('d4-ai-raw-mode', this._rawRender);
293
+ }, 'Toggle raw console');
294
+ this.wandButton = ui.iconFA('magic', async (e) => {
295
+ const scopes = await resolveScopes('panel', this.view ?? grok.shell.v);
296
+ showSuggestionsMenu(scopes, (s) => this.runSuggestion(s), e);
297
+ }, 'Prompt suggestions');
298
+ this.wandButton.classList.add('grokky-search-wand');
299
+ this.setWandVisible(true);
300
+ this.hideContentIcons();
301
+ this.inputControlsDiv = ui.divH([
302
+ this.wandButton, this.micButton, this.rawRenderButton,
303
+ ], 'd4-ai-panel-input-controls');
304
+ this.runButton.classList.add('grokky-send');
305
+ const sessionControls = ui.divH([this.copyConversationButton, this.historyButton, this.newChatButton], 'd4-ai-panel-run-controls');
306
+ sessionControls.style.marginLeft = 'auto';
307
+ const messageControls = ui.divH([this.tryAgainButton, this.runButton], 'd4-ai-panel-run-controls');
308
+ const controlsDiv = ui.divH([this.inputControlsDiv, sessionControls, ui.div([], 'd4-ribbon-separator'), messageControls], 'd4-ai-panel-controls-container');
309
+ controlsDiv.addEventListener('mousedown', (e) => {
310
+ if (document.activeElement === this.textArea)
311
+ e.preventDefault();
312
+ });
313
+ this.textAreaDiv = ui.divV([this.attachmentsRow, this.textArea], {classes: 'd4-ai-input-textarea-div', style: {position: 'relative'}});
314
+ ui.makeDroppable(this.textAreaDiv, {
315
+ acceptDrop: (o) => o instanceof DG.Entity,
316
+ doDrop: (args: any) => {
317
+ if (args?.dragObject instanceof DG.Entity) {
318
+ this.addEntityChip(args.dragObject);
319
+ this.textArea.focus();
320
+ }
321
+ },
322
+ });
323
+ this.inputArea.appendChild(this.textAreaDiv);
324
+ this.inputArea.appendChild(controlsDiv);
325
+ this.root.appendChild(this.header);
326
+ this.root.appendChild(this.outputArea);
327
+ this.root.appendChild(this.statusBar);
328
+ this.root.appendChild(this.inputArea);
329
+ this.outputArea.addEventListener('scroll', () => {
330
+ const o = this.outputArea;
331
+ this.followOutput = o.scrollHeight - o.clientHeight - o.scrollTop < 30;
332
+ });
333
+
334
+ if (this._inline)
335
+ this.root.classList.add('d4-ai-inline-mode');
336
+ }
337
+
338
+ mountInto(parent: HTMLElement) {
339
+ parent.appendChild(this.root);
340
+ }
341
+
342
+ get contextView(): DG.View | DG.ViewBase { return this.view; }
343
+ setContextView(view: DG.View | DG.ViewBase): void { this.view = view; }
344
+
345
+ activate(focus: boolean = false): void {
346
+ this.renderEmptyState();
347
+ if (focus)
348
+ this.textArea.focus();
349
+ }
350
+
351
+ formatConversation() {
352
+ let previousFromAI = false;
353
+ return this._uiMessages.map((msg) => {
354
+ const prefix = msg.fromUser ? 'USER:' : 'Datagrok AI:';
355
+ const separator = '-'.repeat(50);
356
+ const isContinuation = !msg.fromUser && previousFromAI;
357
+ previousFromAI = !msg.fromUser;
358
+ const actualPrefix = isContinuation ? '\n' : `${separator}\n${prefix}\n`;
359
+ return `${actualPrefix}${msg.text}\n`;
360
+ }).join('\n');
361
+ }
362
+
363
+ async copyConversationToClipboard() {
364
+ return copyToClipboard(this.formatConversation());
365
+ }
366
+
367
+ dispose() {
368
+ this.stopRecognition();
369
+ this.root.remove();
370
+ this._messages = [];
371
+ this._uiMessages = [];
372
+ }
373
+
374
+
375
+ public getCurrentInputs(): K {
376
+ return {
377
+ prompt: this.textArea.value,
378
+ } as K;
379
+ }
380
+
381
+ private addEntityChip(e: DG.Entity): void {
382
+ if (this.attachedEntities.some((x) => x.id === e.id))
383
+ return;
384
+ this.attachedEntities.push(e);
385
+ const icon = DG.ObjectHandler.forEntity(e)?.renderIcon(e.dart) ?? ui.iconFA('tag');
386
+ const label = ui.label(e.friendlyName ?? e.name);
387
+ const close = ui.iconFA('times', () => {
388
+ this.attachedEntities = this.attachedEntities.filter((y) => y !== e);
389
+ chip.remove();
390
+ }, 'Remove');
391
+ const chip = ui.divH([icon, label, close], 'grokky-entity-chip');
392
+ this.attachmentsRow.appendChild(chip);
393
+ }
394
+
395
+ private clearAttachments(): void {
396
+ this.attachedEntities = [];
397
+ ui.empty(this.attachmentsRow);
398
+ }
399
+
400
+ private describeEntity(e: DG.Entity): string {
401
+ const parts = [`type: ${e.entityType}`, `id: ${e.id}`];
402
+ if (e.nqName)
403
+ parts.push(`nqName: ${e.nqName}`);
404
+ if (e instanceof DG.FileInfo)
405
+ parts.push(`path: ${e.fullPath}`);
406
+ return `- "${e.friendlyName ?? e.name}" (${parts.join(', ')})`;
407
+ }
408
+
409
+ public prependEntityContext(prompt: string): string {
410
+ const ctx = this._pendingEntityContext;
411
+ if (!ctx)
412
+ return prompt;
413
+ this._pendingEntityContext = '';
414
+ return ctx + '\n---\n\n' + prompt;
415
+ }
416
+
417
+ protected _aiMessagesAccordionPane: HTMLElement | null = null;
418
+ private _lastUserPromptContainer: HTMLElement | null = null;
419
+
420
+ /** Ensures there is an open response block for the current turn. The block holds all consecutive
421
+ * AI messages and exposes a hover-only minimize icon on its left that collapses it to one line. */
422
+ protected ensureResponseBlock(): void {
423
+ if (this._aiMessagesAccordionPane)
424
+ return;
425
+ this._aiMessagesAccordionPane = ui.divV([], 'd4-ai-messages-accordion-pane');
426
+ const minimizeIcon = ui.iconFA('window-minimize', null, 'Minimize');
427
+ minimizeIcon.classList.add('d4-ai-response-minimize-icon');
428
+ const block = ui.divH([minimizeIcon, this._aiMessagesAccordionPane], 'd4-ai-response-block');
429
+ let collapsed = false;
430
+ minimizeIcon.onclick = () => {
431
+ collapsed = !collapsed;
432
+ block.classList.toggle('d4-ai-response-block-collapsed', collapsed);
433
+ minimizeIcon.classList.toggle('fa-window-minimize', !collapsed);
434
+ minimizeIcon.classList.toggle('fa-window-maximize', collapsed);
435
+ };
436
+ ui.tooltip.bind(minimizeIcon, () => collapsed ? 'Expand' : 'Minimize');
437
+ this.outputArea.appendChild(block);
438
+ }
439
+
440
+ protected createStyledMarkdown(content: string): HTMLElement {
441
+ return createStyledMarkdown(content);
442
+ }
443
+
444
+ private createHandledNativelyIcon(): HTMLElement {
445
+ const icon = ui.iconFA('check', null, 'Handled natively');
446
+ icon.classList.add('d4-ai-handled-natively-icon');
447
+ return icon;
448
+ }
449
+
450
+ /** Marks the most recent user prompt as handled by Datagrok's built-in handler:
451
+ * shows a small green check (tooltip "Handled natively") and skips the response block entirely. */
452
+ public markPromptHandledNatively(): void {
453
+ const last = this._uiMessages[this._uiMessages.length - 1];
454
+ if (!last?.fromUser)
455
+ return;
456
+ last.messageOptions = {...last.messageOptions, handledNatively: true};
457
+ if (this._lastUserPromptContainer && !this._lastUserPromptContainer.querySelector('.d4-ai-handled-natively-icon'))
458
+ this._lastUserPromptContainer.insertBefore(this.createHandledNativelyIcon(), this._lastUserPromptContainer.firstChild);
459
+ }
460
+
461
+ protected appendFeedbackButtons(markDown: HTMLElement, onFeedback?: (helpful: boolean) => void, exec?: ExecInfo): void {
462
+ const feedbackDiv = ui.divH([], 'd4-ai-panel-feedback-div');
463
+ const thumbsUp = ui.iconFA('thumbs-up', () => {
464
+ grok.shell.info('Thanks for your feedback!');
465
+ handleFeedback(true);
466
+ }, 'Helpful');
467
+ const thumbsDown = ui.iconFA('thumbs-down', () => {
468
+ grok.shell.info('Thanks for your feedback!');
469
+ handleFeedback(false);
470
+ }, 'Not Helpful');
471
+ const copyMsg = ui.iconFA('copy', () => {
472
+ copyToClipboard(markDown.textContent || '').then((ok) =>
473
+ ok ? grok.shell.info('Message copied to clipboard') : grok.shell.error('Failed to copy message'));
474
+ }, 'Copy Message');
475
+ [copyMsg, thumbsUp, thumbsDown].forEach((el) => dartLike(el.style).set('padding', '2px').set('borderRadius', '6px'));
476
+ function handleFeedback(helpful: boolean) {
477
+ [thumbsUp, thumbsDown].forEach((el) => { el.style.backgroundColor = ''; });
478
+ (helpful ? thumbsUp : thumbsDown).style.backgroundColor = helpful ? 'rgba(0, 150, 30, 0.2)' : 'rgba(200, 0, 0, 0.2)';
479
+ onFeedback?.(helpful);
480
+ }
481
+ const execIcons = exec?.codes.length ? this.buildExecIcons(markDown, exec) : [];
482
+ feedbackDiv.append(copyMsg, thumbsUp, thumbsDown, ...execIcons);
483
+ dartLike(feedbackDiv.style).set('alignItems', 'center').set('width', '100%').set('paddingBottom', '8px').set('paddingLeft', '4px');
484
+ markDown.appendChild(feedbackDiv);
485
+ }
486
+
487
+ private buildExecIcons(markDown: HTMLElement, {codes, ranThisSession, view = this.view}: ExecInfo): HTMLElement[] {
488
+ const pre = ui.element('pre', 'grokky-exec-code');
489
+ pre.textContent = codes.map((c) => c.trim()).join('\n\n');
490
+ const codeBlock = codeCard(pre, 'JavaScript');
491
+ codeBlock.classList.add('grokky-hidden');
492
+ markDown.appendChild(codeBlock);
493
+
494
+ let state: ExecState = ranThisSession ? ExecState.ran : ExecState.idle;
495
+ const setState = (next: ExecState) => {
496
+ state = next;
497
+ codeToggle.classList.remove('grokky-exec-ran', 'grokky-exec-error');
498
+ if (next !== ExecState.idle)
499
+ codeToggle.classList.add(`grokky-exec-${next}`);
500
+ };
501
+ const codeToggle = ui.iconFA('code', () => codeBlock.classList.toggle('grokky-hidden'), null);
502
+ codeToggle.classList.add('grokky-exec-icon');
503
+ ui.tooltip.bind(codeToggle, () => EXEC_TOOLTIPS[state]);
504
+ setState(state);
505
+
506
+ let rerunning = false;
507
+ const rerunIcon = ui.iconFA('redo', async () => {
508
+ if (rerunning) return;
509
+ rerunning = true;
510
+ rerunIcon.classList.add('fa-spin');
511
+ let rerunFailed = false;
512
+ for (const code of codes) {
513
+ const {error} = await executeSingleBlock(code, grok.shell.v ?? view, 0);
514
+ if (error) {
515
+ rerunFailed = true;
516
+ break;
517
+ }
518
+ }
519
+ setState(rerunFailed ? ExecState.error : ExecState.ran);
520
+ rerunIcon.classList.remove('fa-spin');
521
+ rerunning = false;
522
+ }, 'Re-run this code');
523
+ for (const el of [codeToggle, rerunIcon])
524
+ dartLike(el.style).set('padding', '2px').set('borderRadius', '6px');
525
+ return [ui.div([], 'grokky-exec-sep'), codeToggle, rerunIcon];
526
+ }
527
+
528
+ protected appendMessage(
529
+ aiMessage: T, uiMessage: {
530
+ title: string, content: string, fromUser: boolean, onlyAddToMessages?: boolean, uiOnly?: boolean, messageOptions?: UIMessageOptions, execCode?: string[]
531
+ }
532
+ ): PanelMessageRet | undefined {
533
+ let ret: PanelMessageRet | undefined = undefined;
534
+ this.removeChoiceBlocks();
535
+ const emptyState = this.outputArea.querySelector('.grokky-empty-state');
536
+ if (emptyState) {
537
+ emptyState.remove();
538
+ this.setWandVisible(true);
539
+ }
540
+ if (!uiMessage.uiOnly)
541
+ this._messages.push(aiMessage);
542
+ if (uiMessage.onlyAddToMessages)
543
+ return;
544
+ // from this point we know that message is also in the ui.
545
+ this._uiMessages.push({fromUser: !!uiMessage.fromUser, text: uiMessage.content, title: uiMessage.title, messageOptions: uiMessage.messageOptions, execCode: uiMessage.execCode});
546
+ if (uiMessage.fromUser) {
547
+ const promptText = ui.divText(uiMessage.content, 'd4-ai-user-prompt-divtext');
548
+ const userDiv = ui.div(
549
+ uiMessage.messageOptions?.handledNatively ? [this.createHandledNativelyIcon(), promptText] : [promptText],
550
+ 'd4-ai-user-prompt-container');
551
+ this.outputArea.appendChild(userDiv);
552
+ if (this._pendingAttachmentsForRender.length) {
553
+ const chips = this._pendingAttachmentsForRender.map((e) => {
554
+ const icon = DG.ObjectHandler.forEntity(e)?.renderIcon(e.dart) ?? ui.iconFA('tag');
555
+ const label = ui.label(e.friendlyName ?? e.name);
556
+ return ui.divH([icon, label], 'grokky-entity-chip');
557
+ });
558
+ const chipsRow = ui.divH(chips, {style: {flexWrap: 'wrap', justifyContent: 'flex-end'}});
559
+ this.outputArea.appendChild(chipsRow);
560
+ this._pendingAttachmentsForRender = [];
561
+ }
562
+ this._lastUserPromptContainer = userDiv;
563
+ this._aiMessagesAccordionPane = null; // reset accordion pane so that next AI message creates a new one
564
+ } else if (uiMessage.messageOptions?.system) {
565
+ this.outputArea.appendChild(ui.divText(uiMessage.content, 'grokky-system-message'));
566
+ this._aiMessagesAccordionPane = null;
567
+ } else {
568
+ this.ensureResponseBlock();
569
+ const markDown = this.createStyledMarkdown(uiMessage.content);
570
+
571
+ if (uiMessage?.messageOptions?.finalResult && !uiMessage.fromUser) {
572
+ this.appendFeedbackButtons(markDown, (helpful) => {
573
+ receiveFeedback(
574
+ this._uiMessages[0]?.text ?? '',
575
+ uiMessage?.messageOptions?.finalResult!,
576
+ this.contextId,
577
+ helpful
578
+ );
579
+ }, uiMessage.execCode?.length ? {codes: uiMessage.execCode, ranThisSession: false} : undefined);
580
+ }
581
+
582
+ if (uiMessage?.messageOptions?.confirm && !uiMessage.fromUser) {
583
+ let resolve: (value: boolean) => void = () => {};
584
+ const confirmPromise = new Promise<boolean>((res) => { resolve = res; });
585
+ ret = {confirmPromise: confirmPromise};
586
+ const confirmDiv = ui.divV([], 'd4-ai-panel-confirmation-div');
587
+ const confirmText = ui.divText(uiMessage?.messageOptions?.confirm.message ?? 'Allow Datagrok to proceed?', 'd4-ai-panel-confirmation-text');
588
+ const buttonsDiv = ui.divH([], 'd4-ai-panel-confirmation-buttons-div');
589
+ const confirmButton = ui.iconFA('check', null, 'Confirm');
590
+ const cancelButton = ui.iconFA('times', null, 'Cancel');
591
+ dartLike(confirmButton.style).set('padding', '2px').set('borderRadius', '6px').set('marginRight', '2px').set('textAlign', 'center').set('width', '14px');
592
+ dartLike(cancelButton.style).set('padding', '2px').set('borderRadius', '6px').set('textAlign', 'center').set('width', '14px');
593
+ // if the result of confirmation is already set, do not subscribe to changes
594
+ const handleConfirmResult = (confirmed: boolean) => {
595
+ // make sure the reference of the result is also marked
596
+ uiMessage?.messageOptions?.confirm && (uiMessage.messageOptions.confirm.confirmResult = confirmed);
597
+ resolve(confirmed);
598
+ [confirmButton, cancelButton].forEach((el) => {
599
+ el.onclick = null;
600
+ dartLike(el.style).set('backgroundColor', '').set('cursor', 'default').set('opacity', '0.6').set('pointerEvents', 'none');
601
+ });
602
+ (confirmed ? confirmButton : cancelButton).style.backgroundColor = confirmed ? 'rgba(0, 150, 30, 0.3)' : 'rgba(200, 0, 0, 0.3)';
603
+ };
604
+ confirmButton.onclick = () => handleConfirmResult(true);
605
+ cancelButton.onclick = () => handleConfirmResult(false);
606
+ buttonsDiv.appendChild(confirmButton);
607
+ buttonsDiv.appendChild(cancelButton);
608
+ confirmDiv.appendChild(confirmText);
609
+ confirmDiv.appendChild(buttonsDiv);
610
+ markDown.appendChild(confirmDiv);
611
+ if (uiMessage?.messageOptions?.confirm.confirmResult != undefined)
612
+ handleConfirmResult(uiMessage?.messageOptions?.confirm.confirmResult); // already have a result
613
+ }
614
+
615
+ const titleText = uiMessage.title ? [ui.h3(uiMessage.title, 'd4-ai-assistant-response-title')] : [];
616
+ const assistantDiv = ui.divV([...titleText, markDown], 'd4-ai-assistant-response-container');
617
+ this._aiMessagesAccordionPane!.appendChild(assistantDiv);
618
+ }
619
+ this.outputArea.scrollTop = this.outputArea.scrollHeight;
620
+ this.showContentIcons();
621
+ return ret;
622
+ }
623
+
624
+ public startChatSession(): {session: AIPanelFuncs<T>, endSession: () => void} {
625
+ const spinner = ui.icons.loader();
626
+ // Speech is easy to mishear, so while the AI works in voice mode show the word that aborts the run.
627
+ const cancelHint = ui.divText('Say "cancel" to stop', 'd4-ai-voice-cancel-hint');
628
+ cancelHint.style.display = this.isRecognizing ? '' : 'none';
629
+ this._voiceCancelHint = cancelHint;
630
+ this.statusRepeats = 0;
631
+ this.dismissQuestion();
632
+ this.setStatus('Thinking…');
633
+ const loader = ui.divH([spinner, this.statusLabel, cancelHint], 'd4-ai-loader');
634
+ ui.empty(this.statusBar);
635
+ this.statusBar.appendChild(loader);
636
+ this.runButton.classList.remove('fal', 'fa-paper-plane');
637
+ this.runButton.classList.add('fas', 'fa-stop');
638
+ this.runButtonTooltip = actionButtionValues.stop;
639
+ this.syncConversationButtons();
640
+ return {
641
+ session: {
642
+ addAIMessage: (aiMessage, title, content) => this.appendMessage(aiMessage, {title: title, content: content, fromUser: false}),
643
+ addEngineMessage: (aiMessage) => this.appendMessage(aiMessage, {title: '', content: '', fromUser: false, onlyAddToMessages: true}),
644
+ addUiMessage: (msg: string, fromUser: boolean, messageOptions?: UIMessageOptions) => this.appendMessage('' as any, {title: '', content: msg, fromUser: fromUser, uiOnly: true, messageOptions: messageOptions}),
645
+ markHandledNatively: () => this.markPromptHandledNatively(),
646
+ addUserMessage: (aiMsg, content) => this.appendMessage(aiMsg, {title: '', content: content, fromUser: true}),
647
+ addConfirmMessage: (msg?: string) => this.appendMessage('' as any, {title: '', content: '', fromUser: false, uiOnly: true, messageOptions: {confirm: {message: msg}}})!.confirmPromise,
648
+ showInputRequest: (input: AskUserInput) => this.showInputRequest(input),
649
+ },
650
+ endSession: () => {
651
+ this.runButton.classList.remove('fas', 'fa-stop');
652
+ this.runButton.classList.add('fal', 'fa-paper-plane');
653
+ this.runButtonTooltip = actionButtionValues.run;
654
+ this.syncConversationButtons();
655
+ this._voiceCancelHint = null;
656
+ this.saveCurrentConversation().catch((e) => console.error('Failed to save conversation before hiding panel:', e));
657
+ loader.remove();
658
+ }
659
+ };
660
+ }
661
+
662
+ get rawRender(): boolean { return this._rawRender; }
663
+ get noPrompt(): boolean { return this._noPrompt; }
664
+
665
+ public appendArtifact(node: HTMLElement): void {
666
+ this.outputArea.appendChild(ui.divV([node], 'd4-ai-assistant-response-container'));
667
+ this.showContentIcons();
668
+ }
669
+
670
+ /** Removes any pending inline choice blocks — they're transient and shouldn't linger once
671
+ * the user moves on (submits a prompt, gets a new message, or opens another picker). */
672
+ private removeChoiceBlocks(): void {
673
+ const blocks = this.outputArea.querySelectorAll('.grokky-choice-container');
674
+ for (let i = 0; i < blocks.length; i++)
675
+ blocks[i].remove();
676
+ }
677
+
678
+ /** Renders an inline choice block that reads like an assistant reply (used by suggestion actions).
679
+ * Picking an option removes the block; the option's handler adds its own follow-up message. */
680
+ public addChoice(prompt: string | null, options: ChoiceOption[]): void {
681
+ const emptyState = this.outputArea.querySelector('.grokky-empty-state');
682
+ if (emptyState) {
683
+ emptyState.remove();
684
+ this.setWandVisible(true);
685
+ }
686
+ this.removeChoiceBlocks();
687
+ const container = ui.divV([], 'd4-ai-assistant-response-container grokky-choice-container');
688
+ const cards = options.map((o) => {
689
+ const card = ui.div(ui.divText(o.label), 'grokky-choice-card');
690
+ card.onclick = () => {
691
+ container.remove();
692
+ o.onSelect();
693
+ };
694
+ return card;
695
+ });
696
+ const children: HTMLElement[] = [];
697
+ if (prompt)
698
+ children.push(this.createStyledMarkdown(prompt));
699
+ children.push(ui.divH(cards, 'grokky-choice-row'));
700
+ container.appendChild(ui.divV(children, 'grokky-choice-block'));
701
+ this.outputArea.appendChild(container);
702
+ this.showContentIcons();
703
+ }
704
+
705
+ /** Appends a short assistant-style note (e.g. an action's result confirmation) to the transcript. */
706
+ public addNote(markdown: string): void {
707
+ this.appendMessage('' as any, {title: '', content: markdown, fromUser: false, uiOnly: true});
708
+ }
709
+
710
+ enableNoPrompt(): void {
711
+ this._noPrompt = true;
712
+ if (!this._rawRender) {
713
+ this._rawRender = true;
714
+ this.rawRenderButton.style.color = 'var(--blue-1)';
715
+ this.root.classList.add('d4-ai-raw-mode');
716
+ }
717
+ this.resetSession();
718
+ this.handleClear();
719
+ }
720
+
721
+ pushNativeContext(prompt: string): void {
722
+ this._pendingNativeContext.push(prompt);
723
+ }
724
+
725
+ /** Serializes the restored messages into a compact transcript the model can act on
726
+ * ("reproduce what we did") — includes executed code blocks recorded as engine messages. */
727
+ restoredTranscript(): string {
728
+ const messages = this._messages[this._messages.length - 1]?.role === 'user' ?
729
+ this._messages.slice(0, -1) : this._messages;
730
+ const parts: string[] = [];
731
+ for (const m of messages) {
732
+ const c: any = (m as any).content;
733
+ const text = typeof c === 'string' ? c :
734
+ Array.isArray(c) ? c.map((x: any) => x?.text ?? '').filter((x: string) => x).join('\n') : '';
735
+ if (!text.trim())
736
+ continue;
737
+ const role = (m as any).role === 'user' ? 'USER' : 'ASSISTANT';
738
+ parts.push(`${role}: ${text.length > 1500 ? text.slice(0, 1500) + ' …[truncated]' : text}`);
739
+ }
740
+ let out = parts.join('\n');
741
+ if (out.length > 9000)
742
+ out = out.slice(0, 4500) + '\n[... middle of the conversation truncated ...]\n' + out.slice(-4500);
743
+ return out ?
744
+ '[Conversation restored from saved history — you have no memory of it. ' +
745
+ 'The transcript below is what happened earlier; treat it as this conversation\'s history. ' +
746
+ 'ASSISTANT entries starting with "[executed datagrok_exec]" are code that actually ran.]\n' +
747
+ out : '';
748
+ }
749
+
750
+ flushNativeContext(): string {
751
+ if (this._pendingNativeContext.length === 0)
752
+ return '';
753
+ const items = `- "${this._pendingNativeContext.join('"\n- "')}"`;
754
+ this._pendingNativeContext = [];
755
+ return `[The user previously asked:]\n${items}\n\n`;
756
+ }
757
+
758
+ resetSession(): void {
759
+ this._sessionId = `${this._feature}-${crypto.randomUUID()}`;
760
+ this._streamingContainer = null;
761
+ this._streamingMarkdownEl = null;
762
+ }
763
+
764
+ prependViewContext(prompt: string, _view: DG.ViewBase): string {
765
+ const ctx = buildWorkspaceContext();
766
+ if (!ctx)
767
+ return prompt;
768
+ return ctx + '\n---\n\n' + prompt;
769
+ }
770
+
771
+ private createStreamingEl(content: string): HTMLElement | null {
772
+ if (this._rawRender) {
773
+ const pre = document.createElement('pre');
774
+ pre.textContent = content;
775
+ pre.style.cssText = 'white-space:pre-wrap;user-select:text;margin:0';
776
+ return pre;
777
+ }
778
+ const md = tryMarkdown(content);
779
+ if (md)
780
+ dartLike(md.style).set('userSelect', 'text').set('maxWidth', '100%');
781
+ return md;
782
+ }
783
+
784
+ updateStreaming(content: string): void {
785
+ if (!this._streamingContainer) {
786
+ this.ensureResponseBlock();
787
+ this._streamingMarkdownEl = this.createStreamingEl(content) ?? plainTextEl(content);
788
+ this._streamingContainer = ui.divV([this._streamingMarkdownEl], 'd4-ai-assistant-response-container');
789
+ this._aiMessagesAccordionPane!.appendChild(this._streamingContainer);
790
+ } else {
791
+ const el = this.createStreamingEl(content);
792
+ if (el) {
793
+ this._streamingMarkdownEl!.replaceWith(el);
794
+ this._streamingMarkdownEl = el;
795
+ }
796
+ }
797
+ this.scrollIfFollowing();
798
+ }
799
+
800
+ setStatus(text: string): void {
801
+ if (this.statusRepeats && this.statusLabel.dataset.status === text) {
802
+ this.statusLabel.textContent = `${text} \u00d7${++this.statusRepeats}`;
803
+ return;
804
+ }
805
+ this.statusRepeats = 1;
806
+ this.statusLabel.dataset.status = text;
807
+ this.statusLabel.textContent = text;
808
+ this.statusLabel.classList.remove('grokky-status-in');
809
+ void this.statusLabel.offsetWidth;
810
+ this.statusLabel.classList.add('grokky-status-in');
811
+ }
812
+
813
+ showError(text: string): void {
814
+ const error = ui.divText(text, 'grokky-status-error');
815
+ ui.tooltip.bind(error, text);
816
+ ui.empty(this.statusBar);
817
+ this.statusBar.appendChild(error);
818
+ }
819
+
820
+ private scrollIfFollowing(): void {
821
+ if (this.followOutput)
822
+ this.outputArea.scrollTop = this.outputArea.scrollHeight;
823
+ }
824
+
825
+ async finalizeStreaming(displayContent: string, execCodes: string[], view: DG.ViewBase): Promise<void> {
826
+ if (this._rawRender) {
827
+ this._streamingMarkdownEl = null;
828
+ this._streamingContainer = null;
829
+ this._uiMessages.push({fromUser: false, text: displayContent, execCode: execCodes.length ? execCodes : undefined, messageOptions: {finalResult: displayContent}});
830
+ return;
831
+ }
832
+ this.renderFinalContent(displayContent, execCodes, view);
833
+ }
834
+
835
+ public appendStreamedElement(el: HTMLElement): void {
836
+ this.ensureResponseBlock();
837
+ this._aiMessagesAccordionPane!.appendChild(ui.divV([el], 'd4-ai-assistant-response-container'));
838
+ this._streamingContainer = null;
839
+ this._streamingMarkdownEl = null;
840
+ this.scrollIfFollowing();
841
+ }
842
+
843
+ public appendUiMessage(content: string): void {
844
+ this.appendMessage('' as any, {title: '', fromUser: false, uiOnly: true, content, messageOptions: {system: true}});
845
+ }
846
+
847
+ protected renderFinalContent(content: string, execCodes: string[], view: DG.ViewBase): void {
848
+ const markDown = this.createStyledMarkdown(content);
849
+ this.appendFeedbackButtons(markDown, undefined,
850
+ execCodes.length ? {codes: execCodes, ranThisSession: true, view} : undefined);
851
+
852
+ if (this._streamingMarkdownEl) {
853
+ this._streamingMarkdownEl.replaceWith(markDown);
854
+ this._streamingMarkdownEl = null;
855
+ this._streamingContainer = null;
856
+ } else if (content || execCodes.length) {
857
+ this.ensureResponseBlock();
858
+ this._aiMessagesAccordionPane!.appendChild(ui.divV([markDown], 'd4-ai-assistant-response-container'));
859
+ }
860
+
861
+ this._uiMessages.push({fromUser: false, text: content, execCode: execCodes.length ? execCodes : undefined, messageOptions: {finalResult: content}});
862
+ }
863
+
864
+ clearStreaming(): void {
865
+ this._streamingContainer?.remove();
866
+ this._streamingContainer = null;
867
+ this._streamingMarkdownEl = null;
868
+ }
869
+
870
+ showInputRequest(input: AskUserInput): void {
871
+ const questions = input.questions ?? [];
872
+ const answers = questions.map((q) => q.options[0]?.label ?? '');
873
+ const sections = questions.map((q, i): QuestionSection => {
874
+ const pills: HTMLElement[] = q.options.map((o) => {
875
+ const pill = ui.divText(o.label, 'grokky-choice-card');
876
+ if (o.description)
877
+ ui.tooltip.bind(pill, o.description);
878
+ pill.onclick = () => {
879
+ answers[i] = o.label;
880
+ pills.forEach((p) => p.classList.toggle('grokky-choice-selected', p === pill));
881
+ };
882
+ return pill;
883
+ });
884
+ pills[0]?.classList.add('grokky-choice-selected');
885
+ return {
886
+ strip: ui.divH([ui.divText(q.question)], 'grokky-strip grokky-strip-question'),
887
+ body: ui.div([ui.divH(pills, 'grokky-choice-row')], 'grokky-confirm-body'),
888
+ };
889
+ });
890
+ const close = (style: StripStyle, icon: string, answerText: (questionIdx: number) => string): void => {
891
+ this._dismissQuestion = null;
892
+ footer.remove();
893
+ sections.forEach((s, i) => {
894
+ s.body.remove();
895
+ s.strip.classList.replace('grokky-strip-question', `grokky-strip-${style}`);
896
+ s.strip.append(ui.divH([ui.iconFA(icon), ui.divText(answerText(i))], 'grokky-strip-answer'));
897
+ });
898
+ };
899
+ this.dismissQuestion();
900
+ this._dismissQuestion = () => close('muted', 'minus', () => 'Not answered');
901
+ const footer = ui.divH([ui.bigButton('Submit', () => {
902
+ if (this.isBusy)
903
+ return;
904
+ close('success', 'check', (i) => answers[i]);
905
+ const prompt = questions.length === 1 ? answers[0] :
906
+ questions.map((q, i) => `${q.question} ${answers[i]}`).join('\n');
907
+ this._onRunRequest.next({prevMessages: this._messages, currentPrompt: {prompt, isAnswer: true} as K});
908
+ this.textArea.focus();
909
+ })], 'grokky-question-footer');
910
+
911
+ const card = ui.divV([...sections.flatMap((s) => [s.strip, s.body]), footer],
912
+ 'grokky-confirm-card grokky-question-card');
913
+ this.ensureResponseBlock();
914
+ this._aiMessagesAccordionPane!.appendChild(ui.divV([card], 'd4-ai-assistant-response-container'));
915
+ this.outputArea.scrollTop = this.outputArea.scrollHeight;
916
+ }
917
+
918
+ dismissQuestion(): void {
919
+ this._dismissQuestion?.();
920
+ }
921
+
922
+ private tryAgain() {
923
+ if (this._messages.length === 0)
924
+ return; // should never happen, but just in case
925
+ // The prompt itself is resent: a request stopped before the agent picked it up is not in its history.
926
+ const last = this.promptHistory.pop();
927
+ if (!last || this.isBusy)
928
+ return;
929
+ const inputs = this.getCurrentInputs();
930
+ inputs.prompt = last;
931
+ this._onRunRequest.next({
932
+ prevMessages: [...this._messages],
933
+ currentPrompt: inputs,
934
+ });
935
+ }
936
+
937
+ private terminate() {
938
+ fireAIAbortEvent();
939
+ }
940
+
941
+ /** Prompts the user submitted in this session, oldest first — the navigable input history. */
942
+ private get promptHistory(): string[] {
943
+ return this._uiMessages.filter((m) => m.fromUser).map((m) => m.text);
944
+ }
945
+
946
+ /** Replaces the input with the previous (-1) or next (+1) prompt from this session's history; false if there is none. */
947
+ private navigatePromptHistory(direction: -1 | 1): boolean {
948
+ const hist = this.promptHistory;
949
+ const current = this._promptHistoryIndex ?? hist.length;
950
+ const next = current + direction;
951
+ if (next < 0 || next > hist.length)
952
+ return false;
953
+ if (this._promptHistoryIndex === null)
954
+ this._promptDraft = this.textArea.value;
955
+ this._promptHistoryIndex = next === hist.length ? null : next;
956
+ this.textArea.value = next === hist.length ? this._promptDraft : hist[next];
957
+ this.textArea.selectionStart = this.textArea.selectionEnd = this.textArea.value.length;
958
+ return true;
959
+ }
960
+
961
+ protected handleRun() {
962
+ if (this.isBusy)
963
+ return;
964
+ if (!this.textArea.value.trim())
965
+ return;
966
+ const inputs = this.getCurrentInputs();
967
+ this.textArea.value = '';
968
+ this._pendingEntityContext = this.attachedEntities.length ?
969
+ 'Attached Datagrok entities (use MCP tools to fetch full details by id/nqName/path):\n' +
970
+ this.attachedEntities.map((e) => this.describeEntity(e)).join('\n') :
971
+ '';
972
+ this._pendingAttachmentsForRender = [...this.attachedEntities];
973
+ this.clearAttachments();
974
+ this._promptHistoryIndex = null;
975
+ this._onRunRequest.next({
976
+ prevMessages: this._messages,
977
+ currentPrompt: inputs,
978
+ });
979
+ }
980
+
981
+ protected showContentIcons() {
982
+ this.newChatButton.style.display = 'flex';
983
+ this.tryAgainButton.style.display = 'flex';
984
+ this.copyConversationButton.style.display = 'flex';
985
+ }
986
+
987
+ protected hideContentIcons() {
988
+ this.newChatButton.style.display = 'none';
989
+ this.tryAgainButton.style.display = 'none';
990
+ this.copyConversationButton.style.display = 'none';
991
+ }
992
+
993
+ protected handleClear() {
994
+ this._messages = [];
995
+ this._uiMessages = [];
996
+ this._pendingNativeContext = [];
997
+ this._promptHistoryIndex = null;
998
+ this._lastUserPromptContainer = null;
999
+ this.outputArea.innerHTML = '';
1000
+ this._onClearChatRequest.next();
1001
+ this.hideContentIcons();
1002
+ this.renderEmptyState();
1003
+ }
1004
+
1005
+ protected runSuggestion(s: Suggestion): void {
1006
+ if (!runSuggestionAction(s.action, this)) {
1007
+ this.textArea.value = s.prompt ?? '';
1008
+ this.handleRun();
1009
+ }
1010
+ this.textArea.focus();
1011
+ }
1012
+
1013
+ /** The view the panel currently works against: the pinned one for owned panels, else the live current view. */
1014
+ protected get liveView(): DG.View | DG.ViewBase | null {
1015
+ return this.view ?? grok.shell.v;
1016
+ }
1017
+
1018
+ protected shouldShowEmptyState(): boolean {
1019
+ // Global suggestions (Anywhere, Code generation) apply on any view, so show the empty state
1020
+ // and wand everywhere — not just on table views (view/column blocks self-add when applicable).
1021
+ return this._uiMessages.length === 0;
1022
+ }
1023
+
1024
+ private setWandVisible(visible: boolean): void {
1025
+ this.wandButton.style.display = visible ? '' : 'none';
1026
+ }
1027
+
1028
+ /** Rebuilds the suggestion cards for the current view; removes them when they no longer apply. */
1029
+ protected async renderEmptyState(): Promise<void> {
1030
+ const seq = ++this._emptyStateSeq;
1031
+ const removeExisting = () => this.outputArea.querySelector('.grokky-empty-state')?.remove();
1032
+ if (!this.shouldShowEmptyState()) {
1033
+ removeExisting();
1034
+ this.setWandVisible(true);
1035
+ return;
1036
+ }
1037
+ const scopes = await resolveScopes('panel', this.liveView);
1038
+ if (seq !== this._emptyStateSeq || !this.shouldShowEmptyState())
1039
+ return;
1040
+ removeExisting();
1041
+
1042
+ const accordion = ui.accordion();
1043
+ const defaultOpenCategories = 1;
1044
+ scopes.forEach((s, i) => this.addSuggestionCategory(accordion, s, i < defaultOpenCategories));
1045
+
1046
+ const root = ui.panel([ui.h2('I\'m Grokky, your AI assistant. What can I help you with?'), accordion.root], 'grokky-empty-state');
1047
+ this.outputArea.appendChild(root);
1048
+ this.setWandVisible(false);
1049
+ }
1050
+
1051
+ private addSuggestionCategory(accordion: DG.Accordion, s: Block, expanded: boolean): void {
1052
+ const pane = accordion.addPane(s.label, () => {
1053
+ const rows = s.suggestions.map((sg) => {
1054
+ const row = ui.divText(sg.label ?? sg.prompt ?? '', 'grokky-suggestion-item');
1055
+ row.onclick = () => this.runSuggestion(sg);
1056
+ if (sg.prompt && sg.label && sg.label !== sg.prompt)
1057
+ ui.tooltip.bind(row, () => sg.prompt ?? '');
1058
+ return row;
1059
+ });
1060
+ return ui.divV(rows);
1061
+ }, expanded);
1062
+
1063
+ const icon = ui.iconFA(s.icon ?? 'circle');
1064
+ icon.classList.add('grokky-scope-icon');
1065
+ if (s.color)
1066
+ icon.style.color = s.color;
1067
+ pane.root.querySelector('.d4-accordion-pane-header')?.prepend(icon);
1068
+ }
1069
+
1070
+ private async showHistory() {
1071
+ if (this.isBusy)
1072
+ return;
1073
+ try {
1074
+ const conversations = await ConversationStorage.listConversations(
1075
+ this.contextId,
1076
+ 10
1077
+ ) as StoredConversationWithContext<T>[];
1078
+
1079
+ if (conversations.length === 0) {
1080
+ grok.shell.info('No conversation history found');
1081
+ return;
1082
+ }
1083
+
1084
+ const menu = DG.Menu.popup();
1085
+ const deleting = new Map<string, number>();
1086
+ const finish = (id: string, remove: boolean) => {
1087
+ clearTimeout(deleting.get(id));
1088
+ deleting.delete(id);
1089
+ if (remove)
1090
+ ConversationStorage.deleteConversation(id).catch(() => grok.shell.error('Failed to delete chat'));
1091
+ };
1092
+ for (const conv of conversations) {
1093
+ if (this.currentConversationId && conv.id === this.currentConversationId)
1094
+ continue;
1095
+ const date = new Date(conv.timestamp).toLocaleString();
1096
+ const preview = conv.initialPrompt.substring(0, 40).replace(/\|/g, '/'); // '|' would make a submenu
1097
+ const displayText = `${preview}${conv.initialPrompt.length > 40 ? '...' : ''} (${date})`;
1098
+
1099
+ menu.item(displayText, () => {
1100
+ finish(conv.id, false);
1101
+ this.loadConversation(conv.id);
1102
+ });
1103
+ const row = menu.root.querySelector('.d4-menu-item:last-child')!;
1104
+ const toggle = (e: MouseEvent) => {
1105
+ e.stopPropagation();
1106
+ finish(conv.id, false);
1107
+ if (row.classList.toggle('grokky-history-deleted')) {
1108
+ deleting.set(conv.id, window.setTimeout(() => {
1109
+ row.remove();
1110
+ finish(conv.id, true);
1111
+ }, 5000));
1112
+ }
1113
+ };
1114
+ const trash = ui.icons.delete(toggle, 'Delete chat');
1115
+ const undo = ui.icons.undo(toggle, 'Undo');
1116
+ trash.classList.add('grokky-history-icon', 'grokky-history-delete');
1117
+ undo.classList.add('grokky-history-icon', 'grokky-history-undo', 'grok-icon-blue');
1118
+ row.append(trash, undo);
1119
+ }
1120
+ menu.onClose.subscribe(() => Array.from(deleting.keys()).forEach((id) => finish(id, true)));
1121
+
1122
+ menu.separator();
1123
+ menu.item('Clear All History', async () => {
1124
+ // if (await grok.shell.('Delete all conversation history?')) {
1125
+ // await ConversationStorage.clearAll();
1126
+ // grok.shell.info('History cleared');
1127
+ // }
1128
+ ui.dialog('Delete all conversation history').add(ui.divText('This action will permanently delete all saved conversations. Are you sure you want to proceed?'))
1129
+ .onOK(async () => {
1130
+ await ConversationStorage.clearAll();
1131
+ this.currentConversationId = null;
1132
+ grok.shell.info('History cleared');
1133
+ }).show();
1134
+ });
1135
+
1136
+ menu.show();
1137
+ } catch (error) {
1138
+ console.error('Failed to load history:', error);
1139
+ grok.shell.error('Failed to load conversation history');
1140
+ }
1141
+ }
1142
+ private async loadConversation(conversationId: string) {
1143
+ try {
1144
+ const conv = (await ConversationStorage.getConversation(conversationId)) as StoredConversationWithContext<T> | null;
1145
+ if (!conv) {
1146
+ grok.shell.error('Conversation not found');
1147
+ return;
1148
+ }
1149
+
1150
+ this.currentConversationId = conversationId;
1151
+ this._messages = conv.messages;
1152
+
1153
+ // Clear and rebuild UI from messages
1154
+ this.outputArea.innerHTML = '';
1155
+ this._uiMessages = [];
1156
+ this._promptHistoryIndex = null;
1157
+ this._lastUserPromptContainer = null;
1158
+ conv.uiMessages.forEach((msg) => {
1159
+ this.appendMessage(null as any, {title: msg.title ?? '', content: msg.text, fromUser: msg.fromUser, uiOnly: true, messageOptions: msg.messageOptions, execCode: msg.execCode}); // no loader
1160
+ });
1161
+ this.resetSession();
1162
+ // Chat history is per browser, so only the user who saved the chat resumes its runtime session.
1163
+ const meta = conv.meta;
1164
+ if (meta?.sessionId && meta.userId === grok.shell.user.id) {
1165
+ this._sessionId = meta.sessionId;
1166
+ ClaudeRuntimeClient.getInstance().expectResume(meta.sessionId);
1167
+ }
1168
+ this.afterConversationLoad(conv);
1169
+ this.textArea.focus();
1170
+ //grok.shell.info(`Loaded conversation: ${conv.initialPrompt.substring(0, 50)}...`);
1171
+ } catch (error) {
1172
+ console.error('Failed to load conversation:', error);
1173
+ grok.shell.error('Failed to load conversation');
1174
+ }
1175
+ }
1176
+
1177
+ protected afterConversationLoad(conversation: StoredConversationWithContext<T>) {
1178
+ // do nothing in base class
1179
+ }
1180
+
1181
+ protected getConversationMeta(): {sessionId: string, userId: string} {
1182
+ return {sessionId: this._sessionId, userId: grok.shell.user.id};
1183
+ }
1184
+
1185
+ public async saveCurrentConversation(initialPrompt?: string) {
1186
+ if (this._messages.length === 0) return;
1187
+
1188
+ try {
1189
+ if (this.currentConversationId)
1190
+ await ConversationStorage.updateConversation(this.currentConversationId, this._messages, this._uiMessages, this.getConversationMeta());
1191
+ else {
1192
+ this.currentConversationId = await ConversationStorage.saveConversation(
1193
+ this._messages, this._uiMessages, initialPrompt ?? this._uiMessages[0]?.text ?? 'No Title', this.contextId, this.getConversationMeta()
1194
+ );
1195
+ }
1196
+ } catch (error) {
1197
+ console.error('Failed to save conversation:', error);
1198
+ }
1199
+ }
1200
+
1201
+ private toggleSpeechRecognition() {
1202
+ if (this.micAccessDenied)
1203
+ return;
1204
+ if (this.isRecognizing)
1205
+ this.stopRecognition();
1206
+ else
1207
+ this.startRecognition();
1208
+ }
1209
+
1210
+ /** The voice escape hatch only matters while the mic is live — keep the loader caption in sync. */
1211
+ private syncVoiceCancelHint() {
1212
+ if (this._voiceCancelHint)
1213
+ this._voiceCancelHint.style.display = this.isRecognizing ? '' : 'none';
1214
+ }
1215
+
1216
+ private async checkMicPermission(): Promise<void> {
1217
+ if (!navigator.permissions?.query)
1218
+ return;
1219
+
1220
+ try {
1221
+ const status = await navigator.permissions.query({name: 'microphone' as PermissionName});
1222
+ this.applyMicPermissionStatus(status.state);
1223
+ status.onchange = () => this.applyMicPermissionStatus(status.state);
1224
+ } catch (error) {
1225
+ console.error('Failed to query microphone permission:', error);
1226
+ }
1227
+ }
1228
+
1229
+ private applyMicPermissionStatus(state: PermissionState): void {
1230
+ this.setMicDisabled(state === 'denied' ? micTooltips.accessDenied : null);
1231
+ }
1232
+
1233
+ private setMicDisabled(reason: string | null): void {
1234
+ this.micAccessDenied = reason != null;
1235
+ ui.setDisabled(this.micButton, this.micAccessDenied, reason ?? micTooltips.default);
1236
+ }
1237
+
1238
+ private startRecognition() {
1239
+ this.isRecognizing = true;
1240
+ this.voiceTranscript = '';
1241
+ this.micButton.classList.remove('fa-microphone');
1242
+ this.micButton.classList.add('fa-stop');
1243
+ this.micButton.style.color = 'orangered';
1244
+ this.syncVoiceCancelHint();
1245
+ this.listen();
1246
+ }
1247
+
1248
+ /** Starts a recognition session. Chrome ends a continuous session on its own after a while or on
1249
+ * a network hiccup; `onend` then calls this again, keeping the phrase heard so far. */
1250
+ private listen() {
1251
+ try {
1252
+ // Continuous mode, so a pause between words does not end the phrase: Chrome's own end-of-speech
1253
+ // detection cut it after the first word for mics that gate the signal to silence between words.
1254
+ // The phrase is submitted after VOICE_SUBMIT_DELAY_MS without new speech instead.
1255
+ this.recognition = new SpeechRecognition();
1256
+ this.recognition.continuous = true;
1257
+ this.recognition.interimResults = true;
1258
+ this.recognition.lang = 'en-US';
1259
+ if (!this.voiceTranscript)
1260
+ ui.setUpdateIndicator(this.textAreaDiv, true, 'Listening...');
1261
+
1262
+ this.recognition.onresult = (event) => {
1263
+ ui.setUpdateIndicator(this.textAreaDiv, false);
1264
+ let interim = '';
1265
+ for (let i = event.resultIndex; i < event.results.length; i++) {
1266
+ const text = event.results[i][0].transcript;
1267
+ if (!event.results[i].isFinal) {
1268
+ interim += text;
1269
+ continue;
1270
+ }
1271
+ const command = text.trim().replace(/[.,;:!?]+$/, '').toLowerCase();
1272
+ if (command === 'stop' || command === 'cancel') {
1273
+ this.onVoiceCancel();
1274
+ return;
1275
+ }
1276
+ this.voiceTranscript += text;
1277
+ }
1278
+
1279
+ // Speech while the AI works is not a prompt (one can't be submitted yet); only "stop"/"cancel"
1280
+ // counts then, to abort the run.
1281
+ if (this.isBusy) {
1282
+ this.voiceTranscript = '';
1283
+ return;
1284
+ }
1285
+
1286
+ this._promptHistoryIndex = null;
1287
+ this.textArea.value = (this.voiceTranscript + interim).trim();
1288
+ window.clearTimeout(this.voiceSubmitTimer);
1289
+ this.voiceSubmitTimer = window.setTimeout(() => this.submitVoicePrompt(), VOICE_SUBMIT_DELAY_MS);
1290
+ };
1291
+
1292
+ this.recognition.onerror = (event) => {
1293
+ if (event.error === 'no-speech')
1294
+ return; // silence timeout — onend restarts the mic, no user action needed
1295
+ if (event.error !== 'aborted')
1296
+ console.error('Speech recognition error:', event.error);
1297
+ ui.setUpdateIndicator(this.textAreaDiv, false);
1298
+
1299
+ let errorMessage = 'Speech recognition error';
1300
+ switch (event.error) {
1301
+ case 'audio-capture':
1302
+ errorMessage = micTooltips.noDevice;
1303
+ this.setMicDisabled(micTooltips.noDevice);
1304
+ break;
1305
+ case 'not-allowed':
1306
+ errorMessage = micTooltips.accessDenied;
1307
+ this.setMicDisabled(micTooltips.accessDenied);
1308
+ break;
1309
+ case 'network':
1310
+ errorMessage = 'Network error during speech recognition';
1311
+ break;
1312
+ case 'aborted':
1313
+ // Something else took the microphone, e.g. voice input in another tab: no error message needed
1314
+ break;
1315
+ default:
1316
+ errorMessage = `Speech recognition error: ${event.error}`;
1317
+ }
1318
+
1319
+ if (event.error !== 'aborted')
1320
+ grok.shell.error(errorMessage);
1321
+
1322
+
1323
+ this.stopRecognition();
1324
+ };
1325
+
1326
+ this.recognition.onend = () => {
1327
+ if (this.isRecognizing)
1328
+ this.listen();
1329
+ };
1330
+
1331
+ this.recognition.start();
1332
+ } catch (error) {
1333
+ console.error('Failed to start speech recognition:', error);
1334
+ grok.shell.error('Failed to start speech recognition');
1335
+ this.stopRecognition();
1336
+ }
1337
+ }
1338
+
1339
+ /** "stop"/"cancel" aborts the AI run while it works, and otherwise drops the phrase and the mic. */
1340
+ private onVoiceCancel() {
1341
+ window.clearTimeout(this.voiceSubmitTimer);
1342
+ this.voiceTranscript = '';
1343
+ if (this.isBusy) {
1344
+ this.terminate();
1345
+ return;
1346
+ }
1347
+ this._promptHistoryIndex = null;
1348
+ this.textArea.value = '';
1349
+ this.stopRecognition();
1350
+ this.textArea.focus();
1351
+ }
1352
+
1353
+ private submitVoicePrompt() {
1354
+ this.voiceTranscript = '';
1355
+ this.handleRun();
1356
+ }
1357
+
1358
+ /** Stops listening; a phrase heard so far stays in the prompt box, unsent, to edit or send by hand. */
1359
+ private stopRecognition() {
1360
+ this.isRecognizing = false;
1361
+ this.voiceTranscript = '';
1362
+ window.clearTimeout(this.voiceSubmitTimer);
1363
+ this.syncVoiceCancelHint();
1364
+
1365
+ if (this.recognition) {
1366
+ // A stopped session can still report late; it must not log or switch off a newer one.
1367
+ this.recognition.onresult = this.recognition.onerror = this.recognition.onend = null;
1368
+ try {
1369
+ this.recognition.stop();
1370
+ } catch (error) {
1371
+ console.error('Error stopping recognition:', error);
1372
+ }
1373
+ this.recognition = null;
1374
+ }
1375
+ this.micButton.classList.remove('fa-stop');
1376
+ this.micButton.classList.add('fa-microphone');
1377
+ this.micButton.style.color = '';
1378
+ ui.setUpdateIndicator(this.textAreaDiv, false);
1379
+ }
1380
+ }
1381
+
1382
+
1383
+ function receiveFeedback(userPrompt: string, aiResponse: string, contextId: string, helpful: boolean) {
1384
+ // not implemented yet
1385
+ }