@dudko.dev/agent-web-react 0.0.40 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -2,8 +2,8 @@ import * as react from 'react';
2
2
  import { DependencyList, ReactNode, RefObject, ComponentType, CSSProperties } from 'react';
3
3
  import { AskUserRequest, AskUserContext, AskUserAnswer, AskUserConfig, AskUserHandler, AgentEvent, RunFile, RunResult, Agent, ToolApprovalMode, AppToolCallRequest, AppSamplingRequest, AppSamplingView, AppSamplingResult, CompactResult, IUsage, AgentEventHandler, BrowserAgentConfig, VirtualFileInfo, VirtualFileSystem, CredentialStore, createWebLLMModel, WebLLMModelOptions, ModelTier, TierReason, EscalationReason, DecisionFallbackReason, Skill, IPlan, ToolApprovalRequest, ToolApprovalContext, ToolApprovalDecision } from '@dudko.dev/agent-web';
4
4
  export { Agent, AgentEvent, AgentEventHandler, AgentLoggerSink, AgentTool, AgentToolSet, AppToolCallRequest, AskUserAnswer, AskUserConfig, AskUserContext, AskUserHandler, AskUserOption, AskUserRequest, AttachmentsNotSupportedError, BrowserAgentConfig, CompactResult, CompactionConfig, CredentialStore, FileToolsOptions, IPlan, IPlanStep, IStepResult, IToolCall, IUsage, ImagesNotSupportedError, IndexedDBStore, LearningConfig, LogLevel, McpAppCsp, McpAppResource, McpAppToolResult, MemoryCredentialStore, MemorySkillStore, MemoryStore, ModelInput, ProviderModelSpec, ProviderType, RunControl, RunFile, RunOptions, RunResult, SessionBusyError, SessionHolder, SessionLockMode, SessionRunState, SessionWatch, Skill, SkillStore, StorageChange, StorageChangeKind, StorageChangeOp, SubagentInfo, SubagentToolOptions, SubagentWorkerConfig, ThinkingLevel, ThinkingSetting, TokenLimits, ToolApprovalConfig, ToolApprovalContext, ToolApprovalMode, ToolApprovalRequest, VaultCredentialStore, VfsSkillStore, VirtualFile, VirtualFileInfo, VirtualFileSystem, WatchSessionOptions, createAgent, createFileTools, createRunControl, createSubagentTool, createWebLLMModel, defineSkill, defineTool, isWebGPUAvailable, loadSkillFromUrl, markReadOnly, onStorageChange, parseSkillMarkdown, postStorageChange, preloadWebLLMModel, serveSubagentWorker, supportsImages, supportsPdf, unloadWebLLMModel, watchSession } from '@dudko.dev/agent-web';
5
- import { A as AgentUiState, C as ChatAttachment, a as ApprovalView, b as ChatMessage, c as AgentStatus, E as ElicitationIssueKind, d as ElicitationOutcomeReason, M as McpAppSandboxReason, R as RemoteRunView, L as LessonView, S as SubagentView, e as SubagentNode, P as PendingElicitation, f as McpElicitationResult, g as ElicitationView, W as WrittenFileView, T as ToolCallView, h as StepView, U as UserNoteView, D as DecisionView, i as MediaView, j as AppView, Q as QuestionView, k as McpAppsConnectionLike, l as McpAppSandboxOptions, m as AppRequestView, n as TranscriptView, B as BudgetView, o as CompactionView, p as ModelLoadState, q as McpAppHost, r as AppRequestAnswerOptions } from './elicitation-IpjGRDD-.cjs';
6
- export { s as APP_DEFAULT_HEIGHT, t as APP_MAX_HEIGHT, u as APP_MIN_HEIGHT, v as AppDownload, w as AppDownloadView, x as AppFileSaverEnv, y as AppLink, z as AppReadyDownload, F as AppResourceReader, G as ElicitationControl, H as ElicitationDraft, I as ElicitationDraftValue, J as ElicitationField, K as ElicitationFormOutcome, N as ElicitationIssue, O as ElicitationLink, V as ElicitationOption, X as FetchView, Y as MCP_APP_DISPLAY_MODES, Z as MCP_APP_MAX_ARGS_CHARS, _ as MCP_APP_MAX_DOWNLOAD_BYTES, $ as MCP_APP_MAX_FILE_NAME_CHARS, a0 as MCP_APP_MAX_IN_FLIGHT, a1 as MCP_APP_MAX_MESSAGE_CHARS, a2 as MCP_APP_MAX_URL_CHARS, a3 as MCP_APP_NOTIFICATIONS, a4 as MCP_APP_OPTIONAL_REQUESTS, a5 as MCP_APP_PROTOCOL_VERSION, a6 as MCP_APP_REFUSED, a7 as MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS, a8 as MCP_APP_REFUSED_DOWNLOAD_TYPES, a9 as MCP_APP_RELAY, aa as MCP_APP_REQUESTS, ab as MCP_APP_SANDBOX_FRAME_TOKENS, ac as MCP_APP_SANDBOX_GRACE_MS, ad as MCP_APP_SANDBOX_SERVER, ae as MCP_APP_SANDBOX_TIMEOUT_MS, af as McpAppBridge, ag as McpAppBridgeHandlers, ah as McpAppBridgeOptions, ai as McpAppDisplayMode, aj as McpAppRpcError, ak as McpAppRpcMessage, al as McpAppSandboxInput, am as McpAppSandboxLink, an as McpAppSandboxLinkOptions, ao as McpAppSandboxTarget, ap as McpElicitationFieldSchema, aq as McpElicitationRequest, ar as McpElicitationSchema, as as QueuedMessageView, at as ReplanState, au as SkillConsentView, av as StepEscalationView, aw as UseMcpAppHostOptions, ax as appDisplayModeAllowed, ay as appDownloadOf, az as appDownloadRefusal, aA as appFileExtensionOf, aB as appFileNameOf, aC as appGestureOf, aD as appLinkOf, aE as appMessageTextOf, aF as appMimeTypeOf, aG as appSamplingErrorOf, aH as buildMcpAppDocument, aI as buildMcpAppSandboxShell, aJ as clampAppHeight, aK as elicitationFields, aL as elicitationFormAnswer, aM as elicitationInitialDraft, aN as elicitationLink, aO as formatCountdown, aP as grantedAppCsp, aQ as mcpAppCsp, aR as mcpAppHostCapabilities, aS as mcpAppSandboxProxyUrl, aT as mcpAppSandboxShellCsp, aU as mcpAppSandboxTarget, aV as resolveAppDownload, aW as saveAppFile, aX as useMcpAppHost } from './elicitation-IpjGRDD-.cjs';
5
+ import { A as AgentUiState, C as ChatAttachment, a as ApprovalView, b as ChatMessage, c as AgentStatus, E as ElicitationIssueKind, d as ElicitationOutcomeReason, M as McpAppSandboxReason, R as RemoteRunView, L as LessonView, S as SubagentView, e as SubagentNode, P as PendingElicitation, f as McpElicitationResult, g as ElicitationView, W as WrittenFileView, T as ToolCallView, h as StepView, U as UserNoteView, D as DecisionView, i as MediaView, j as AppView, Q as QuestionView, k as McpAppsConnectionLike, l as McpAppSandboxOptions, m as AppRequestView, n as TranscriptView, B as BudgetView, o as CompactionView, p as ModelLoadState, q as McpAppHost, r as AppRequestAnswerOptions } from './elicitation-Dp6Fi6ZA.cjs';
6
+ export { s as APP_DEFAULT_HEIGHT, t as APP_MAX_HEIGHT, u as APP_MIN_HEIGHT, v as AppDownload, w as AppDownloadView, x as AppFileSaverEnv, y as AppLink, z as AppReadyDownload, F as AppResourceReader, G as ElicitationControl, H as ElicitationDraft, I as ElicitationDraftValue, J as ElicitationField, K as ElicitationFormOutcome, N as ElicitationIssue, O as ElicitationLink, V as ElicitationOption, X as FetchView, Y as MCP_APP_DISPLAY_MODES, Z as MCP_APP_MAX_ARGS_CHARS, _ as MCP_APP_MAX_DOWNLOAD_BYTES, $ as MCP_APP_MAX_FILE_NAME_CHARS, a0 as MCP_APP_MAX_IN_FLIGHT, a1 as MCP_APP_MAX_MESSAGE_CHARS, a2 as MCP_APP_MAX_URL_CHARS, a3 as MCP_APP_NOTIFICATIONS, a4 as MCP_APP_OPTIONAL_REQUESTS, a5 as MCP_APP_PROTOCOL_VERSION, a6 as MCP_APP_REFUSED, a7 as MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS, a8 as MCP_APP_REFUSED_DOWNLOAD_TYPES, a9 as MCP_APP_RELAY, aa as MCP_APP_REQUESTS, ab as MCP_APP_SANDBOX_FRAME_TOKENS, ac as MCP_APP_SANDBOX_GRACE_MS, ad as MCP_APP_SANDBOX_SERVER, ae as MCP_APP_SANDBOX_TIMEOUT_MS, af as McpAppBridge, ag as McpAppBridgeHandlers, ah as McpAppBridgeOptions, ai as McpAppDisplayMode, aj as McpAppRpcError, ak as McpAppRpcMessage, al as McpAppSandboxInput, am as McpAppSandboxLink, an as McpAppSandboxLinkOptions, ao as McpAppSandboxTarget, ap as McpElicitationFieldSchema, aq as McpElicitationRequest, ar as McpElicitationSchema, as as QueuedMessageView, at as ReplanState, au as SkillConsentView, av as StepEscalationView, aw as UseMcpAppHostOptions, ax as appDisplayModeAllowed, ay as appDownloadOf, az as appDownloadRefusal, aA as appFileExtensionOf, aB as appFileNameOf, aC as appGestureOf, aD as appLinkOf, aE as appMessageTextOf, aF as appMimeTypeOf, aG as appSamplingErrorOf, aH as buildMcpAppDocument, aI as buildMcpAppSandboxShell, aJ as clampAppHeight, aK as elicitationFields, aL as elicitationFormAnswer, aM as elicitationInitialDraft, aN as elicitationLink, aO as formatCountdown, aP as grantedAppCsp, aQ as mcpAppCsp, aR as mcpAppHostCapabilities, aS as mcpAppSandboxProxyUrl, aT as mcpAppSandboxShellCsp, aU as mcpAppSandboxTarget, aV as resolveAppDownload, aW as saveAppFile, aX as useMcpAppHost } from './elicitation-Dp6Fi6ZA.cjs';
7
7
  export { M as MCP_APP_POLICY_TOKEN_MAX_CHARS, a as MCP_APP_SANDBOX_PROXY_READY, b as MCP_APP_SANDBOX_RESOURCE_READY, i as isMcpAppSandboxMessage, m as mcpAppPolicyToken } from './mcp-app-policy-DIUmGPJP.cjs';
