@elyracode/web-ui 0.9.58 → 1.0.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 (95) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/components/SandboxedIframe.d.ts +15 -1
  3. package/dist/components/SandboxedIframe.d.ts.map +1 -1
  4. package/dist/components/SandboxedIframe.js +129 -67
  5. package/dist/components/SandboxedIframe.js.map +1 -1
  6. package/dist/components/sandbox/RuntimeMessageRouter.d.ts +12 -2
  7. package/dist/components/sandbox/RuntimeMessageRouter.d.ts.map +1 -1
  8. package/dist/components/sandbox/RuntimeMessageRouter.js +26 -2
  9. package/dist/components/sandbox/RuntimeMessageRouter.js.map +1 -1
  10. package/package.json +18 -8
  11. package/example/README.md +0 -61
  12. package/example/index.html +0 -13
  13. package/example/package.json +0 -25
  14. package/example/src/app.css +0 -1
  15. package/example/src/css-modules.d.ts +0 -3
  16. package/example/src/custom-messages.ts +0 -99
  17. package/example/src/main.ts +0 -421
  18. package/example/tsconfig.json +0 -23
  19. package/example/vite.config.ts +0 -6
  20. package/scripts/count-prompt-tokens.ts +0 -88
  21. package/src/ChatPanel.ts +0 -209
  22. package/src/app.css +0 -68
  23. package/src/components/AgentInterface.ts +0 -403
  24. package/src/components/AttachmentTile.ts +0 -107
  25. package/src/components/ConsoleBlock.ts +0 -72
  26. package/src/components/CustomProviderCard.ts +0 -100
  27. package/src/components/ExpandableSection.ts +0 -46
  28. package/src/components/Input.ts +0 -113
  29. package/src/components/MessageEditor.ts +0 -405
  30. package/src/components/MessageList.ts +0 -98
  31. package/src/components/Messages.ts +0 -383
  32. package/src/components/ProviderKeyInput.ts +0 -153
  33. package/src/components/SandboxedIframe.ts +0 -627
  34. package/src/components/StreamingMessageContainer.ts +0 -103
  35. package/src/components/ThinkingBlock.ts +0 -43
  36. package/src/components/message-renderer-registry.ts +0 -28
  37. package/src/components/sandbox/ArtifactsRuntimeProvider.ts +0 -226
  38. package/src/components/sandbox/AttachmentsRuntimeProvider.ts +0 -68
  39. package/src/components/sandbox/ConsoleRuntimeProvider.ts +0 -188
  40. package/src/components/sandbox/FileDownloadRuntimeProvider.ts +0 -114
  41. package/src/components/sandbox/RuntimeMessageBridge.ts +0 -82
  42. package/src/components/sandbox/RuntimeMessageRouter.ts +0 -215
  43. package/src/components/sandbox/SandboxRuntimeProvider.ts +0 -54
  44. package/src/components/sandbox/runtime-messages.ts +0 -146
  45. package/src/dialogs/ApiKeyPromptDialog.ts +0 -75
  46. package/src/dialogs/AttachmentOverlay.ts +0 -637
  47. package/src/dialogs/CustomProviderDialog.ts +0 -274
  48. package/src/dialogs/ModelSelector.ts +0 -370
  49. package/src/dialogs/PersistentStorageDialog.ts +0 -144
  50. package/src/dialogs/ProvidersModelsTab.ts +0 -212
  51. package/src/dialogs/SessionListDialog.ts +0 -150
  52. package/src/dialogs/SettingsDialog.ts +0 -218
  53. package/src/index.ts +0 -120
  54. package/src/prompts/prompts.ts +0 -282
  55. package/src/storage/app-storage.ts +0 -60
  56. package/src/storage/backends/indexeddb-storage-backend.ts +0 -193
  57. package/src/storage/store.ts +0 -33
  58. package/src/storage/stores/custom-providers-store.ts +0 -62
  59. package/src/storage/stores/provider-keys-store.ts +0 -33
  60. package/src/storage/stores/sessions-store.ts +0 -136
  61. package/src/storage/stores/settings-store.ts +0 -34
  62. package/src/storage/types.ts +0 -206
  63. package/src/tools/artifacts/ArtifactElement.ts +0 -14
  64. package/src/tools/artifacts/ArtifactPill.ts +0 -26
  65. package/src/tools/artifacts/Console.ts +0 -93
  66. package/src/tools/artifacts/DocxArtifact.ts +0 -213
  67. package/src/tools/artifacts/ExcelArtifact.ts +0 -231
  68. package/src/tools/artifacts/GenericArtifact.ts +0 -117
  69. package/src/tools/artifacts/HtmlArtifact.ts +0 -195
  70. package/src/tools/artifacts/ImageArtifact.ts +0 -116
  71. package/src/tools/artifacts/MarkdownArtifact.ts +0 -82
  72. package/src/tools/artifacts/PdfArtifact.ts +0 -202
  73. package/src/tools/artifacts/SvgArtifact.ts +0 -119
  74. package/src/tools/artifacts/TextArtifact.ts +0 -148
  75. package/src/tools/artifacts/artifacts-tool-renderer.ts +0 -310
  76. package/src/tools/artifacts/artifacts.ts +0 -713
  77. package/src/tools/artifacts/index.ts +0 -7
  78. package/src/tools/extract-document.ts +0 -275
  79. package/src/tools/index.ts +0 -46
  80. package/src/tools/javascript-repl.ts +0 -293
  81. package/src/tools/renderer-registry.ts +0 -130
  82. package/src/tools/renderers/BashRenderer.ts +0 -52
  83. package/src/tools/renderers/CalculateRenderer.ts +0 -58
  84. package/src/tools/renderers/DefaultRenderer.ts +0 -103
  85. package/src/tools/renderers/GetCurrentTimeRenderer.ts +0 -92
  86. package/src/tools/types.ts +0 -15
  87. package/src/utils/attachment-utils.ts +0 -479
  88. package/src/utils/auth-token.ts +0 -22
  89. package/src/utils/format.ts +0 -42
  90. package/src/utils/i18n.ts +0 -653
  91. package/src/utils/model-discovery.ts +0 -290
  92. package/src/utils/proxy-utils.ts +0 -139
  93. package/src/utils/test-sessions.ts +0 -2357
  94. package/tsconfig.build.json +0 -20
  95. package/tsconfig.json +0 -7
