Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

feat: refactor chat input components and enhance functionality

Salman-Ahamedf3b64069854d
diff --git a/packages/app/src/react/features/ai-chat/components/footer/claude-input.tsx b/packages/app/src/react/features/ai-chat/components/footer/claude-input.tsx
deleted file mode 100644
index 32a3a314..00000000
--- a/packages/app/src/react/features/ai-chat/components/footer/claude-input.tsx
+++ /dev/null
@@ -1,248 +0,0 @@
-import { ChangeEvent, KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
-
-import {
- FileItemPreview,
- PlusIcon,
- SendButton2,
- UploadMenu,
-} from '@react/features/ai-chat/components';
-import { useChatStores, useClipboardPaste } from '@react/features/ai-chat/hooks';
-import {
- adjustTextareaHeight,
- forceScrollToBottomImmediate,
- scrollManager,
- textToFile,
-} from '@react/features/ai-chat/utils';
-import { MAX_CHAT_MESSAGE_LENGTH } from '@react/shared/constants';
-import { cn } from '@src/react/shared/utils/general';
-
-const LARGE_TEXT_THRESHOLD = 4000;
-const TEXTAREA_MAX_HEIGHT = 300;
-
-const ClaudeInput = () => {
- const { refs, files: filesData, chat, agent } = useChatStores();
- const [message, setMessage] = useState('');
- const [isMenuOpen, setIsMenuOpen] = useState(false);
- const fileInputRef = useRef<HTMLInputElement>(null);
- const menuTriggerRef = useRef<HTMLButtonElement>(null);
-
- const inputRef = refs?.input;
-
- const { isChatCreating } = chat || {};
- const { isStreaming, sendMessage, stopStreaming } = chat || {};
- const { isLoading, data: agentData, settings: agentSettings } = agent || {};
- const { attachments, status, addFiles, remove, clear, uploading } = filesData || {};
-
- const maxLength = MAX_CHAT_MESSAGE_LENGTH;
- const isChatbotDisabled = agentSettings?.chatbot === 'false';
- const isDisabled = isChatCreating || isLoading.agent || isChatbotDisabled;
-
- // Adjust textarea height when message changes
- useEffect(() => {
- adjustTextareaHeight(inputRef?.current ?? null, TEXTAREA_MAX_HEIGHT);
- }, [inputRef, message]);
-
- const handleChange = useCallback(
- (e: ChangeEvent<HTMLTextAreaElement>) => {
- const newValue = e.target.value.slice(0, maxLength);
- setMessage(newValue);
- },
- [maxLength],
- );
-
- const handleSubmit = useCallback((): void => {
- if (isChatbotDisabled) return;
- if (isStreaming) return stopStreaming();
-
- const trimmedMessage = message.trim();
- if (trimmedMessage.length > 0 || attachments.length > 0) {
- sendMessage(trimmedMessage);
- setMessage('');
- clear();
- requestAnimationFrame(() => adjustTextareaHeight(inputRef?.current ?? null));
-
- if (fileInputRef.current) fileInputRef.current.value = '';
- let container: HTMLElement = document.querySelector('[data-chat-container]');
- if (!container) container = document.querySelector('.overflow-auto');
- if (!container) container = document.querySelector('.scroll-smooth');
-
- if (container) {
- scrollManager.init(container);
- } else {
- const existingContainer = scrollManager.getContainer();
- if (!existingContainer) return;
- }
-
- scrollManager.resetForceScrollCooldown();
-
- setTimeout(() => {
- forceScrollToBottomImmediate({ behavior: 'smooth', delay: 0 });
- }, 150);
- }
- }, [
- isChatbotDisabled,
- isStreaming,
- stopStreaming,
- message,
- attachments.length,
- sendMessage,
- clear,
- inputRef,
- ]);
-
- const handleKeyDown = useCallback(
- (e: KeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- if (!isStreaming) handleSubmit();
- }
- },
- [handleSubmit, isStreaming],
- );
-
- const handleRemoveFile = useCallback(
- (index: number): void => {
- remove(index);
- if (fileInputRef.current) fileInputRef.current.value = '';
- },
- [remove],
- );
-
- useClipboardPaste({
- onFilePaste: addFiles,
- targetRef: inputRef,
- largeTextThreshold: LARGE_TEXT_THRESHOLD,
- onLargeTextPaste: (text) => addFiles([textToFile(text).file]),
- });
-
- // Keyboard shortcut: Ctrl+U to add files
- useEffect(() => {
- const handleKeyboardShortcut = (e: globalThis.KeyboardEvent) => {
- if (e.ctrlKey && e.key === 'u') {
- e.preventDefault();
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- fileInputRef.current.click();
- }
- }
- };
-
- window.addEventListener('keydown', handleKeyboardShortcut);
- return () => window.removeEventListener('keydown', handleKeyboardShortcut);
- }, []);
-
- const toggleMenu = useCallback(() => {
- setIsMenuOpen((prev) => !prev);
- }, []);
-
- const closeMenu = useCallback(() => {
- setIsMenuOpen(false);
- }, []);
-
- const handleAddFiles = useCallback(() => {
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- fileInputRef.current.click();
- }
- }, []);
-
- const handleTakeScreenshot = useCallback(() => {
- // console.log('Take screenshot clicked');
- }, []);
-
- const canSubmit =
- !isDisabled && (message.trim().length > 0 || isStreaming || attachments.length > 0);
-
- return (
- <div className="grid-area-[1/1] min-w-0 w-full mx-auto">
- <fieldset className="flex w-full min-w-0 flex-col">
- <div
- className="flex flex-col bg-white mx-2 md:mx-0 items-stretch transition-all duration-200 relative z-10 rounded-2xl border
- border-transparent shadow-[0_0.25rem_1.25rem_#00000009,0_0_0_0.5px_#C8C8C84D]
- hover:shadow-[0_0.25rem_1.25rem_#00000013,0_0_0_0.5px_#C8C8C866]
- focus-within:shadow-[0_0.25rem_1.25rem_#00000013,0_0_0_0.5px_#C8C8C866]"
- >
- <div className={cn('flex flex-col gap-2.5 p-3.5', attachments.length > 0 && 'pt-1.5')}>
- {attachments.length > 0 && (
- <div
- role="list"
- aria-label="Attached files"
- className="flex flex-nowrap gap-2 w-full h-full overflow-x-auto attachments-container-enter"
- >
- {attachments.map((file, index) => (
- <FileItemPreview
- key={`${file.id}`}
- attachment={file}
- onRemove={() => handleRemoveFile(index)}
- isUploading={status[file.name]?.status === 'uploading'}
- />
- ))}
- </div>
- )}
-
- <div className="w-full h-fit overflow-y-auto">
- <textarea
- rows={1}
- ref={inputRef}
- value={message}
- maxLength={maxLength}
- onChange={handleChange}
- onKeyDown={handleKeyDown}
- aria-label="Message input"
- onClick={(e) => e.stopPropagation()}
- placeholder={`Message ${agentData?.name || ''}...`}
- className="w-full min-h-12 max-h-96 bg-white border-none outline-none ring-0 focus:outline-none focus:border-none flex-1 resize-none ph-no-capture text-gray-900 placeholder:text-gray-500 px-1"
- />
- </div>
-
- <div className="w-full flex gap-2 items-center justify-between">
- <div className="relative flex items-center shrink min-w-0 gap-2">
- <input
- multiple
- type="file"
- ref={fileInputRef}
- className="hidden"
- aria-label="File attachment input"
- onClick={(e) => e.stopPropagation()}
- onChange={(e) => {
- if (e.target.files?.length) {
- addFiles(Array.from(e.target.files));
- }
- }}
- />
-
- <button
- type="button"
- aria-haspopup="menu"
- onClick={toggleMenu}
- ref={menuTriggerRef}
- aria-label="Upload files"
- aria-expanded={isMenuOpen}
- className="border-[0.5px] transition-all h-8 flex items-center group cursor-pointer overflow-hidden px-1.5 min-w-8 rounded-lg justify-center text-gray-400 border-gray-200 hover:text-gray-600 hover:bg-gray-50 active:scale-[0.98] "
- >
- <PlusIcon />
- </button>
-
- <UploadMenu
- isOpen={isMenuOpen}
- onClose={closeMenu}
- onAddFiles={handleAddFiles}
- onTakeScreenshot={handleTakeScreenshot}
- triggerRef={menuTriggerRef}
- />
- </div>
-
- <SendButton2
- onClick={handleSubmit}
- isStreaming={isStreaming}
- disabled={!canSubmit || uploading}
- />
- </div>
- </div>
- </div>
- </fieldset>
- </div>
- );
-};
-
-export default ClaudeInput;
diff --git a/packages/app/src/react/features/ai-chat/components/footer/footer.tsx b/packages/app/src/react/features/ai-chat/components/footer/footer.tsx
index ed80d08f..de041922 100644
--- a/packages/app/src/react/features/ai-chat/components/footer/footer.tsx
+++ b/packages/app/src/react/features/ai-chat/components/footer/footer.tsx
@@ -1,7 +1,6 @@
-import { ErrorToast, ScrollToBottomButton } from '@react/features/ai-chat/components';
+import { ErrorToast, Input, ScrollToBottomButton } from '@react/features/ai-chat/components';
import { useChatStores } from '@react/features/ai-chat/hooks';
import { FC } from 'react';
-import ClaudeInput from './claude-input';
export const Footer: FC = () => {
const { files, scroll } = useChatStores();
@@ -13,7 +12,7 @@ export const Footer: FC = () => {
{errorMessage && <ErrorToast message={errorMessage} onClose={clearError} />}
<div className="relative">
{showScrollButton && <ScrollToBottomButton onClick={() => scrollToBottom()} />}
- <ClaudeInput />
+ <Input />
</div>
<h6 className="py-4 text-center text-xs text-gray-500">
diff --git a/packages/app/src/react/features/ai-chat/components/footer/input.tsx b/packages/app/src/react/features/ai-chat/components/footer/input.tsx
index 14a3984e..ea32e6bd 100644
--- a/packages/app/src/react/features/ai-chat/components/footer/input.tsx
+++ b/packages/app/src/react/features/ai-chat/components/footer/input.tsx
@@ -1,22 +1,31 @@
import { ChangeEvent, KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
-import { AttachmentButton, FileItemPreview, SendButton } from '@react/features/ai-chat/components';
+import {
+ FileItemPreview,
+ PlusIcon,
+ SendButton,
+ UploadMenu,
+} from '@react/features/ai-chat/components';
import { useChatStores, useClipboardPaste } from '@react/features/ai-chat/hooks';
import {
adjustTextareaHeight,
+ captureScreenshot,
forceScrollToBottomImmediate,
scrollManager,
textToFile,
} from '@react/features/ai-chat/utils';
import { MAX_CHAT_MESSAGE_LENGTH } from '@react/shared/constants';
-import { cn } from '@react/shared/utils/general';
+import { cn } from '@src/react/shared/utils/general';
const LARGE_TEXT_THRESHOLD = 4000;
+const TEXTAREA_MAX_HEIGHT = 300;
-export const ChatInput = () => {
+export const Input = () => {
const { refs, files: filesData, chat, agent } = useChatStores();
const [message, setMessage] = useState('');
+ const [isMenuOpen, setIsMenuOpen] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
+ const menuTriggerRef = useRef<HTMLButtonElement>(null);
const inputRef = refs?.input;
@@ -26,14 +35,13 @@ export const ChatInput = () => {
const { attachments, status, addFiles, remove, clear, uploading } = filesData || {};
const maxLength = MAX_CHAT_MESSAGE_LENGTH;
- const isMaxFilesUploaded = attachments.length >= 10;
const isChatbotDisabled = agentSettings?.chatbot === 'false';
const isDisabled = isChatCreating || isLoading.agent || isChatbotDisabled;
- // Adjust textarea height when message changes (chatbot pattern)
+ // Adjust textarea height when message changes
useEffect(() => {
- adjustTextareaHeight(inputRef?.current ?? null);
- }, [message, inputRef]);
+ adjustTextareaHeight(inputRef?.current ?? null, TEXTAREA_MAX_HEIGHT);
+ }, [inputRef, message]);
const handleChange = useCallback(
(e: ChangeEvent<HTMLTextAreaElement>) => {
@@ -52,8 +60,6 @@ export const ChatInput = () => {
sendMessage(trimmedMessage);
setMessage('');
clear();
-
- // Reset textarea height after clearing message
requestAnimationFrame(() => adjustTextareaHeight(inputRef?.current ?? null));
if (fileInputRef.current) fileInputRef.current.value = '';
@@ -110,89 +116,133 @@ export const ChatInput = () => {
onLargeTextPaste: (text) => addFiles([textToFile(text).file]),
});
- const isMaxLengthReached = message.length === maxLength;
- const canSubmit =
- !isDisabled && (message.trim().length > 0 || isStreaming || attachments.length > 0);
+ // Keyboard shortcut: Ctrl+U to add files
+ useEffect(() => {
+ const handleKeyboardShortcut = (e: globalThis.KeyboardEvent) => {
+ if (e.ctrlKey && e.key === 'u') {
+ e.preventDefault();
+ if (fileInputRef.current) {
+ fileInputRef.current.value = '';
+ fileInputRef.current.click();
+ }
+ }
+ };
- const handleContainerClick = () => inputRef?.current?.focus();
+ window.addEventListener('keydown', handleKeyboardShortcut);
+ return () => window.removeEventListener('keydown', handleKeyboardShortcut);
+ }, []);
- return (
- <div
- onClick={handleContainerClick}
- className="w-full bg-white border border-solid border-[#e5e5e5] rounded-lg py-1 mt-2.5 text-sm flex flex-col items-start justify-center cursor-text"
- >
- {attachments.length > 0 && (
- <div
- role="list"
- aria-label="Attached files"
- className="flex flex-nowrap gap-2 w-full h-full px-2.5 py-5 overflow-x-auto"
- >
- {attachments.map((file, index) => (
- <FileItemPreview
- key={`${file.id}`}
- attachment={file}
- onRemove={() => handleRemoveFile(index)}
- isUploading={status[file.name]?.status === 'uploading'}
- />
- ))}
- </div>
- )}
-
- <div
- onClick={handleContainerClick}
- className="rounded-lg py-1 px-2.5 flex items-center text-sm w-full min-h-[60px] cursor-text"
- >
- <textarea
- rows={1}
- ref={inputRef}
- value={message}
- maxLength={maxLength}
- onChange={handleChange}
- onKeyDown={handleKeyDown}
- aria-label="Message input"
- onClick={(e) => e.stopPropagation()}
- placeholder={`Message ${agentData?.name || ''}...`}
- className="bg-white border-none outline-none ring-0 focus:outline-none focus:border-none flex-1 max-h-36 resize-none ph-no-capture text-[16px] font-[400] text-gray-900 placeholder:text-gray-500 placeholder:text-[16px] placeholder:font-[400]"
- />
+ const toggleMenu = useCallback(() => {
+ setIsMenuOpen((prev) => !prev);
+ }, []);
- <div
- aria-live="polite"
- onClick={(e) => e.stopPropagation()}
- className={cn(
- 'text-xs mr-2 w-[75px] text-right flex-shrink-0',
- isMaxLengthReached ? 'text-red-500' : 'text-gray-500',
- )}
- >
- {message.length}/{maxLength}
- </div>
+ const closeMenu = useCallback(() => {
+ setIsMenuOpen(false);
+ }, []);
- <div
- onClick={(e) => e.stopPropagation()}
- data-disabled={isDisabled || isStreaming}
- aria-disabled={isDisabled || isStreaming}
- className="data-[disabled=true]:cursor-not-allowed"
- >
- <AttachmentButton
- onFilesAdd={addFiles}
- fileInputRef={fileInputRef}
- isDisabled={isDisabled || isStreaming}
- isMaxFilesUploaded={isMaxFilesUploaded}
- />
- </div>
+ const handleAddFiles = useCallback(() => {
+ if (fileInputRef.current) {
+ fileInputRef.current.value = '';
+ fileInputRef.current.click();
+ }
+ }, []);
+ const handleTakeScreenshot = useCallback(async () => {
+ const screenshotFile = await captureScreenshot();
+ if (screenshotFile) addFiles([screenshotFile]);
+ }, [addFiles]);
+
+ const canSubmit =
+ !isDisabled && (message.trim().length > 0 || isStreaming || attachments.length > 0);
+
+ return (
+ <div className="grid-area-[1/1] min-w-0 w-full mx-auto">
+ <fieldset className="flex w-full min-w-0 flex-col">
<div
- onClick={(e) => e.stopPropagation()}
- data-disabled={isDisabled || isStreaming}
- aria-disabled={isDisabled || isStreaming}
- className="data-[disabled=true]:cursor-not-allowed"
+ className="flex flex-col bg-white mx-2 md:mx-0 items-stretch transition-all duration-200 relative z-10 rounded-2xl border
+ border-transparent shadow-[0_0.25rem_1.25rem_#00000009,0_0_0_0.5px_#C8C8C84D]
+ hover:shadow-[0_0.25rem_1.25rem_#00000013,0_0_0_0.5px_#C8C8C866]
+ focus-within:shadow-[0_0.25rem_1.25rem_#00000013,0_0_0_0.5px_#C8C8C866]"
>
- <SendButton
- onClick={handleSubmit}
- isStreaming={isStreaming}
- disabled={!canSubmit || uploading}
- />
+ <div className={cn('flex flex-col gap-2.5 p-3.5', attachments.length > 0 && 'pt-1.5')}>
+ {attachments.length > 0 && (
+ <div
+ role="list"
+ aria-label="Attached files"
+ className="flex flex-nowrap gap-2 w-full h-full overflow-x-auto attachments-container-enter"
+ >
+ {attachments.map((file, index) => (
+ <FileItemPreview
+ key={`${file.id}`}
+ attachment={file}
+ onRemove={() => handleRemoveFile(index)}
+ isUploading={status[file.name]?.status === 'uploading'}
+ />
+ ))}
+ </div>
+ )}
+
+ <div className="w-full h-fit overflow-y-auto">
+ <textarea
+ rows={1}
+ ref={inputRef}
+ value={message}
+ maxLength={maxLength}
+ onChange={handleChange}
+ onKeyDown={handleKeyDown}
+ aria-label="Message input"
+ onClick={(e) => e.stopPropagation()}
+ placeholder={`Message ${agentData?.name || ''}...`}
+ className="w-full min-h-12 max-h-96 bg-white border-none outline-none ring-0 focus:outline-none focus:border-none flex-1 resize-none ph-no-capture text-gray-900 placeholder:text-gray-500 px-1"
+ />
+ </div>
+
+ <div className="w-full flex gap-2 items-center justify-between">
+ <div className="relative flex items-center shrink min-w-0 gap-2">
+ <input
+ multiple
+ type="file"
+ ref={fileInputRef}
+ className="hidden"
+ aria-label="File attachment input"
+ onClick={(e) => e.stopPropagation()}
+ onChange={(e) => {
+ if (e.target.files?.length) {
+ addFiles(Array.from(e.target.files));
+ }
+ }}
+ />
+
+ <button
+ type="button"
+ aria-haspopup="menu"
+ onClick={toggleMenu}
+ ref={menuTriggerRef}
+ aria-label="Upload files"
+ aria-expanded={isMenuOpen}
+ className="border-[0.5px] transition-all h-8 flex items-center group cursor-pointer overflow-hidden px-1.5 min-w-8 rounded-lg justify-center text-gray-400 border-gray-200 hover:text-gray-600 hover:bg-gray-50 active:scale-[0.98] "
+ >
+ <PlusIcon />
+ </button>
+
+ <UploadMenu
+ isOpen={isMenuOpen}
+ onClose={closeMenu}
+ onAddFiles={handleAddFiles}
+ onTakeScreenshot={handleTakeScreenshot}
+ triggerRef={menuTriggerRef}
+ />
+ </div>
+
+ <SendButton
+ onClick={handleSubmit}
+ isStreaming={isStreaming}
+ disabled={!canSubmit || uploading}
+ />
+ </div>
+ </div>
</div>
- </div>
+ </fieldset>
</div>
);
};
diff --git a/packages/app/src/react/features/ai-chat/components/footer/send-button.tsx b/packages/app/src/react/features/ai-chat/components/footer/send-button.tsx
index 2ca4a4d5..d5d63c34 100644
--- a/packages/app/src/react/features/ai-chat/components/footer/send-button.tsx
+++ b/packages/app/src/react/features/ai-chat/components/footer/send-button.tsx
@@ -12,20 +12,6 @@ interface IProps {
}
export const SendButton: FC<IProps> = ({ isStreaming, disabled, onClick }) => (
- <Button
- addIcon
- variant="primary"
- disabled={disabled}
- handleClick={onClick}
- className={cn(
- 'h-[40px] w-[40px] rounded-lg px-0 py-0 disabled:cursor-not-allowed',
- isStreaming ? 'chat-stop' : 'chat-send',
- )}
- Icon={isStreaming ? <FaStop fontSize={14} /> : <SendIcon className="text-white" />}
- />
-);
-
-export const SendButton2: FC<IProps> = ({ isStreaming, disabled, onClick }) => (
<Button
addIcon
variant="primary"
diff --git a/packages/app/src/react/features/ai-chat/utils/index.ts b/packages/app/src/react/features/ai-chat/utils/index.ts
index e62fd902..2f630ad4 100644
--- a/packages/app/src/react/features/ai-chat/utils/index.ts
+++ b/packages/app/src/react/features/ai-chat/utils/index.ts
@@ -2,5 +2,6 @@ export * from './file';
export * from './model';
export * from './performance-monitor';
export * from './scroll';
+export * from './screenshot';
export * from './stream';
export * from './textarea';
diff --git a/packages/app/src/react/features/ai-chat/utils/screenshot.ts b/packages/app/src/react/features/ai-chat/utils/screenshot.ts
new file mode 100644
index 00000000..32d71797
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/utils/screenshot.ts
@@ -0,0 +1,94 @@
+/**
+ * Captures a screenshot using the browser's Screen Capture API.
+ * User will be prompted to select a screen, window, or tab to capture.
+ *
+ * @returns Promise<File | null> - The captured screenshot as a PNG File, or null if cancelled/failed
+ */
+export const captureScreenshot = async (): Promise<File | null> => {
+ let stream: MediaStream | null = null;
+
+ try {
+ // Request screen capture - browser will show native picker dialog
+ stream = await navigator.mediaDevices.getDisplayMedia({
+ video: { displaySurface: 'monitor' },
+ audio: false,
+ });
+
+ // Get the video track
+ const videoTrack = stream.getVideoTracks()[0];
+ if (!videoTrack) return null;
+
+ // Get track settings for dimensions
+ const settings = videoTrack.getSettings();
+ const width = settings.width || 1920;
+ const height = settings.height || 1080;
+
+ // Create video element to capture frame
+ const video = document.createElement('video');
+ video.srcObject = stream;
+ video.muted = true;
+ video.playsInline = true;
+
+ // Wait for video to be ready
+ await new Promise<void>((resolve, reject) => {
+ video.onloadedmetadata = () => {
+ video.play().then(resolve).catch(reject);
+ };
+ video.onerror = () => reject(new Error('Video loading failed'));
+ });
+
+ // Small delay to ensure frame is rendered
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Create canvas and draw video frame
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return null;
+
+ ctx.drawImage(video, 0, 0, width, height);
+
+ // Stop all tracks immediately after capture
+ stream.getTracks().forEach((track) => track.stop());
+ stream = null;
+
+ // Convert canvas to blob
+ const blob = await new Promise<Blob | null>((resolve) => {
+ canvas.toBlob(resolve, 'image/png', 1.0);
+ });
+
+ if (!blob) return null;
+
+ // Generate filename with timestamp
+ const timestamp = generateTimestamp();
+ const filename = `screenshot-${timestamp}.png`;
+
+ // Create File from Blob
+ return new File([blob], filename, { type: 'image/png' });
+ } catch {
+ // User cancelled or permission denied - silently return null
+ return null;
+ } finally {
+ // Ensure stream is stopped even on error
+ if (stream) stream.getTracks().forEach((track) => track.stop());
+ }
+};
+
+/**
+ * Generates a formatted timestamp string for filename
+ * Format: YYYY-MM-DD-HH-MM-SS
+ */
+const generateTimestamp = (): string => {
+ const now = new Date();
+
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ const day = String(now.getDate()).padStart(2, '0');
+ const hours = String(now.getHours()).padStart(2, '0');
+ const minutes = String(now.getMinutes()).padStart(2, '0');
+ const seconds = String(now.getSeconds()).padStart(2, '0');
+
+ return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
+};