8
8
 
9
9
  /**
@@ -418,7 +418,9 @@ declare const unchangedSince: (messages: ChatMessage[], base: ChatBase | undefin
418
418
  * from here - that tab saves its own, unclipped copy. When another tab saved the chat after this
419
419
  * tab last read or wrote it (or saved a chat this tab never read), THAT record is the truth for
420
420
  * everything that is not this tab's own: this tab's own new messages - by identity, not by count,
421
- * so a reset or a trim here drops nothing there - go after it.
421
+ * so a reset or a trim here drops nothing there - go after it, each before a stored turn that
422
+ * began after its own (`ChatMessage.startedAt`: this tab saved its turn late, after another tab
423
+ * ran the next one and saved first). Without times, after it all.
422
424
  */
423
425
  declare const mergeChatRecord: (view: ChatRecord, stored: ChatRecord | undefined, base: ChatBase | undefined,
424
426
  /** The words of a title of attachments only (`chatTitle`). */
@@ -444,6 +446,10 @@ declare const saveChat: (store: ChatHistoryStore, view: ChatRecord, base: ChatBa
444
446
  * Several tabs: the list follows what other tabs of the site save (the store's `chats`
445
447
  * notices), the open chat is read again when another tab saved it and nothing runs here, and a
446
448
  * run followed from another tab (`agent.remote`) is never saved from here - its own tab saves it.
449
+ * A turn of this tab's is saved even when such a run reached it before the save began (a tab the
450
+ * browser froze, waking), and keeps its place among the other tab's turns (`mergeChatRecord`); a
451
+ * read of the chat again (another tab's save notice, a followed run's end) never replaces such a
452
+ * turn - it is saved first, merged, and the merged record shown.
447
453
  */
448
454
  declare const useChatHistory: (agent: UseAgentReturn, options?: UseChatHistoryOptions) => UseChatHistoryReturn;
449
455
 
@@ -2063,6 +2069,22 @@ interface ConvertedFile {
2063
2069
  text: string;
2064
2070
  /** Name of the text attachment (default: the file's name + ".md"). */
2065
2071
  name?: string;
2072
+ /** The attachment's note (default: `convertedFrom` - "converted from report.pdf"). */
2073
+ note?: string;
2074
+ /**
2075
+ * Pictures that go with the text (e.g. the pages of a scanned PDF): each is attached as an
2076
+ * image the composer took itself - downscaled, counted against `maxImages` / `maxTotalBytes`,
2077
+ * saved under `/attachments/` - and only when the model reads images (otherwise the refusal is
2078
+ * said and the text goes alone).
2079
+ */
2080
+ images?: ConvertedImage[];
2081
+ }
2082
+ /** A picture a `convertFile` made (`ConvertedFile.images`). */
2083
+ interface ConvertedImage {
2084
+ /** Its attachment's name, e.g. "scan-page-1.jpg". */
2085
+ name: string;
2086
+ /** The encoded picture; its `type` is the media type (an `image/*`). */
2087
+ blob: Blob;
2066
2088
  }
2067
2089
  interface AgentComposerProps {
2068
2090
  /** The agent from `useAgent()` (or `useAgentContext()`). */
@@ -3532,4 +3554,4 @@ interface AppRequestPromptProps {
3532
3554
  declare const AppRequestPrompt: ({ requests, onAnswer, renderRequest, labels, className, }: AppRequestPromptProps) => react.JSX.Element | null;
3533
3555
 
3534
3556
  export { ASK_USER_TOOL_NAME, ATTACHMENT_BOUNDS, AgentChat, AgentComposer, AgentLabelsProvider, AgentProvider, AgentStatus, AgentUiState, ApiKeyForm, AppRequestAnswerOptions, AppRequestPrompt, AppRequestView, AppView, ApprovalModeSwitch, ApprovalView, AttachmentView, BudgetView, ChatAttachment, ChatHistoryList, ChatHistoryStore, ChatMessage, CompactionView, Composer, ContextMeter, DecisionView, ElicitationIssueKind, ElicitationOutcomeReason, ElicitationPrompt, ElicitationView, FILE_PREVIEW_CHARS, FOLLOW_LEAVE_PX, FOLLOW_REJOIN_PX, FRAME_MAX_HEIGHT, FRAME_MIN_HEIGHT, FileChip, FileChips, FilesPanel, GeneratedMedia, HTML_PREVIEW_MAX_CHARS, ImageThumb, ImageViewer, ImageViewerProvider, LearnedSkills, LessonView, McpAppFrame, McpAppHost, McpAppLine, McpAppSandboxOptions, McpAppSandboxReason, McpAppsConnectionLike, McpElicitationResult, MediaView, MemoryCard, MessageList, MicError, ModelLoadBar, ModelLoadState, PendingElicitation, PlanView, QUESTION_TIMEOUT_MS, QuestionPrompt, QuestionView, RECORDING_DEFAULT_MAX_MS, RECORDING_TYPES, RemoteRunView, SandboxedFrame, SourceView, SpeechOutputError, StepList, StepView, SubagentNode, SubagentRow, SubagentTree, SubagentView, ToolApprovalPrompt, ToolCallRow, ToolCallView, TranscriptBlock, TranscriptView, UsageBadge, UserNoteRow, UserNoteView, agentStateReducer, agentStatusOf, askUserOutputKept, askUserWith, attachmentKindOf, attachmentOverLimit, attachmentRefusal, attachmentTransformOf, attachmentsText, audioExtensionOf, audioTypeOf, buildSandboxedDocument, chatTitle, clampFrameHeight, createApprovalQueue, createAudioSpeaker, createBrowserSpeaker, createInitialAgentState, createQuestionQueue, createRecordingRecognizer, createWebLLMEngine, decisionNote, defaultLabels, downscaleImage, escapeAttribute, fileKindOf, fileNameOf, filterCommands, followsAfterResize, followsAfterScroll, formatClock, formatElapsed, imageExtensionOf, imageSizeOf, languageOfText, lessonsOf, linkedFilesOf, mediaFamilyOf, menuKeyTarget, menuSections, mergeChatRecord, mergeLabels, messageOverLimit, micProblemOf, micProblemText, newChatId, noticesOf, parseSlash, pendingApprovalsOf, pickRecordingType, questionChoiceOf, questionOtherOf, questionTimeoutOf, recordingSupported, sandboxTokens, sandboxedCsp, saveChat, scriptOfLanguage, scriptOfText, settleAudioDuration, speakableText, speechSynthesisSupported, splitForSpeech, startRecording, steerIntent, stopTracks, subagentTree, tokenizeHtml, unchangedSince, usageLine, useAgent, useAgentContext, useAudioRecorder, useChatHistory, useCredentials, useFollowScroll, useLabels, useLocalModel, useOptionalAgentContext, useReadAloud, useSpeechToText, useSpeechVoices, useVirtualFiles, useWebLLMModel, voiceFor, voiceMessageName, voicesOf, webSearchOf, withAttachments, withCspFirst, withPolicyFirst, withoutOwnWords };
3535
- export type { AgentAction, AgentChatClassNames, AgentChatComponents, AgentChatProps, AgentChatSlots, AgentComposerProps, AgentLabels, AgentLabelsOverride, AgentLabelsProviderProps, AgentProviderProps, ApiKeyFormProps, AppRequestPromptProps, ApprovalModeSwitchProps, ApprovalQueue, ApproveOptions, AttachmentBounds, AttachmentOverLimit, AttachmentTexts, AttachmentTransform, AudioLike, AudioSpeakerOptions, BrowserSpeakerOptions, ChatBase, ChatHistoryListProps, ChatHistoryStoreOptions, ChatRecord, ChatSummary, ComposerAttachment, ComposerModelChip, ComposerModelOption, ComposerNotice, ComposerProps, ComposerThinkingChip, ContextMeterProps, ConvertedFile, DownscaleOptions, ElicitationPromptProps, FileChipProps, FileChipsProps, FileKind, FilesPanelProps, GeneratedMediaProps, HtmlPreviewOptions, ImageSize, ImageThumbProps, ImageViewerProps, LearnedSkillsProps, LocalModelEngine, LocalModelLoadContext, LocalModelProgress, McpAppFrameProps, McpAppLineProps, MediaRecorderConstructorLike, MediaRecorderLike, MemoryCardProps, MenuSection, MessageListProps, MicProblem, ModelLoadBarProps, NoticeTexts, PendingQuestion, PlanViewProps, QuestionOutcomeReason, QuestionPromptProps, QuestionQueue, QuestionQueueOptions, ReadAloudOptions, ReadAloudState, RecordedAudio, Recording, RecordingDeps, RecordingRecognizerOptions, RenderImageViewer, RenderSubagent, RenderToolCall, RunGoalOptions, SandboxedDocumentOptions, SandboxedFrameProps, ScrollMeasure, SlashCommand, SourceToken, SourceViewProps, SpeakText, SpeakableOptions, SpeechPlayback, SpeechRecognizerLike, SpeechScript, SpeechSynthesisLike, SpeechUtteranceLike, SpeechVoiceLike, StartRecordingOptions, SteerIntent, StepListProps, SubagentRowProps, SubagentTreeProps, SynthesizeSpeech, ToolApprovalPromptProps, ToolCallRowProps, TranscribeAudio, TranscriptBlockProps, UsageBadgeProps, UseAgentOptions, UseAgentReturn, UseAudioRecorderOptions, UseAudioRecorderReturn, UseChatHistoryOptions, UseChatHistoryReturn, UseCredentialsReturn, UseLocalModelOptions, UseLocalModelReturn, UseReadAloudReturn, UseSpeechToTextOptions, UseSpeechToTextReturn, UseVirtualFilesReturn, UseWebLLMModelOptions, UseWebLLMModelReturn, ViewerImage, WebLLMModelFactory, WebSearchResultView, WebSearchView };
3557
+ export type { AgentAction, AgentChatClassNames, AgentChatComponents, AgentChatProps, AgentChatSlots, AgentComposerProps, AgentLabels, AgentLabelsOverride, AgentLabelsProviderProps, AgentProviderProps, ApiKeyFormProps, AppRequestPromptProps, ApprovalModeSwitchProps, ApprovalQueue, ApproveOptions, AttachmentBounds, AttachmentOverLimit, AttachmentTexts, AttachmentTransform, AudioLike, AudioSpeakerOptions, BrowserSpeakerOptions, ChatBase, ChatHistoryListProps, ChatHistoryStoreOptions, ChatRecord, ChatSummary, ComposerAttachment, ComposerModelChip, ComposerModelOption, ComposerNotice, ComposerProps, ComposerThinkingChip, ContextMeterProps, ConvertedFile, ConvertedImage, DownscaleOptions, ElicitationPromptProps, FileChipProps, FileChipsProps, FileKind, FilesPanelProps, GeneratedMediaProps, HtmlPreviewOptions, ImageSize, ImageThumbProps, ImageViewerProps, LearnedSkillsProps, LocalModelEngine, LocalModelLoadContext, LocalModelProgress, McpAppFrameProps, McpAppLineProps, MediaRecorderConstructorLike, MediaRecorderLike, MemoryCardProps, MenuSection, MessageListProps, MicProblem, ModelLoadBarProps, NoticeTexts, PendingQuestion, PlanViewProps, QuestionOutcomeReason, QuestionPromptProps, QuestionQueue, QuestionQueueOptions, ReadAloudOptions, ReadAloudState, RecordedAudio, Recording, RecordingDeps, RecordingRecognizerOptions, RenderImageViewer, RenderSubagent, RenderToolCall, RunGoalOptions, SandboxedDocumentOptions, SandboxedFrameProps, ScrollMeasure, SlashCommand, SourceToken, SourceViewProps, SpeakText, SpeakableOptions, SpeechPlayback, SpeechRecognizerLike, SpeechScript, SpeechSynthesisLike, SpeechUtteranceLike, SpeechVoiceLike, StartRecordingOptions, SteerIntent, StepListProps, SubagentRowProps, SubagentTreeProps, SynthesizeSpeech, ToolApprovalPromptProps, ToolCallRowProps, TranscribeAudio, TranscriptBlockProps, UsageBadgeProps, UseAgentOptions, UseAgentReturn, UseAudioRecorderOptions, UseAudioRecorderReturn, UseChatHistoryOptions, UseChatHistoryReturn, UseCredentialsReturn, UseLocalModelOptions, UseLocalModelReturn, UseReadAloudReturn, UseSpeechToTextOptions, UseSpeechToTextReturn, UseVirtualFilesReturn, UseWebLLMModelOptions, UseWebLLMModelReturn, ViewerImage, WebLLMModelFactory, WebSearchResultView, WebSearchView };
package/dist/index.d.ts CHANGED
@@ -2,8 +2,8 @@ import * as react from 'react';
2
2
  import { DependencyList, ReactNode, RefObject, ComponentType, CSSProperties } from 'react';
3
3
  import { AskUserRequest, AskUserContext, AskUserAnswer, AskUserConfig, AskUserHandler, AgentEvent, RunFile, RunResult, Agent, ToolApprovalMode, AppToolCallRequest, AppSamplingRequest, AppSamplingView, AppSamplingResult, CompactResult, IUsage, AgentEventHandler, BrowserAgentConfig, VirtualFileInfo, VirtualFileSystem, CredentialStore, createWebLLMModel, WebLLMModelOptions, ModelTier, TierReason, EscalationReason, DecisionFallbackReason, Skill, IPlan, ToolApprovalRequest, ToolApprovalContext, ToolApprovalDecision } from '@dudko.dev/agent-web';
4
4
  export { Agent, AgentEvent, AgentEventHandler, AgentLoggerSink, AgentTool, AgentToolSet, AppToolCallRequest, AskUserAnswer, AskUserConfig, AskUserContext, AskUserHandler, AskUserOption, AskUserRequest, AttachmentsNotSupportedError, BrowserAgentConfig, CompactResult, CompactionConfig, CredentialStore, FileToolsOptions, IPlan, IPlanStep, IStepResult, IToolCall, IUsage, ImagesNotSupportedError, IndexedDBStore, LearningConfig, LogLevel, McpAppCsp, McpAppResource, McpAppToolResult, MemoryCredentialStore, MemorySkillStore, MemoryStore, ModelInput, ProviderModelSpec, ProviderType, RunControl, RunFile, RunOptions, RunResult, SessionBusyError, SessionHolder, SessionLockMode, SessionRunState, SessionWatch, Skill, SkillStore, StorageChange, StorageChangeKind, StorageChangeOp, SubagentInfo, SubagentToolOptions, SubagentWorkerConfig, ThinkingLevel, ThinkingSetting, TokenLimits, ToolApprovalConfig, ToolApprovalContext, ToolApprovalMode, ToolApprovalRequest, VaultCredentialStore, VfsSkillStore, VirtualFile, VirtualFileInfo, VirtualFileSystem, WatchSessionOptions, createAgent, createFileTools, createRunControl, createSubagentTool, createWebLLMModel, defineSkill, defineTool, isWebGPUAvailable, loadSkillFromUrl, markReadOnly, onStorageChange, parseSkillMarkdown, postStorageChange, preloadWebLLMModel, serveSubagentWorker, supportsImages, supportsPdf, unloadWebLLMModel, watchSession } from '@dudko.dev/agent-web';
5
- import { A as AgentUiState, C as ChatAttachment, a as ApprovalView, b as ChatMessage, c as AgentStatus, E as ElicitationIssueKind, d as ElicitationOutcomeReason, M as McpAppSandboxReason, R as RemoteRunView, L as LessonView, S as SubagentView, e as SubagentNode, P as PendingElicitation, f as McpElicitationResult, g as ElicitationView, W as WrittenFileView, T as ToolCallView, h as StepView, U as UserNoteView, D as DecisionView, i as MediaView, j as AppView, Q as QuestionView, k as McpAppsConnectionLike, l as McpAppSandboxOptions, m as AppRequestView, n as TranscriptView, B as BudgetView, o as CompactionView, p as ModelLoadState, q as McpAppHost, r as AppRequestAnswerOptions } from './elicitation-IpjGRDD-.js';
6
- export { s as APP_DEFAULT_HEIGHT, t as APP_MAX_HEIGHT, u as APP_MIN_HEIGHT, v as AppDownload, w as AppDownloadView, x as AppFileSaverEnv, y as AppLink, z as AppReadyDownload, F as AppResourceReader, G as ElicitationControl, H as ElicitationDraft, I as ElicitationDraftValue, J as ElicitationField, K as ElicitationFormOutcome, N as ElicitationIssue, O as ElicitationLink, V as ElicitationOption, X as FetchView, Y as MCP_APP_DISPLAY_MODES, Z as MCP_APP_MAX_ARGS_CHARS, _ as MCP_APP_MAX_DOWNLOAD_BYTES, $ as MCP_APP_MAX_FILE_NAME_CHARS, a0 as MCP_APP_MAX_IN_FLIGHT, a1 as MCP_APP_MAX_MESSAGE_CHARS, a2 as MCP_APP_MAX_URL_CHARS, a3 as MCP_APP_NOTIFICATIONS, a4 as MCP_APP_OPTIONAL_REQUESTS, a5 as MCP_APP_PROTOCOL_VERSION, a6 as MCP_APP_REFUSED, a7 as MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS, a8 as MCP_APP_REFUSED_DOWNLOAD_TYPES, a9 as MCP_APP_RELAY, aa as MCP_APP_REQUESTS, ab as MCP_APP_SANDBOX_FRAME_TOKENS, ac as MCP_APP_SANDBOX_GRACE_MS, ad as MCP_APP_SANDBOX_SERVER, ae as MCP_APP_SANDBOX_TIMEOUT_MS, af as McpAppBridge, ag as McpAppBridgeHandlers, ah as McpAppBridgeOptions, ai as McpAppDisplayMode, aj as McpAppRpcError, ak as McpAppRpcMessage, al as McpAppSandboxInput, am as McpAppSandboxLink, an as McpAppSandboxLinkOptions, ao as McpAppSandboxTarget, ap as McpElicitationFieldSchema, aq as McpElicitationRequest, ar as McpElicitationSchema, as as QueuedMessageView, at as ReplanState, au as SkillConsentView, av as StepEscalationView, aw as UseMcpAppHostOptions, ax as appDisplayModeAllowed, ay as appDownloadOf, az as appDownloadRefusal, aA as appFileExtensionOf, aB as appFileNameOf, aC as appGestureOf, aD as appLinkOf, aE as appMessageTextOf, aF as appMimeTypeOf, aG as appSamplingErrorOf, aH as buildMcpAppDocument, aI as buildMcpAppSandboxShell, aJ as clampAppHeight, aK as elicitationFields, aL as elicitationFormAnswer, aM as elicitationInitialDraft, aN as elicitationLink, aO as formatCountdown, aP as grantedAppCsp, aQ as mcpAppCsp, aR as mcpAppHostCapabilities, aS as mcpAppSandboxProxyUrl, aT as mcpAppSandboxShellCsp, aU as mcpAppSandboxTarget, aV as resolveAppDownload, aW as saveAppFile, aX as useMcpAppHost } from './elicitation-IpjGRDD-.js';
5
+ import { A as AgentUiState, C as ChatAttachment, a as ApprovalView, b as ChatMessage, c as AgentStatus, E as ElicitationIssueKind, d as ElicitationOutcomeReason, M as McpAppSandboxReason, R as RemoteRunView, L as LessonView, S as SubagentView, e as SubagentNode, P as PendingElicitation, f as McpElicitationResult, g as ElicitationView, W as WrittenFileView, T as ToolCallView, h as StepView, U as UserNoteView, D as DecisionView, i as MediaView, j as AppView, Q as QuestionView, k as McpAppsConnectionLike, l as McpAppSandboxOptions, m as AppRequestView, n as TranscriptView, B as BudgetView, o as CompactionView, p as ModelLoadState, q as McpAppHost, r as AppRequestAnswerOptions } from './elicitation-Dp6Fi6ZA.js';
6
+ export { s as APP_DEFAULT_HEIGHT, t as APP_MAX_HEIGHT, u as APP_MIN_HEIGHT, v as AppDownload, w as AppDownloadView, x as AppFileSaverEnv, y as AppLink, z as AppReadyDownload, F as AppResourceReader, G as ElicitationControl, H as ElicitationDraft, I as ElicitationDraftValue, J as ElicitationField, K as ElicitationFormOutcome, N as ElicitationIssue, O as ElicitationLink, V as ElicitationOption, X as FetchView, Y as MCP_APP_DISPLAY_MODES, Z as MCP_APP_MAX_ARGS_CHARS, _ as MCP_APP_MAX_DOWNLOAD_BYTES, $ as MCP_APP_MAX_FILE_NAME_CHARS, a0 as MCP_APP_MAX_IN_FLIGHT, a1 as MCP_APP_MAX_MESSAGE_CHARS, a2 as MCP_APP_MAX_URL_CHARS, a3 as MCP_APP_NOTIFICATIONS, a4 as MCP_APP_OPTIONAL_REQUESTS, a5 as MCP_APP_PROTOCOL_VERSION, a6 as MCP_APP_REFUSED, a7 as MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS, a8 as MCP_APP_REFUSED_DOWNLOAD_TYPES, a9 as MCP_APP_RELAY, aa as MCP_APP_REQUESTS, ab as MCP_APP_SANDBOX_FRAME_TOKENS, ac as MCP_APP_SANDBOX_GRACE_MS, ad as MCP_APP_SANDBOX_SERVER, ae as MCP_APP_SANDBOX_TIMEOUT_MS, af as McpAppBridge, ag as McpAppBridgeHandlers, ah as McpAppBridgeOptions, ai as McpAppDisplayMode, aj as McpAppRpcError, ak as McpAppRpcMessage, al as McpAppSandboxInput, am as McpAppSandboxLink, an as McpAppSandboxLinkOptions, ao as McpAppSandboxTarget, ap as McpElicitationFieldSchema, aq as McpElicitationRequest, ar as McpElicitationSchema, as as QueuedMessageView, at as ReplanState, au as SkillConsentView, av as StepEscalationView, aw as UseMcpAppHostOptions, ax as appDisplayModeAllowed, ay as appDownloadOf, az as appDownloadRefusal, aA as appFileExtensionOf, aB as appFileNameOf, aC as appGestureOf, aD as appLinkOf, aE as appMessageTextOf, aF as appMimeTypeOf, aG as appSamplingErrorOf, aH as buildMcpAppDocument, aI as buildMcpAppSandboxShell, aJ as clampAppHeight, aK as elicitationFields, aL as elicitationFormAnswer, aM as elicitationInitialDraft, aN as elicitationLink, aO as formatCountdown, aP as grantedAppCsp, aQ as mcpAppCsp, aR as mcpAppHostCapabilities, aS as mcpAppSandboxProxyUrl, aT as mcpAppSandboxShellCsp, aU as mcpAppSandboxTarget, aV as resolveAppDownload, aW as saveAppFile, aX as useMcpAppHost } from './elicitation-Dp6Fi6ZA.js';
7
7
  export { M as MCP_APP_POLICY_TOKEN_MAX_CHARS, a as MCP_APP_SANDBOX_PROXY_READY, b as MCP_APP_SANDBOX_RESOURCE_READY, i as isMcpAppSandboxMessage, m as mcpAppPolicyToken } from './mcp-app-policy-DIUmGPJP.js';
8
8
 
9
9
  /**
@@ -418,7 +418,9 @@ declare const unchangedSince: (messages: ChatMessage[], base: ChatBase | undefin
418
418
  * from here - that tab saves its own, unclipped copy. When another tab saved the chat after this
419
419
  * tab last read or wrote it (or saved a chat this tab never read), THAT record is the truth for
420
420
  * everything that is not this tab's own: this tab's own new messages - by identity, not by count,
421
- * so a reset or a trim here drops nothing there - go after it.
421
+ * so a reset or a trim here drops nothing there - go after it, each before a stored turn that
422
+ * began after its own (`ChatMessage.startedAt`: this tab saved its turn late, after another tab
423
+ * ran the next one and saved first). Without times, after it all.
422
424
  */
423
425
  declare const mergeChatRecord: (view: ChatRecord, stored: ChatRecord | undefined, base: ChatBase | undefined,
424
426
  /** The words of a title of attachments only (`chatTitle`). */
@@ -444,6 +446,10 @@ declare const saveChat: (store: ChatHistoryStore, view: ChatRecord, base: ChatBa
444
446
  * Several tabs: the list follows what other tabs of the site save (the store's `chats`
445
447
  * notices), the open chat is read again when another tab saved it and nothing runs here, and a
446
448
  * run followed from another tab (`agent.remote`) is never saved from here - its own tab saves it.
449
+ * A turn of this tab's is saved even when such a run reached it before the save began (a tab the
450
+ * browser froze, waking), and keeps its place among the other tab's turns (`mergeChatRecord`); a
451
+ * read of the chat again (another tab's save notice, a followed run's end) never replaces such a
452
+ * turn - it is saved first, merged, and the merged record shown.
447
453
  */
448
454
  declare const useChatHistory: (agent: UseAgentReturn, options?: UseChatHistoryOptions) => UseChatHistoryReturn;
449
455
 
@@ -2063,6 +2069,22 @@ interface ConvertedFile {
2063
2069
  text: string;
2064
2070
  /** Name of the text attachment (default: the file's name + ".md"). */
2065
2071
  name?: string;
2072
+ /** The attachment's note (default: `convertedFrom` - "converted from report.pdf"). */
2073
+ note?: string;
2074
+ /**
2075
+ * Pictures that go with the text (e.g. the pages of a scanned PDF): each is attached as an
2076
+ * image the composer took itself - downscaled, counted against `maxImages` / `maxTotalBytes`,
2077
+ * saved under `/attachments/` - and only when the model reads images (otherwise the refusal is
2078
+ * said and the text goes alone).
2079
+ */
2080
+ images?: ConvertedImage[];
2081
+ }
2082
+ /** A picture a `convertFile` made (`ConvertedFile.images`). */
2083
+ interface ConvertedImage {
2084
+ /** Its attachment's name, e.g. "scan-page-1.jpg". */
2085
+ name: string;
2086
+ /** The encoded picture; its `type` is the media type (an `image/*`). */
2087
+ blob: Blob;
2066
2088
  }
2067
2089
  interface AgentComposerProps {
2068
2090
  /** The agent from `useAgent()` (or `useAgentContext()`). */
@@ -3532,4 +3554,4 @@ interface AppRequestPromptProps {
3532
3554
  declare const AppRequestPrompt: ({ requests, onAnswer, renderRequest, labels, className, }: AppRequestPromptProps) => react.JSX.Element | null;
3533
3555
 
3534
3556
  export { ASK_USER_TOOL_NAME, ATTACHMENT_BOUNDS, AgentChat, AgentComposer, AgentLabelsProvider, AgentProvider, AgentStatus, AgentUiState, ApiKeyForm, AppRequestAnswerOptions, AppRequestPrompt, AppRequestView, AppView, ApprovalModeSwitch, ApprovalView, AttachmentView, BudgetView, ChatAttachment, ChatHistoryList, ChatHistoryStore, ChatMessage, CompactionView, Composer, ContextMeter, DecisionView, ElicitationIssueKind, ElicitationOutcomeReason, ElicitationPrompt, ElicitationView, FILE_PREVIEW_CHARS, FOLLOW_LEAVE_PX, FOLLOW_REJOIN_PX, FRAME_MAX_HEIGHT, FRAME_MIN_HEIGHT, FileChip, FileChips, FilesPanel, GeneratedMedia, HTML_PREVIEW_MAX_CHARS, ImageThumb, ImageViewer, ImageViewerProvider, LearnedSkills, LessonView, McpAppFrame, McpAppHost, McpAppLine, McpAppSandboxOptions, McpAppSandboxReason, McpAppsConnectionLike, McpElicitationResult, MediaView, MemoryCard, MessageList, MicError, ModelLoadBar, ModelLoadState, PendingElicitation, PlanView, QUESTION_TIMEOUT_MS, QuestionPrompt, QuestionView, RECORDING_DEFAULT_MAX_MS, RECORDING_TYPES, RemoteRunView, SandboxedFrame, SourceView, SpeechOutputError, StepList, StepView, SubagentNode, SubagentRow, SubagentTree, SubagentView, ToolApprovalPrompt, ToolCallRow, ToolCallView, TranscriptBlock, TranscriptView, UsageBadge, UserNoteRow, UserNoteView, agentStateReducer, agentStatusOf, askUserOutputKept, askUserWith, attachmentKindOf, attachmentOverLimit, attachmentRefusal, attachmentTransformOf, attachmentsText, audioExtensionOf, audioTypeOf, buildSandboxedDocument, chatTitle, clampFrameHeight, createApprovalQueue, createAudioSpeaker, createBrowserSpeaker, createInitialAgentState, createQuestionQueue, createRecordingRecognizer, createWebLLMEngine, decisionNote, defaultLabels, downscaleImage, escapeAttribute, fileKindOf, fileNameOf, filterCommands, followsAfterResize, followsAfterScroll, formatClock, formatElapsed, imageExtensionOf, imageSizeOf, languageOfText, lessonsOf, linkedFilesOf, mediaFamilyOf, menuKeyTarget, menuSections, mergeChatRecord, mergeLabels, messageOverLimit, micProblemOf, micProblemText, newChatId, noticesOf, parseSlash, pendingApprovalsOf, pickRecordingType, questionChoiceOf, questionOtherOf, questionTimeoutOf, recordingSupported, sandboxTokens, sandboxedCsp, saveChat, scriptOfLanguage, scriptOfText, settleAudioDuration, speakableText, speechSynthesisSupported, splitForSpeech, startRecording, steerIntent, stopTracks, subagentTree, tokenizeHtml, unchangedSince, usageLine, useAgent, useAgentContext, useAudioRecorder, useChatHistory, useCredentials, useFollowScroll, useLabels, useLocalModel, useOptionalAgentContext, useReadAloud, useSpeechToText, useSpeechVoices, useVirtualFiles, useWebLLMModel, voiceFor, voiceMessageName, voicesOf, webSearchOf, withAttachments, withCspFirst, withPolicyFirst, withoutOwnWords };
3535
- export type { AgentAction, AgentChatClassNames, AgentChatComponents, AgentChatProps, AgentChatSlots, AgentComposerProps, AgentLabels, AgentLabelsOverride, AgentLabelsProviderProps, AgentProviderProps, ApiKeyFormProps, AppRequestPromptProps, ApprovalModeSwitchProps, ApprovalQueue, ApproveOptions, AttachmentBounds, AttachmentOverLimit, AttachmentTexts, AttachmentTransform, AudioLike, AudioSpeakerOptions, BrowserSpeakerOptions, ChatBase, ChatHistoryListProps, ChatHistoryStoreOptions, ChatRecord, ChatSummary, ComposerAttachment, ComposerModelChip, ComposerModelOption, ComposerNotice, ComposerProps, ComposerThinkingChip, ContextMeterProps, ConvertedFile, DownscaleOptions, ElicitationPromptProps, FileChipProps, FileChipsProps, FileKind, FilesPanelProps, GeneratedMediaProps, HtmlPreviewOptions, ImageSize, ImageThumbProps, ImageViewerProps, LearnedSkillsProps, LocalModelEngine, LocalModelLoadContext, LocalModelProgress, McpAppFrameProps, McpAppLineProps, MediaRecorderConstructorLike, MediaRecorderLike, MemoryCardProps, MenuSection, MessageListProps, MicProblem, ModelLoadBarProps, NoticeTexts, PendingQuestion, PlanViewProps, QuestionOutcomeReason, QuestionPromptProps, QuestionQueue, QuestionQueueOptions, ReadAloudOptions, ReadAloudState, RecordedAudio, Recording, RecordingDeps, RecordingRecognizerOptions, RenderImageViewer, RenderSubagent, RenderToolCall, RunGoalOptions, SandboxedDocumentOptions, SandboxedFrameProps, ScrollMeasure, SlashCommand, SourceToken, SourceViewProps, SpeakText, SpeakableOptions, SpeechPlayback, SpeechRecognizerLike, SpeechScript, SpeechSynthesisLike, SpeechUtteranceLike, SpeechVoiceLike, StartRecordingOptions, SteerIntent, StepListProps, SubagentRowProps, SubagentTreeProps, SynthesizeSpeech, ToolApprovalPromptProps, ToolCallRowProps, TranscribeAudio, TranscriptBlockProps, UsageBadgeProps, UseAgentOptions, UseAgentReturn, UseAudioRecorderOptions, UseAudioRecorderReturn, UseChatHistoryOptions, UseChatHistoryReturn, UseCredentialsReturn, UseLocalModelOptions, UseLocalModelReturn, UseReadAloudReturn, UseSpeechToTextOptions, UseSpeechToTextReturn, UseVirtualFilesReturn, UseWebLLMModelOptions, UseWebLLMModelReturn, ViewerImage, WebLLMModelFactory, WebSearchResultView, WebSearchView };
3557
+ export type { AgentAction, AgentChatClassNames, AgentChatComponents, AgentChatProps, AgentChatSlots, AgentComposerProps, AgentLabels, AgentLabelsOverride, AgentLabelsProviderProps, AgentProviderProps, ApiKeyFormProps, AppRequestPromptProps, ApprovalModeSwitchProps, ApprovalQueue, ApproveOptions, AttachmentBounds, AttachmentOverLimit, AttachmentTexts, AttachmentTransform, AudioLike, AudioSpeakerOptions, BrowserSpeakerOptions, ChatBase, ChatHistoryListProps, ChatHistoryStoreOptions, ChatRecord, ChatSummary, ComposerAttachment, ComposerModelChip, ComposerModelOption, ComposerNotice, ComposerProps, ComposerThinkingChip, ContextMeterProps, ConvertedFile, ConvertedImage, DownscaleOptions, ElicitationPromptProps, FileChipProps, FileChipsProps, FileKind, FilesPanelProps, GeneratedMediaProps, HtmlPreviewOptions, ImageSize, ImageThumbProps, ImageViewerProps, LearnedSkillsProps, LocalModelEngine, LocalModelLoadContext, LocalModelProgress, McpAppFrameProps, McpAppLineProps, MediaRecorderConstructorLike, MediaRecorderLike, MemoryCardProps, MenuSection, MessageListProps, MicProblem, ModelLoadBarProps, NoticeTexts, PendingQuestion, PlanViewProps, QuestionOutcomeReason, QuestionPromptProps, QuestionQueue, QuestionQueueOptions, ReadAloudOptions, ReadAloudState, RecordedAudio, Recording, RecordingDeps, RecordingRecognizerOptions, RenderImageViewer, RenderSubagent, RenderToolCall, RunGoalOptions, SandboxedDocumentOptions, SandboxedFrameProps, ScrollMeasure, SlashCommand, SourceToken, SourceViewProps, SpeakText, SpeakableOptions, SpeechPlayback, SpeechRecognizerLike, SpeechScript, SpeechSynthesisLike, SpeechUtteranceLike, SpeechVoiceLike, StartRecordingOptions, SteerIntent, StepListProps, SubagentRowProps, SubagentTreeProps, SynthesizeSpeech, ToolApprovalPromptProps, ToolCallRowProps, TranscribeAudio, TranscriptBlockProps, UsageBadgeProps, UseAgentOptions, UseAgentReturn, UseAudioRecorderOptions, UseAudioRecorderReturn, UseChatHistoryOptions, UseChatHistoryReturn, UseCredentialsReturn, UseLocalModelOptions, UseLocalModelReturn, UseReadAloudReturn, UseSpeechToTextOptions, UseSpeechToTextReturn, UseVirtualFilesReturn, UseWebLLMModelOptions, UseWebLLMModelReturn, ViewerImage, WebLLMModelFactory, WebSearchResultView, WebSearchView };
package/dist/index.js CHANGED
@@ -816,6 +816,7 @@ var applyEvent = (state, event, ctx) => {
816
816
  const base = resetRun(ctx.remote ? state : withoutSubmitted(state));
817
817
  const userId = `msg-${base.seq}`;
818
818
  const assistantId = `msg-${base.seq + 1}`;
819
+ const began = ctx.at !== void 0 ? { startedAt: ctx.at } : {};
819
820
  return {
820
821
  ...base,
821
822
  // Another tab's run keeps the view of it; a run of this tab's ends it (and any wait).
@@ -833,6 +834,7 @@ var applyEvent = (state, event, ctx) => {
833
834
  content: event.goal,
834
835
  pending: false,
835
836
  ...ctx.remote ? { remote: true } : {},
837
+ ...began,
836
838
  ...ctx.attachments?.length ? { attachments: ctx.attachments } : {}
837
839
  },
838
840
  {
@@ -840,7 +842,8 @@ var applyEvent = (state, event, ctx) => {
840
842
  role: "assistant",
841
843
  content: "",
842
844
  pending: true,
843
- ...ctx.remote ? { remote: true } : {}
845
+ ...ctx.remote ? { remote: true } : {},
846
+ ...began
844
847
  }
845
848
  ],
846
849
  seq: base.seq + 2
@@ -2053,6 +2056,22 @@ var renumber = (own, after) => {
2053
2056
  );
2054
2057
  return own.map((m) => ({ ...m, id: `msg-${next += 1}` }));
2055
2058
  };
2059
+ var turnAt = (m) => typeof m.startedAt === "number" && Number.isFinite(m.startedAt) ? m.startedAt : void 0;
2060
+ var placeByTurn = (stored, own) => {
2061
+ let i = stored.length;
2062
+ while (i > 0 && turnAt(stored[i - 1]) !== void 0) i -= 1;
2063
+ const out = stored.slice(0, i);
2064
+ for (const m of own) {
2065
+ const at = turnAt(m);
2066
+ while (i < stored.length && (at === void 0 || turnAt(stored[i]) <= at)) {
2067
+ out.push(stored[i]);
2068
+ i += 1;
2069
+ }
2070
+ out.push(m);
2071
+ }
2072
+ return [...out, ...stored.slice(i)];
2073
+ };
2074
+ var ownUnsaved = (messages, base) => messages.some((m) => !m.remote && !base?.known.has(m));
2056
2075
  var unchangedSince = (messages, base) => base !== void 0 && messages.length === base.known.size && messages.every((m) => base.known.has(m));
2057
2076
  var mergeChatRecord = (view, stored, base, texts) => {
2058
2077
  const local = view.messages.filter((m) => !m.remote);
@@ -2060,7 +2079,7 @@ var mergeChatRecord = (view, stored, base, texts) => {
2060
2079
  return { record: { ...view, messages: local }, merged: false };
2061
2080
  }
2062
2081
  const own = local.filter((m) => !base?.known.has(m));
2063
- const messages = [...stored.messages, ...renumber(own, stored.messages)];
2082
+ const messages = placeByTurn(stored.messages, renumber(own, stored.messages));
2064
2083
  return {
2065
2084
  record: {
2066
2085
  ...view,
@@ -2095,7 +2114,18 @@ var useChatHistory = (agent, options = {}) => {
2095
2114
  const agentRef = useRef2(agent);
2096
2115
  agentRef.current = agent;
2097
2116
  const baseRef = useRef2(void 0);
2117
+ const loadingRef = useRef2(void 0);
2118
+ if (loadingRef.current && agent.messages !== loadingRef.current) loadingRef.current = void 0;
2098
2119
  const staleRef = useRef2(void 0);
2120
+ const queueRef = useRef2(Promise.resolve());
2121
+ const serially = useCallback2((task) => {
2122
+ const next = queueRef.current.then(task);
2123
+ queueRef.current = next.catch(() => {
2124
+ });
2125
+ return next;
2126
+ }, []);
2127
+ const baseOf = (id) => baseRef.current?.id === id ? baseRef.current : void 0;
2128
+ const unsavedHere = (messages2, id) => !loadingRef.current && ownUnsaved(messages2, baseOf(id));
2099
2129
  const refresh = useCallback2(async () => {
2100
2130
  try {
2101
2131
  setChats(await store.list());
@@ -2105,19 +2135,79 @@ var useChatHistory = (agent, options = {}) => {
2105
2135
  const newChat = useCallback2(() => {
2106
2136
  agentRef.current.loadChat({ sessionId: newChatId(), messages: [] });
2107
2137
  }, []);
2108
- const select = useCallback2(
2138
+ const show = useCallback2((record) => {
2139
+ createdRef.current.set(record.id, record.createdAt);
2140
+ baseRef.current = {
2141
+ id: record.id,
2142
+ known: new Set(record.messages),
2143
+ updatedAt: record.updatedAt
2144
+ };
2145
+ loadingRef.current ??= agentRef.current.messages;
2146
+ agentRef.current.loadChat({
2147
+ sessionId: record.id,
2148
+ messages: record.messages,
2149
+ totalUsage: record.totalUsage
2150
+ });
2151
+ }, []);
2152
+ const saveOpen = useCallback2(
2109
2153
  async (id) => {
2110
- const record = await store.get(id).catch(() => void 0);
2111
- if (!record) return;
2112
- createdRef.current.set(id, record.createdAt);
2113
- baseRef.current = { id, known: new Set(record.messages), updatedAt: record.updatedAt };
2114
- agentRef.current.loadChat({
2115
- sessionId: record.id,
2116
- messages: record.messages,
2117
- totalUsage: record.totalUsage
2118
- });
2154
+ const current = agentRef.current;
2155
+ if (current.sessionId !== id || current.isRunning) return;
2156
+ const { messages: messages2, totalUsage: totalUsage2, remote: remote2 } = current;
2157
+ if (messages2.length === 0) return;
2158
+ const base = baseOf(id);
2159
+ if (loadingRef.current || unchangedSince(messages2, base)) return;
2160
+ if (remote2 && !ownUnsaved(messages2, base)) return;
2161
+ const now = Date.now();
2162
+ const createdAt = createdRef.current.get(id) ?? now;
2163
+ createdRef.current.set(id, createdAt);
2164
+ const view = {
2165
+ id,
2166
+ title: chatTitle(messages2, textsRef.current),
2167
+ createdAt,
2168
+ updatedAt: now,
2169
+ messages: messages2,
2170
+ totalUsage: totalUsage2
2171
+ };
2172
+ const { record, merged } = await saveChat(store, view, base, textsRef.current);
2173
+ baseRef.current = {
2174
+ id,
2175
+ known: new Set(merged ? record.messages : messages2),
2176
+ updatedAt: record.updatedAt
2177
+ };
2178
+ await refresh();
2179
+ if (merged && agentRef.current.sessionId === id) show(record);
2119
2180
  },
2120
- [store]
2181
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2182
+ [store, show]
2183
+ );
2184
+ const reread = useCallback2(
2185
+ (id) => serially(async () => {
2186
+ const settled = () => {
2187
+ const current = agentRef.current;
2188
+ if (current.sessionId !== id) return false;
2189
+ if (current.isRunning) {
2190
+ if (current.remote?.running) staleRef.current = id;
2191
+ return false;
2192
+ }
2193
+ return true;
2194
+ };
2195
+ if (!settled()) return;
2196
+ if (unsavedHere(agentRef.current.messages, id)) return saveOpen(id);
2197
+ const record = await store.get(id).catch(() => void 0);
2198
+ if (!record || !settled()) return;
2199
+ if (unsavedHere(agentRef.current.messages, id)) return saveOpen(id);
2200
+ show(record);
2201
+ }),
2202
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2203
+ [store, serially, saveOpen, show]
2204
+ );
2205
+ const select = useCallback2(
2206
+ (id) => serially(async () => {
2207
+ const record = await store.get(id).catch(() => void 0);
2208
+ if (record) show(record);
2209
+ }),
2210
+ [store, serially, show]
2121
2211
  );
2122
2212
  const remove = useCallback2(
2123
2213
  async (id) => {
@@ -2161,44 +2251,34 @@ var useChatHistory = (agent, options = {}) => {
2161
2251
  const current = agentRef.current;
2162
2252
  if (key === void 0 || key !== current.sessionId) return;
2163
2253
  if (current.remote?.running) staleRef.current = key;
2164
- else if (!current.isRunning) void select(key);
2254
+ else if (!current.isRunning) void reread(key);
2165
2255
  }
2166
2256
  );
2167
- }, [enabled, store, refresh, select]);
2257
+ }, [enabled, store, refresh, reread]);
2168
2258
  const { messages, totalUsage, sessionId, isRunning, remote } = agent;
2169
2259
  useEffect2(() => {
2170
2260
  if (!enabled || loading || isRunning) return;
2171
2261
  if (staleRef.current === sessionId) {
2172
2262
  staleRef.current = void 0;
2173
- void select(sessionId);
2263
+ void reread(sessionId).catch(() => {
2264
+ });
2174
2265
  return;
2175
2266
  }
2176
- if (remote || messages.length === 0) return;
2177
- const base = baseRef.current?.id === sessionId ? baseRef.current : void 0;
2178
- if (unchangedSince(messages, base)) return;
2179
- const now = Date.now();
2180
- const createdAt = createdRef.current.get(sessionId) ?? now;
2181
- createdRef.current.set(sessionId, createdAt);
2182
- const view = {
2183
- id: sessionId,
2184
- title: chatTitle(messages, textsRef.current),
2185
- createdAt,
2186
- updatedAt: now,
2187
- messages,
2188
- totalUsage
2189
- };
2190
- void (async () => {
2191
- const { record, merged } = await saveChat(store, view, base, textsRef.current);
2192
- baseRef.current = {
2193
- id: sessionId,
2194
- known: new Set(merged ? record.messages : messages),
2195
- updatedAt: record.updatedAt
2196
- };
2197
- await refresh();
2198
- if (merged && agentRef.current.sessionId === sessionId) await select(sessionId);
2199
- })().catch(() => {
2267
+ if (messages.length === 0) return;
2268
+ void serially(() => saveOpen(sessionId)).catch(() => {
2200
2269
  });
2201
- }, [enabled, loading, isRunning, remote, messages, totalUsage, sessionId, store, refresh, select]);
2270
+ }, [
2271
+ enabled,
2272
+ loading,
2273
+ isRunning,
2274
+ remote,
2275
+ messages,
2276
+ totalUsage,
2277
+ sessionId,
2278
+ serially,
2279
+ saveOpen,
2280
+ reread
2281
+ ]);
2202
2282
  return { chats, currentId: sessionId, loading, select, newChat, remove };
2203
2283
  };
2204
2284
 
@@ -6375,6 +6455,47 @@ ${draftText}` : draftText);
6375
6455
  if (full) noRoom[full].push(name);
6376
6456
  else setPending((cur) => [...cur, a]);
6377
6457
  };
6458
+ const sendAs = async (name, f, kind, mediaType, transform, id) => {
6459
+ const blob = transform === "downscale" ? await downscaleImage(f, {
6460
+ maxDimension: imageMax,
6461
+ maxPixels: attachCfg.imageMaxPixels
6462
+ }) : f;
6463
+ const sentOver = attachmentOverLimit({ bytes: blob.size }, "sent", transform, bounds);
6464
+ if (sentOver) return overLimitText(name, sentOver);
6465
+ add(name, {
6466
+ id,
6467
+ name,
6468
+ kind,
6469
+ mediaType: blob.type || mediaType,
6470
+ dataUrl: await readDataUrl2(blob),
6471
+ bytes: blob.size,
6472
+ ...blob !== f ? { note: L.downscaledFrom(L.bytes(f.size)) } : {}
6473
+ });
6474
+ return void 0;
6475
+ };
6476
+ const addImage = async (name, blob, id) => {
6477
+ const mediaType = blob.type || "image/jpeg";
6478
+ if (attachmentKindOf(mediaType, name) !== "image") return L.binaryText(name);
6479
+ const transform = attachmentTransformOf({
6480
+ kind: "image",
6481
+ mediaType,
6482
+ imageMaxDimension: imageMax,
6483
+ converts: false
6484
+ });
6485
+ const size = transform === "downscale" ? await imageSizeOf(blob) : void 0;
6486
+ const over = attachmentOverLimit(
6487
+ { bytes: blob.size, pixels: size && size.width * size.height },
6488
+ "original",
6489
+ transform,
6490
+ bounds
6491
+ );
6492
+ if (over) return overLimitText(name, over);
6493
+ if (messageOverLimit(pendingRef.current, { kind: "image", bytes: 0 }, bounds) === "images") {
6494
+ noRoom.images.push(name);
6495
+ return void 0;
6496
+ }
6497
+ return sendAs(name, blob, "image", mediaType, transform, id);
6498
+ };
6378
6499
  for (const f of list) {
6379
6500
  const mediaType = f.type || "application/octet-stream";
6380
6501
  const name = f.name || `pasted-${Date.now()}.${mediaType.split("/")[1] ?? "bin"}`;
@@ -6413,9 +6534,9 @@ ${draftText}` : draftText);
6413
6534
  const converted = await convertFile(f);
6414
6535
  if (converted) {
6415
6536
  const bytes = new Blob([converted.text]).size;
6416
- const sentOver2 = attachmentOverLimit({ bytes }, "sent", transform, bounds);
6417
- if (sentOver2) {
6418
- problem = overLimitText(name, sentOver2);
6537
+ const sentOver = attachmentOverLimit({ bytes }, "sent", transform, bounds);
6538
+ if (sentOver) {
6539
+ problem = overLimitText(name, sentOver);
6419
6540
  continue;
6420
6541
  }
6421
6542
  add(name, {
@@ -6425,8 +6546,18 @@ ${draftText}` : draftText);
6425
6546
  mediaType: "text/markdown",
6426
6547
  text: converted.text,
6427
6548
  bytes,
6428
- note: L.convertedFrom(name)
6549
+ note: converted.note ?? L.convertedFrom(name)
6429
6550
  });
6551
+ const images = converted.images ?? [];
6552
+ if (images.length > 0) {
6553
+ const imageRefusal = attachmentRefusal("image", caps);
6554
+ if (imageRefusal) problem = imageRefusal;
6555
+ else
6556
+ for (const image of images) {
6557
+ const said3 = await addImage(image.name, image.blob, `att-${attachSeq += 1}`);
6558
+ if (said3) problem = said3;
6559
+ }
6560
+ }
6430
6561
  continue;
6431
6562
  }
6432
6563
  }
@@ -6434,24 +6565,8 @@ ${draftText}` : draftText);
6434
6565
  problem = refusal;
6435
6566
  continue;
6436
6567
  }
6437
- const blob = transform === "downscale" ? await downscaleImage(f, {
6438
- maxDimension: imageMax,
6439
- maxPixels: attachCfg.imageMaxPixels
6440
- }) : f;
6441
- const sentOver = attachmentOverLimit({ bytes: blob.size }, "sent", transform, bounds);
6442
- if (sentOver) {
6443
- problem = overLimitText(name, sentOver);
6444
- continue;
6445
- }
6446
- add(name, {
6447
- id,
6448
- name,
6449
- kind,
6450
- mediaType: blob.type || mediaType,
6451
- dataUrl: await readDataUrl2(blob),
6452
- bytes: blob.size,
6453
- ...blob !== f ? { note: L.downscaledFrom(L.bytes(f.size)) } : {}
6454
- });
6568
+ const said2 = await sendAs(name, f, kind, mediaType, transform, id);
6569
+ if (said2) problem = said2;
6455
6570
  } catch (err) {
6456
6571
  problem = `${name}: ${err instanceof Error ? err.message : String(err)}`;
6457
6572
  }