@@ -1,103 +0,0 @@
1
- import type { AgentMessage, AgentTool } from "@elyracode/agent-core";
2
- import type { ToolResultMessage } from "@elyracode/ai";
3
- import { html, LitElement } from "lit";
4
- import { property, state } from "lit/decorators.js";
5
-
6
- export class StreamingMessageContainer extends LitElement {
7
- @property({ type: Array }) tools: AgentTool[] = [];
8
- @property({ type: Boolean }) isStreaming = false;
9
- @property({ type: Object }) pendingToolCalls?: ReadonlySet<string>;
10
- @property({ type: Object }) toolResultsById?: Map<string, ToolResultMessage>;
11
- @property({ attribute: false }) onCostClick?: () => void;
12
-
13
- @state() private _message: AgentMessage | null = null;
14
- private _pendingMessage: AgentMessage | null = null;
15
- private _updateScheduled = false;
16
- private _immediateUpdate = false;
17
-
18
- protected override createRenderRoot(): HTMLElement | DocumentFragment {
19
- return this;
20
- }
21
-
22
- override connectedCallback(): void {
23
- super.connectedCallback();
24
- this.style.display = "block";
25
- }
26
-
27
- // Public method to update the message with batching for performance
28
- public setMessage(message: AgentMessage | null, immediate = false) {
29
- // Store the latest message
30
- this._pendingMessage = message;
31
-
32
- // If this is an immediate update (like clearing), apply it right away
33
- if (immediate || message === null) {
34
- this._immediateUpdate = true;
35
- this._message = message;
36
- this.requestUpdate();
37
- // Cancel any pending updates since we're clearing
38
- this._pendingMessage = null;
39
- this._updateScheduled = false;
40
- return;
41
- }
42
-
43
- // Otherwise batch updates for performance during streaming
44
- if (!this._updateScheduled) {
45
- this._updateScheduled = true;
46
-
47
- requestAnimationFrame(async () => {
48
- // Only apply the update if we haven't been cleared
49
- if (!this._immediateUpdate && this._pendingMessage !== null) {
50
- // Deep clone the message to ensure Lit detects changes in nested properties
51
- // (like toolCall.arguments being mutated during streaming)
52
- this._message = JSON.parse(JSON.stringify(this._pendingMessage));
53
- this.requestUpdate();
54
- }
55
- // Reset for next batch
56
- this._pendingMessage = null;
57
- this._updateScheduled = false;
58
- this._immediateUpdate = false;
59
- });
60
- }
61
- }
62
-
63
- override render() {
64
- // Show loading indicator if loading but no message yet
65
- if (!this._message) {
66
- if (this.isStreaming)
67
- return html`<div class="flex flex-col gap-3 mb-3">
68
- <span class="mx-4 inline-block w-2 h-4 bg-muted-foreground animate-pulse"></span>
69
- </div>`;
70
- return html``; // Empty until a message is set
71
- }
72
- const msg = this._message;
73
-
74
- if (msg.role === "toolResult") {
75
- // Skip standalone tool result in streaming; the stable list will render paired tool-message
76
- return html``;
77
- } else if (msg.role === "user" || msg.role === "user-with-attachments") {
78
- // Skip standalone tool result in streaming; the stable list will render it immediiately
79
- return html``;
80
- } else if (msg.role === "assistant") {
81
- // Assistant message - render inline tool messages during streaming
82
- return html`
83
- <div class="flex flex-col gap-3 mb-3">
84
- <assistant-message
85
- .message=${msg}
86
- .tools=${this.tools}
87
- .isStreaming=${this.isStreaming}
88
- .pendingToolCalls=${this.pendingToolCalls}
89
- .toolResultsById=${this.toolResultsById}
90
- .hideToolCalls=${false}
91
- .onCostClick=${this.onCostClick}
92
- ></assistant-message>
93
- ${this.isStreaming ? html`<span class="mx-4 inline-block w-2 h-4 bg-muted-foreground animate-pulse"></span>` : ""}
94
- </div>
95
- `;
96
- }
97
- }
98
- }
99
-
100
- // Register custom element
101
- if (!customElements.get("streaming-message-container")) {
102
- customElements.define("streaming-message-container", StreamingMessageContainer);
103
- }
@@ -1,43 +0,0 @@
1
- import { icon } from "@elyracode/mini-lit";
2
- import { html, LitElement } from "lit";
3
- import { customElement, property, state } from "lit/decorators.js";
4
- import { ChevronRight } from "lucide";
5
-
6
- @customElement("thinking-block")
7
- export class ThinkingBlock extends LitElement {
8
- @property() content!: string;
9
- @property({ type: Boolean }) isStreaming = false;
10
- @state() private isExpanded = false;
11
-
12
- protected override createRenderRoot(): HTMLElement | DocumentFragment {
13
- return this;
14
- }
15
-
16
- override connectedCallback(): void {
17
- super.connectedCallback();
18
- this.style.display = "block";
19
- }
20
-
21
- private toggleExpanded() {
22
- this.isExpanded = !this.isExpanded;
23
- }
24
-
25
- override render() {
26
- const shimmerClasses = this.isStreaming
27
- ? "animate-shimmer bg-gradient-to-r from-muted-foreground via-foreground to-muted-foreground bg-[length:200%_100%] bg-clip-text text-transparent"
28
- : "";
29
-
30
- return html`
31
- <div class="thinking-block">
32
- <div
33
- class="thinking-header cursor-pointer select-none flex items-center gap-2 py-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
34
- @click=${this.toggleExpanded}
35
- >
36
- <span class="transition-transform inline-block ${this.isExpanded ? "rotate-90" : ""}">${icon(ChevronRight, "sm")}</span>
37
- <span class="${shimmerClasses}">Thinking...</span>
38
- </div>
39
- ${this.isExpanded ? html`<markdown-block .content=${this.content} .isThinking=${true}></markdown-block>` : ""}
40
- </div>
41
- `;
42
- }
43
- }
@@ -1,28 +0,0 @@
1
- import type { AgentMessage } from "@elyracode/agent-core";
2
- import type { TemplateResult } from "lit";
3
-
4
- // Extract role type from AppMessage union
5
- export type MessageRole = AgentMessage["role"];
6
-
7
- // Generic message renderer typed to specific message type
8
- export interface MessageRenderer<TMessage extends AgentMessage = AgentMessage> {
9
- render(message: TMessage): TemplateResult;
10
- }
11
-
12
- // Registry of custom message renderers by role
13
- const messageRenderers = new Map<MessageRole, MessageRenderer>();
14
-
15
- export function registerMessageRenderer<TRole extends MessageRole>(
16
- role: TRole,
17
- renderer: MessageRenderer<Extract<AgentMessage, { role: TRole }>>,
18
- ): void {
19
- messageRenderers.set(role, renderer);
20
- }
21
-
22
- export function getMessageRenderer(role: MessageRole): MessageRenderer | undefined {
23
- return messageRenderers.get(role);
24
- }
25
-
26
- export function renderMessage(message: AgentMessage): TemplateResult | undefined {
27
- return messageRenderers.get(message.role)?.render(message);
28
- }
@@ -1,226 +0,0 @@
1
- import type { AgentMessage } from "@elyracode/agent-core";
2
- import {
3
- ARTIFACTS_RUNTIME_PROVIDER_DESCRIPTION_RO,
4
- ARTIFACTS_RUNTIME_PROVIDER_DESCRIPTION_RW,
5
- } from "../../prompts/prompts.js";
6
- import type { RuntimeMessage, RuntimeResponse, SandboxRuntimeWindow } from "./runtime-messages.js";
7
- import type { SandboxRuntimeProvider } from "./SandboxRuntimeProvider.js";
8
-
9
- // Define minimal interface for ArtifactsPanel to avoid circular dependencies
10
- interface ArtifactsPanelLike {
11
- artifacts: Map<string, { content: string }>;
12
- tool: {
13
- execute(toolCallId: string, args: { command: string; filename: string; content?: string }): Promise<unknown>;
14
- };
15
- }
16
-
17
- interface AgentLike {
18
- state: { readonly messages: readonly AgentMessage[] };
19
- appendMessage?(message: AgentMessage): void;
20
- }
21
-
22
- /**
23
- * Artifacts Runtime Provider
24
- *
25
- * Provides programmatic access to session artifacts from sandboxed code.
26
- * Allows code to create, read, update, and delete artifacts dynamically.
27
- * Supports both online (extension) and offline (downloaded HTML) modes.
28
- */
29
- export class ArtifactsRuntimeProvider implements SandboxRuntimeProvider {
30
- constructor(
31
- private artifactsPanel: ArtifactsPanelLike,
32
- private agent?: AgentLike,
33
- private readWrite: boolean = true,
34
- ) {}
35
-
36
- private pushAgentMessage(message: AgentMessage): void {
37
- if (!this.agent) return;
38
- if (this.agent.appendMessage) {
39
- this.agent.appendMessage(message);
40
- } else {
41
- (this.agent.state.messages as AgentMessage[]).push(message);
42
- }
43
- }
44
-
45
- getData(): Record<string, unknown> {
46
- // Inject artifact snapshot for offline mode
47
- const snapshot: Record<string, string> = {};
48
- this.artifactsPanel.artifacts.forEach((artifact, filename) => {
49
- snapshot[filename] = artifact.content;
50
- });
51
- return { artifacts: snapshot };
52
- }
53
-
54
- getRuntime(): (sandboxId: string) => void {
55
- // This function will be stringified, so no external references!
56
- return (_sandboxId: string) => {
57
- const win = window as unknown as SandboxRuntimeWindow;
58
- // Auto-parse/stringify for .json files
59
- const isJsonFile = (filename: string) => filename.endsWith(".json");
60
-
61
- win.listArtifacts = async (): Promise<string[]> => {
62
- // Online: ask extension
63
- if (win.sendRuntimeMessage) {
64
- const response = await win.sendRuntimeMessage({
65
- type: "artifact-operation",
66
- action: "list",
67
- });
68
- if (!response.success) throw new Error(response.error);
69
- return response.result as string[];
70
- }
71
- // Offline: return snapshot keys
72
- else {
73
- return Object.keys(win.artifacts || {});
74
- }
75
- };
76
-
77
- win.getArtifact = async (filename: string): Promise<unknown> => {
78
- let content: string;
79
-
80
- // Online: ask extension
81
- if (win.sendRuntimeMessage) {
82
- const response = await win.sendRuntimeMessage({
83
- type: "artifact-operation",
84
- action: "get",
85
- filename,
86
- });
87
- if (!response.success) throw new Error(response.error);
88
- content = response.result as string;
89
- }
90
- // Offline: read snapshot
91
- else {
92
- if (!win.artifacts?.[filename]) {
93
- throw new Error(`Artifact not found (offline mode): ${filename}`);
94
- }
95
- content = win.artifacts[filename];
96
- }
97
-
98
- // Auto-parse .json files
99
- if (isJsonFile(filename)) {
100
- try {
101
- return JSON.parse(content);
102
- } catch (e) {
103
- throw new Error(`Failed to parse JSON from ${filename}: ${e}`);
104
- }
105
- }
106
- return content;
107
- };
108
-
109
- win.createOrUpdateArtifact = async (filename: string, content: unknown, mimeType?: string): Promise<void> => {
110
- if (!win.sendRuntimeMessage) {
111
- throw new Error("Cannot create/update artifacts in offline mode (read-only)");
112
- }
113
-
114
- let finalContent = content;
115
- // Auto-stringify .json files
116
- if (isJsonFile(filename) && typeof content !== "string") {
117
- finalContent = JSON.stringify(content, null, 2);
118
- } else if (typeof content !== "string") {
119
- finalContent = JSON.stringify(content, null, 2);
120
- }
121
-
122
- const response = await win.sendRuntimeMessage({
123
- type: "artifact-operation",
124
- action: "createOrUpdate",
125
- filename,
126
- content: finalContent,
127
- mimeType,
128
- });
129
- if (!response.success) throw new Error(response.error);
130
- };
131
-
132
- win.deleteArtifact = async (filename: string): Promise<void> => {
133
- if (!win.sendRuntimeMessage) {
134
- throw new Error("Cannot delete artifacts in offline mode (read-only)");
135
- }
136
-
137
- const response = await win.sendRuntimeMessage({
138
- type: "artifact-operation",
139
- action: "delete",
140
- filename,
141
- });
142
- if (!response.success) throw new Error(response.error);
143
- };
144
- };
145
- }
146
-
147
- async handleMessage(message: RuntimeMessage, respond: (response: RuntimeResponse) => void): Promise<void> {
148
- if (message.type !== "artifact-operation") {
149
- return;
150
- }
151
-
152
- try {
153
- switch (message.action) {
154
- case "list": {
155
- const filenames = Array.from(this.artifactsPanel.artifacts.keys());
156
- respond({ success: true, result: filenames });
157
- break;
158
- }
159
-
160
- case "get": {
161
- const artifact = this.artifactsPanel.artifacts.get(message.filename);
162
- if (!artifact) {
163
- respond({ success: false, error: `Artifact not found: ${message.filename}` });
164
- } else {
165
- respond({ success: true, result: artifact.content });
166
- }
167
- break;
168
- }
169
-
170
- case "createOrUpdate": {
171
- try {
172
- const exists = this.artifactsPanel.artifacts.has(message.filename);
173
- const command = exists ? "rewrite" : "create";
174
- const action = exists ? "update" : "create";
175
-
176
- await this.artifactsPanel.tool.execute("", {
177
- command,
178
- filename: message.filename,
179
- content: message.content,
180
- });
181
- this.pushAgentMessage({
182
- role: "artifact",
183
- action,
184
- filename: message.filename,
185
- content: message.content,
186
- ...(action === "create" && { title: message.filename }),
187
- timestamp: new Date().toISOString(),
188
- });
189
- respond({ success: true });
190
- } catch (err) {
191
- respond({ success: false, error: err instanceof Error ? err.message : String(err) });
192
- }
193
- break;
194
- }
195
-
196
- case "delete": {
197
- try {
198
- await this.artifactsPanel.tool.execute("", {
199
- command: "delete",
200
- filename: message.filename,
201
- });
202
- this.pushAgentMessage({
203
- role: "artifact",
204
- action: "delete",
205
- filename: message.filename,
206
- timestamp: new Date().toISOString(),
207
- });
208
- respond({ success: true });
209
- } catch (err) {
210
- respond({ success: false, error: err instanceof Error ? err.message : String(err) });
211
- }
212
- break;
213
- }
214
-
215
- default:
216
- respond({ success: false, error: "Unknown artifact action" });
217
- }
218
- } catch (error) {
219
- respond({ success: false, error: error instanceof Error ? error.message : String(error) });
220
- }
221
- }
222
-
223
- getDescription(): string {
224
- return this.readWrite ? ARTIFACTS_RUNTIME_PROVIDER_DESCRIPTION_RW : ARTIFACTS_RUNTIME_PROVIDER_DESCRIPTION_RO;
225
- }
226
- }
@@ -1,68 +0,0 @@
1
- import { ATTACHMENTS_RUNTIME_DESCRIPTION } from "../../prompts/prompts.js";
2
- import type { Attachment } from "../../utils/attachment-utils.js";
3
- import type { SandboxAttachment, SandboxRuntimeWindow } from "./runtime-messages.js";
4
- import type { SandboxRuntimeProvider } from "./SandboxRuntimeProvider.js";
5
-
6
- /**
7
- * Attachments Runtime Provider
8
- *
9
- * OPTIONAL provider that provides file access APIs to sandboxed code.
10
- * Only needed when attachments are present.
11
- * Attachments are read-only snapshot data - no messaging needed.
12
- */
13
- export class AttachmentsRuntimeProvider implements SandboxRuntimeProvider {
14
- constructor(private attachments: Attachment[]) {}
15
-
16
- getData(): Record<string, unknown> {
17
- const attachmentsData = this.attachments.map((a) => ({
18
- id: a.id,
19
- fileName: a.fileName,
20
- mimeType: a.mimeType,
21
- size: a.size,
22
- content: a.content,
23
- extractedText: a.extractedText,
24
- }));
25
-
26
- return { attachments: attachmentsData };
27
- }
28
-
29
- getRuntime(): (sandboxId: string) => void {
30
- // This function will be stringified, so no external references!
31
- // These functions read directly from window.attachments
32
- // Works both online AND offline (no messaging needed!)
33
- return (_sandboxId: string) => {
34
- const win = window as unknown as SandboxRuntimeWindow;
35
- win.listAttachments = () =>
36
- (win.attachments || []).map((a: SandboxAttachment) => ({
37
- id: a.id,
38
- fileName: a.fileName,
39
- mimeType: a.mimeType,
40
- size: a.size,
41
- }));
42
-
43
- win.readTextAttachment = (attachmentId: string) => {
44
- const a = (win.attachments || []).find((x: SandboxAttachment) => x.id === attachmentId);
45
- if (!a) throw new Error(`Attachment not found: ${attachmentId}`);
46
- if (a.extractedText) return a.extractedText;
47
- try {
48
- return atob(a.content);
49
- } catch {
50
- throw new Error(`Failed to decode text content for: ${attachmentId}`);
51
- }
52
- };
53
-
54
- win.readBinaryAttachment = (attachmentId: string) => {
55
- const a = (win.attachments || []).find((x: SandboxAttachment) => x.id === attachmentId);
56
- if (!a) throw new Error(`Attachment not found: ${attachmentId}`);
57
- const bin = atob(a.content);
58
- const bytes = new Uint8Array(bin.length);
59
- for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
60
- return bytes;
61
- };
62
- };
63
- }
64
-
65
- getDescription(): string {
66
- return ATTACHMENTS_RUNTIME_DESCRIPTION;
67
- }
68
- }
@@ -1,188 +0,0 @@
1
- import type { RuntimeMessage, RuntimeResponse, SandboxRuntimeWindow } from "./runtime-messages.js";
2
- import type { SandboxRuntimeProvider } from "./SandboxRuntimeProvider.js";
3
-
4
- export interface ConsoleLog {
5
- type: "log" | "warn" | "error" | "info";
6
- text: string;
7
- args?: unknown[];
8
- }
9
-
10
- /**
11
- * Console Runtime Provider
12
- *
13
- * REQUIRED provider that should always be included first.
14
- * Provides console capture, error handling, and execution lifecycle management.
15
- * Collects console output for retrieval by caller.
16
- */
17
- export class ConsoleRuntimeProvider implements SandboxRuntimeProvider {
18
- private logs: ConsoleLog[] = [];
19
- private completionError: { message: string; stack: string } | null = null;
20
- private completed = false;
21
-
22
- getData(): Record<string, unknown> {
23
- // No data needed
24
- return {};
25
- }
26
-
27
- getDescription(): string {
28
- return "";
29
- }
30
-
31
- getRuntime(): (sandboxId: string) => void {
32
- return (_sandboxId: string) => {
33
- const win = window as unknown as SandboxRuntimeWindow;
34
- // Store truly original console methods on first wrap only
35
- // This prevents accumulation of wrapper functions across multiple executions
36
- if (!win.__originalConsole) {
37
- win.__originalConsole = {
38
- log: console.log.bind(console),
39
- error: console.error.bind(console),
40
- warn: console.warn.bind(console),
41
- info: console.info.bind(console),
42
- };
43
- }
44
-
45
- // Always use the truly original console, not the current (possibly wrapped) one
46
- const originalConsole = win.__originalConsole;
47
-
48
- // Track pending send promises to wait for them in onCompleted
49
- const pendingSends: Promise<unknown>[] = [];
50
-
51
- (["log", "error", "warn", "info"] as const).forEach((method) => {
52
- console[method] = (...args: unknown[]) => {
53
- const text = args
54
- .map((arg) => {
55
- try {
56
- return typeof arg === "object" ? JSON.stringify(arg) : String(arg);
57
- } catch {
58
- return String(arg);
59
- }
60
- })
61
- .join(" ");
62
-
63
- // Always log locally too (using truly original console)
64
- originalConsole[method].apply(console, args);
65
-
66
- // Send immediately and track the promise (only in extension context)
67
- if (win.sendRuntimeMessage) {
68
- const sendPromise = win
69
- .sendRuntimeMessage({
70
- type: "console",
71
- method,
72
- text,
73
- args,
74
- })
75
- .catch(() => {});
76
- pendingSends.push(sendPromise);
77
- }
78
- };
79
- });
80
-
81
- // Register completion callback to wait for all pending sends
82
- if (win.onCompleted) {
83
- win.onCompleted(async (_success: boolean) => {
84
- // Wait for all pending console sends to complete
85
- if (pendingSends.length > 0) {
86
- await Promise.all(pendingSends);
87
- }
88
- });
89
- }
90
-
91
- // Track errors for HTML artifacts
92
- let lastError: { message: string; stack: string } | null = null;
93
-
94
- // Error handlers - track errors but don't log them
95
- // (they'll be shown via execution-error message)
96
- window.addEventListener("error", (e) => {
97
- const text = `${e.error?.stack || e.message || String(e)} at line ${e.lineno || "?"}:${e.colno || "?"}`;
98
-
99
- lastError = {
100
- message: e.error?.message || e.message || String(e),
101
- stack: e.error?.stack || text,
102
- };
103
- });
104
-
105
- window.addEventListener("unhandledrejection", (e) => {
106
- const text = `Unhandled promise rejection: ${e.reason?.message || e.reason || "Unknown error"}`;
107
-
108
- lastError = {
109
- message: e.reason?.message || String(e.reason) || "Unhandled promise rejection",
110
- stack: e.reason?.stack || text,
111
- };
112
- });
113
-
114
- // Expose complete() method for user code to call
115
- let completionSent = false;
116
- win.complete = async (error?: { message: string; stack: string } | null, returnValue?: unknown) => {
117
- if (completionSent) return;
118
- completionSent = true;
119
-
120
- const finalError = error || lastError;
121
-
122
- if (win.sendRuntimeMessage) {
123
- if (finalError) {
124
- await win.sendRuntimeMessage({
125
- type: "execution-error",
126
- error: finalError,
127
- });
128
- } else {
129
- await win.sendRuntimeMessage({
130
- type: "execution-complete",
131
- returnValue,
132
- });
133
- }
134
- }
135
- };
136
- };
137
- }
138
-
139
- async handleMessage(message: RuntimeMessage, respond: (response: RuntimeResponse) => void): Promise<void> {
140
- if (message.type === "console") {
141
- // Collect console output
142
- this.logs.push({
143
- type:
144
- message.method === "error"
145
- ? "error"
146
- : message.method === "warn"
147
- ? "warn"
148
- : message.method === "info"
149
- ? "info"
150
- : "log",
151
- text: message.text,
152
- args: message.args,
153
- });
154
- // Acknowledge receipt
155
- respond({ success: true });
156
- }
157
- }
158
-
159
- /**
160
- * Get collected console logs
161
- */
162
- getLogs(): ConsoleLog[] {
163
- return this.logs;
164
- }
165
-
166
- /**
167
- * Get completion status
168
- */
169
- isCompleted(): boolean {
170
- return this.completed;
171
- }
172
-
173
- /**
174
- * Get completion error if any
175
- */
176
- getCompletionError(): { message: string; stack: string } | null {
177
- return this.completionError;
178
- }
179
-
180
- /**
181
- * Reset state for reuse
182
- */
183
- reset(): void {
184
- this.logs = [];
185
- this.completionError = null;
186
- this.completed = false;
187
- }
188
- }