Skip to content

AI-native design editor. Open-source Figma alternative.

fix(desktop): route chat input shortcuts to the field, stream chat, resume autoscroll (#1158)

Danila Poyarkov4a2a4a4fc518
diff --git a/changes/1158/fixed.md b/changes/1158/fixed.md
new file mode 100644
index 000000000..7007ec1d3
--- /dev/null
+++ b/changes/1158/fixed.md
@@ -0,0 +1,3 @@
+- In the desktop app, Select All, Undo, and Redo typed in a text field such as the chat input act on the field instead of the canvas, and other canvas shortcuts no longer reach the canvas from a text field.
+- AI chat streams in the desktop app, and a reply keeps going past 30 seconds while it is still arriving instead of failing with "Desktop HTTP request failed"; a request that cannot reach the provider is retried before the reply starts.
+- Scrolling the chat back to the bottom resumes following new output.
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
index ef3f8a2ee..05aa53f11 100644
--- a/desktop/Cargo.lock
+++ b/desktop/Cargo.lock
@@ -3278,6 +3278,7 @@ dependencies = [
"tauri-plugin-single-instance",
"tauri-plugin-updater",
"tauri-plugin-wdio-webdriver",
+ "tokio",
"url",
"which",
"zip 2.4.2",
diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml
index a7c96cffe..b45ebf6e8 100644
--- a/desktop/Cargo.toml
+++ b/desktop/Cargo.toml
@@ -28,6 +28,7 @@ tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
+tokio = { version = "1", features = ["sync"] }
tauri-plugin-dialog = "2.6.0"
tauri-plugin-fs = { version = "2.4.5", features = ["watch"] }
tauri-plugin-shell = "2"
diff --git a/desktop/src/http.rs b/desktop/src/http.rs
index a6a2a4df0..86e089ff4 100644
--- a/desktop/src/http.rs
+++ b/desktop/src/http.rs
@@ -3,7 +3,13 @@ use reqwest::{
Method,
};
use serde::{Deserialize, Serialize};
+use std::collections::{HashMap, HashSet};
+use std::sync::Mutex;
use std::time::Duration;
+use tauri::async_runtime::JoinHandle;
+use tauri::ipc::{Channel, InvokeResponseBody};
+use tauri::Manager;
+use tokio::sync::oneshot;
#[derive(Clone, Deserialize, Serialize)]
pub struct ProxyHttpHeader {
@@ -13,6 +19,8 @@ pub struct ProxyHttpHeader {
#[derive(Deserialize)]
pub struct ProxyHttpRequest {
+ /// Chosen by the page so it can cancel the request before the head arrives.
+ id: String,
url: String,
method: Option<String>,
headers: Option<Vec<ProxyHttpHeader>>,
@@ -22,14 +30,89 @@ pub struct ProxyHttpRequest {
timeout_ms: Option<u64>,
}
+/// Status and headers; the body follows on the request's channel.
#[derive(Serialize)]
-pub struct ProxyHttpResponse {
+pub struct ProxyHttpHead {
status: u16,
headers: Vec<ProxyHttpHeader>,
- body: Vec<u8>,
url: String,
}
+/// `network` marks failures to reach the server or read from it, which the page
+/// reports the way `fetch` does so callers can retry them.
+#[derive(Serialize)]
+pub struct ProxyHttpError {
+ network: bool,
+ message: String,
+}
+
+impl ProxyHttpError {
+ fn request(message: impl Into<String>) -> Self {
+ Self {
+ network: false,
+ message: message.into(),
+ }
+ }
+
+ fn network(error: reqwest::Error) -> Self {
+ Self {
+ network: true,
+ message: error.to_string(),
+ }
+ }
+}
+
+/// The end of a body on the request's channel; chunks before it are raw bytes.
+#[derive(Serialize)]
+#[serde(untagged)]
+enum ProxyHttpBodyEnd {
+ Done { done: bool },
+ Error { error: ProxyHttpError },
+}
+
+/// Requests in flight, so the page can cancel one, and cancellations that arrived
+/// first: Tauri runs `proxy_http_request` on its own task, so `cancel_http_request`
+/// can run before the request is registered.
+#[derive(Default)]
+pub struct ProxyHttpRequests(Mutex<Requests>);
+
+#[derive(Default)]
+struct Requests {
+ tasks: HashMap<String, JoinHandle<()>>,
+ cancelled: HashSet<String>,
+}
+
+impl Requests {
+ /// Stops a registered request, or refuses it when it registers later.
+ fn cancel(&mut self, id: String) {
+ match self.tasks.remove(&id) {
+ Some(task) => task.abort(),
+ None => {
+ self.cancelled.insert(id);
+ }
+ }
+ }
+
+ /// Whether a request may start; false once the page cancelled it.
+ fn admit(&mut self, id: &str) -> bool {
+ !self.cancelled.remove(id)
+ }
+}
+
+impl ProxyHttpRequests {
+ fn requests(&self) -> std::sync::MutexGuard<'_, Requests> {
+ self.0
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
+}
+
+fn cancelled() -> ProxyHttpError {
+ ProxyHttpError::request("The request was cancelled")
+}
+
+type HeadResult = Result<ProxyHttpHead, ProxyHttpError>;
+
fn request_headers(headers: Option<Vec<ProxyHttpHeader>>) -> HeaderMap {
let mut mapped = HeaderMap::new();
for header in headers.unwrap_or_default() {
@@ -44,16 +127,18 @@ fn request_headers(headers: Option<Vec<ProxyHttpHeader>>) -> HeaderMap {
mapped
}
-fn request_method(method: Option<String>) -> Result<Method, String> {
+fn request_method(method: Option<String>) -> Result<Method, ProxyHttpError> {
let raw = method.unwrap_or_else(|| "GET".into());
- Method::from_bytes(raw.as_bytes()).map_err(|e| e.to_string())
+ Method::from_bytes(raw.as_bytes()).map_err(|e| ProxyHttpError::request(e.to_string()))
}
-#[tauri::command]
-pub async fn proxy_http_request(request: ProxyHttpRequest) -> Result<ProxyHttpResponse, String> {
- let parsed = reqwest::Url::parse(&request.url).map_err(|e| e.to_string())?;
+async fn send(request: ProxyHttpRequest) -> Result<reqwest::Response, ProxyHttpError> {
+ let parsed =
+ reqwest::Url::parse(&request.url).map_err(|e| ProxyHttpError::request(e.to_string()))?;
if !matches!(parsed.scheme(), "http" | "https") {
- return Err("Only HTTP(S) requests are supported".into());
+ return Err(ProxyHttpError::request(
+ "Only HTTP(S) requests are supported",
+ ));
}
let redirect_policy = if request.follow_redirects.unwrap_or(true) {
@@ -63,9 +148,12 @@ pub async fn proxy_http_request(request: ProxyHttpRequest) -> Result<ProxyHttpRe
};
let client = reqwest::Client::builder()
.redirect(redirect_policy)
- .timeout(Duration::from_secs(30))
+ // An idle limit, not a total one: a streamed model response can run for
+ // minutes while still delivering bytes. Callers cap the total with timeout_ms.
+ .connect_timeout(Duration::from_secs(30))
+ .read_timeout(Duration::from_secs(30))
.build()
- .map_err(|e| e.to_string())?;
+ .map_err(|e| ProxyHttpError::request(e.to_string()))?;
let mut builder = client
.request(request_method(request.method)?, parsed)
.headers(request_headers(request.headers));
@@ -74,14 +162,42 @@ pub async fn proxy_http_request(request: ProxyHttpRequest) -> Result<ProxyHttpRe
}
if let Some(timeout_ms) = request.timeout_ms {
if timeout_ms == 0 {
- return Err("timeoutMs must be greater than 0".into());
+ return Err(ProxyHttpError::request("timeoutMs must be greater than 0"));
}
builder = builder.timeout(Duration::from_millis(timeout_ms));
}
+ builder.send().await.map_err(ProxyHttpError::network)
+}
+
+fn size_limit_error() -> ProxyHttpError {
+ ProxyHttpError::request("HTTP response exceeds the configured size limit")
+}
+
+fn end_body(on_body: &Channel<InvokeResponseBody>, end: ProxyHttpBodyEnd) {
+ if let Ok(json) = serde_json::to_string(&end) {
+ let _ = on_body.send(InvokeResponseBody::Json(json));
+ }
+}
- let mut response = builder.send().await.map_err(|e| e.to_string())?;
- let status = response.status().as_u16();
- let url = response.url().to_string();
+async fn run(
+ request: ProxyHttpRequest,
+ head: oneshot::Sender<HeadResult>,
+ on_body: Channel<InvokeResponseBody>,
+) {
+ let limit = request.max_response_bytes;
+ let mut response = match send(request).await {
+ Ok(response) => response,
+ Err(error) => {
+ let _ = head.send(Err(error));
+ return;
+ }
+ };
+ if let (Some(limit), Some(content_length)) = (limit, response.content_length()) {
+ if content_length > limit as u64 {
+ let _ = head.send(Err(size_limit_error()));
+ return;
+ }
+ }
let headers = response
.headers()
.iter()
@@ -92,28 +208,105 @@ pub async fn proxy_http_request(request: ProxyHttpRequest) -> Result<ProxyHttpRe
})
})
.collect();
- if let (Some(limit), Some(content_length)) =
- (request.max_response_bytes, response.content_length())
- {
- if content_length > limit as u64 {
- return Err("HTTP response exceeds the configured size limit".into());
+ let sent = head.send(Ok(ProxyHttpHead {
+ status: response.status().as_u16(),
+ headers,
+ url: response.url().to_string(),
+ }));
+ if sent.is_err() {
+ return;
+ }
+
+ let mut received = 0;
+ loop {
+ match response.chunk().await {
+ Ok(Some(chunk)) => {
+ received += chunk.len();
+ if limit.is_some_and(|limit| received > limit) {
+ end_body(
+ &on_body,
+ ProxyHttpBodyEnd::Error {
+ error: size_limit_error(),
+ },
+ );
+ return;
+ }
+ if on_body
+ .send(InvokeResponseBody::Raw(chunk.to_vec()))
+ .is_err()
+ {
+ return;
+ }
+ }
+ Ok(None) => {
+ end_body(&on_body, ProxyHttpBodyEnd::Done { done: true });
+ return;
+ }
+ Err(error) => {
+ end_body(
+ &on_body,
+ ProxyHttpBodyEnd::Error {
+ error: ProxyHttpError::network(error),
+ },
+ );
+ return;
+ }
}
}
- let mut body = Vec::new();
- while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
- if request
- .max_response_bytes
- .is_some_and(|limit| body.len() + chunk.len() > limit)
- {
- return Err("HTTP response exceeds the configured size limit".into());
+}
+
+/// Sends a request from the native side, out of reach of WebView CORS. Resolves
+/// with the head as soon as it arrives and streams the body to `on_body`.
+#[tauri::command]
+pub async fn proxy_http_request<R: tauri::Runtime>(
+ app: tauri::AppHandle<R>,
+ request: ProxyHttpRequest,
+ on_body: Channel<InvokeResponseBody>,
+) -> HeadResult {
+ let id = request.id.clone();
+ let (head, head_received) = oneshot::channel();
+ {
+ // Held while spawning, so the task cannot remove its entry before it exists.
+ let state = app.state::<ProxyHttpRequests>();
+ let mut requests = state.requests();
+ if !requests.admit(&id) {
+ return Err(cancelled());
+ }
+ let task_app = app.clone();
+ let task_id = id.clone();
+ let task = tauri::async_runtime::spawn(async move {
+ run(request, head, on_body).await;
+ task_app
+ .state::<ProxyHttpRequests>()
+ .requests()
+ .tasks
+ .remove(&task_id);
+ });
+ if let Some(previous) = requests.tasks.insert(id, task) {
+ previous.abort();
}
- body.extend_from_slice(&chunk);
}
+ head_received.await.map_err(|_| cancelled())?
+}
- Ok(ProxyHttpResponse {
- status,
- headers,
- body,
- url,
- })
+/// Stops a request and its body stream, closing the connection.
+#[tauri::command]
+pub fn cancel_http_request(requests: tauri::State<'_, ProxyHttpRequests>, id: String) {
+ requests.requests().cancel(id);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::Requests;
+
+ #[test]
+ fn a_cancel_before_registration_refuses_the_request() {
+ let mut requests = Requests::default();
+ requests.cancel("early".into());
+
+ assert!(!requests.admit("early"));
+ // The refusal is spent; the id is not refused again.
+ assert!(requests.admit("early"));
+ assert!(requests.admit("other"));
+ }
}
diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs
index b1fb1cbe4..8071484e5 100644
--- a/desktop/src/lib.rs
+++ b/desktop/src/lib.rs
@@ -16,7 +16,7 @@ use credentials::{
use deep_link::path_matches_suffix;
use fig_container::build_fig_file;
use fonts::{list_system_fonts, load_system_font};
-use http::proxy_http_request;
+use http::{cancel_http_request, proxy_http_request, ProxyHttpRequests};
use menu::{install_app_menu, native_menu_checked, set_native_menu_checked};
use menu_events::handle_menu_event;
use std::{
@@ -359,6 +359,7 @@ pub fn run() {
builder
.manage(PendingOpen(Mutex::new(Vec::new())))
+ .manage(ProxyHttpRequests::default())
.manage(PendingRooms(Mutex::new(Vec::new())))
.invoke_handler(tauri::generate_handler![
agents::agent_lookup,
@@ -375,6 +376,7 @@ pub fn run() {
list_system_fonts,
load_system_font,
proxy_http_request,
+ cancel_http_request,
set_recent_files,
native_menu_checked,
set_native_menu_checked,
diff --git a/packages/vue/src/canvas/text-edit/textarea.ts b/packages/vue/src/canvas/text-edit/textarea.ts
index 110970d2d..da2ab9af8 100644
--- a/packages/vue/src/canvas/text-edit/textarea.ts
+++ b/packages/vue/src/canvas/text-edit/textarea.ts
@@ -3,8 +3,20 @@ import type { ShallowRef } from 'vue'
import type { Editor } from '@open-pencil/core/editor'
+const CANVAS_TEXT_INPUT = 'data-canvas-text-input'
+
+/**
+ * Whether `element` is the hidden textarea the canvas text editor types through. Focus can leave
+ * it for a page field while the text edit stays open, so callers ask this rather than whether a
+ * text edit is active.
+ */
+export function isCanvasTextInput(element: Element | null): boolean {
+ return element?.hasAttribute(CANVAS_TEXT_INPUT) ?? false
+}
+
export function createHiddenTextArea() {
const textarea = document.createElement('textarea')
+ textarea.setAttribute(CANVAS_TEXT_INPUT, '')
textarea.setAttribute('aria-hidden', 'true')
textarea.tabIndex = -1
textarea.className = 'fixed left-0 top-0 h-px w-px opacity-0'
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index 9b81b568f..6761bbfd1 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -32,6 +32,7 @@ export type { CanvasIssueMarkerOptions } from '#vue/canvas/issues/use'
export type { CanvasLabelEdit, CanvasLabelKind } from '#vue/canvas/labels/edit'
export { useCanvasVirtualReference } from '#vue/canvas/overlays/useCanvasVirtualReference'
export { useTextEdit } from '#vue/canvas/text-edit/use'
+export { isCanvasTextInput } from '#vue/canvas/text-edit/textarea'
export {
useCanvasDrop,
extractImageFilesFromClipboard,
diff --git a/src/app/shell/commands/focused.ts b/src/app/shell/commands/focused.ts
new file mode 100644
index 000000000..bcbd27e86
--- /dev/null
+++ b/src/app/shell/commands/focused.ts
@@ -0,0 +1,56 @@
+import { isCanvasTextInput } from '@open-pencil/vue'
+import type { EditorCommandId } from '@open-pencil/vue'
+
+import type { EditorStore } from '@/app/editor/active-store'
+import { isInputElement } from '@/app/shell/keyboard/focus'
+
+/**
+ * Commands a focused text field carries out itself. As in VS Code's
+ * `EditorOrNativeTextInputCommand`, `execCommand` is the one API that reaches a field's own
+ * selection and undo history.
+ */
+const TEXT_FIELD_EDITS: Partial<Record<EditorCommandId, 'selectAll' | 'undo' | 'redo'>> = {
+ 'selection.selectAll': 'selectAll',
+ 'edit.undo': 'undo',
+ 'edit.redo': 'redo'
+}
+
+/** A text field in the page has focus; the canvas text editor types through its own textarea. */
+export function textFieldFocused(): boolean {
+ const active = document.activeElement
+ return isInputElement(active) && !isCanvasTextInput(active)
+}
+
+/**
+ * Runs a command against what has keyboard focus when it runs. A focused text field takes the
+ * edits it has its own version of, and commands on the document or selection wait for the
+ * canvas, as keyboard shortcuts do; view commands still run.
+ *
+ * Entry points that keep the person's focus, the native menu, run commands through this. The
+ * command palette and the in-app menu take focus themselves and act on the document.
+ */
+export function runFocusedCommand(
+ store: EditorStore,
+ runCommand: (id: EditorCommandId) => void,
+ id: EditorCommandId
+): void {
+ if (id === 'selection.selectAll' && isCanvasTextInput(document.activeElement)) {
+ store.textEditor?.selectAll()
+ store.requestRender()
+ return
+ }
+ if (textFieldFocused()) {
+ const edit = TEXT_FIELD_EDITS[id]
+ if (edit) document.execCommand(edit)
+ else if (id.startsWith('view.')) runCommand(id)
+ return
+ }
+ runCommand(id)
+}
+
+/** An action on the canvas selection that waits, like the commands above, while a field has focus. */
+export function onCanvasSelection(action: () => void): () => void {
+ return () => {
+ if (!textFieldFocused()) action()
+ }
+}
diff --git a/src/app/shell/menu/editor-actions.ts b/src/app/shell/menu/actions/editor.ts
similarity index 80%
rename from src/app/shell/menu/editor-actions.ts
rename to src/app/shell/menu/actions/editor.ts
index 498275d75..6694166ae 100644
--- a/src/app/shell/menu/editor-actions.ts
+++ b/src/app/shell/menu/actions/editor.ts
@@ -7,6 +7,7 @@ import {
setSnappingPreference
} from '@/app/settings/preferences/apply'
import { appPreferences } from '@/app/settings/preferences/store'
+import { onCanvasSelection } from '@/app/shell/commands/focused'
type TextFormatUpdates = {
fontWeight?: number
@@ -88,14 +89,14 @@ export function createSharedEditorMenuActions(
'theme-light': () => setTheme('light'),
'theme-dark': () => setTheme('dark'),
'theme-auto': () => setTheme('auto'),
- 'text.bold': toggleSelectedTextBold,
- 'text.italic': toggleSelectedTextItalic,
- 'text.underline': toggleSelectedTextUnderline,
- 'arrange.align-left': () => alignSelected('horizontal', 'min'),
- 'arrange.align-center': () => alignSelected('horizontal', 'center'),
- 'arrange.align-right': () => alignSelected('horizontal', 'max'),
- 'arrange.align-top': () => alignSelected('vertical', 'min'),
- 'arrange.align-middle': () => alignSelected('vertical', 'center'),
- 'arrange.align-bottom': () => alignSelected('vertical', 'max')
+ 'text.bold': onCanvasSelection(toggleSelectedTextBold),
+ 'text.italic': onCanvasSelection(toggleSelectedTextItalic),
+ 'text.underline': onCanvasSelection(toggleSelectedTextUnderline),
+ 'arrange.align-left': onCanvasSelection(() => alignSelected('horizontal', 'min')),
+ 'arrange.align-center': onCanvasSelection(() => alignSelected('horizontal', 'center')),
+ 'arrange.align-right': onCanvasSelection(() => alignSelected('horizontal', 'max')),
+ 'arrange.align-top': onCanvasSelection(() => alignSelected('vertical', 'min')),
+ 'arrange.align-middle': onCanvasSelection(() => alignSelected('vertical', 'center')),
+ 'arrange.align-bottom': onCanvasSelection(() => alignSelected('vertical', 'max'))
}
}
diff --git a/src/app/shell/menu/selection-actions.ts b/src/app/shell/menu/actions/selection.ts
similarity index 70%
rename from src/app/shell/menu/selection-actions.ts
rename to src/app/shell/menu/actions/selection.ts
index ccf2e1bcd..03799548a 100644
--- a/src/app/shell/menu/selection-actions.ts
+++ b/src/app/shell/menu/actions/selection.ts
@@ -2,13 +2,14 @@ import type { EditorStore } from '@/app/editor/active-store'
import { pasteClipboardToReplace } from '@/app/editor/clipboard/paste-to-replace'
import { executeClipboardCommand } from '@/app/editor/clipboard/system'
import { requestRenameSelection } from '@/app/editor/selection/rename-dialog'
+import { onCanvasSelection } from '@/app/shell/commands/focused'
export function createSelectionMenuActions(store: EditorStore) {
return {
copy: () => void executeClipboardCommand(store, 'copy'),
cut: () => void executeClipboardCommand(store, 'cut'),
paste: () => void executeClipboardCommand(store, 'paste'),
- 'paste-to-replace': () => void pasteClipboardToReplace(store),
- 'selection.rename': () => requestRenameSelection(store)
+ 'paste-to-replace': onCanvasSelection(() => void pasteClipboardToReplace(store)),
+ 'selection.rename': onCanvasSelection(() => requestRenameSelection(store))
}
}
diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.ts
index 8c583256e..e9ab53432 100644
--- a/src/app/shell/menu/app-menu.ts
+++ b/src/app/shell/menu/app-menu.ts
@@ -30,7 +30,8 @@ import {
setSnappingPreference
} from '@/app/settings/preferences/apply'
import { appPreferences } from '@/app/settings/preferences/store'
-import { createSharedEditorMenuActions } from '@/app/shell/menu/editor-actions'
+import { createSharedEditorMenuActions } from '@/app/shell/menu/actions/editor'
+import { createSelectionMenuActions } from '@/app/shell/menu/actions/selection'
import { openStorageWorkspace } from '@/app/shell/menu/navigation'
import type {
AppMenuActionItem,
@@ -39,7 +40,6 @@ import type {
AppMenuIcon
} from '@/app/shell/menu/schema'
import { APP_MENU_SCHEMA } from '@/app/shell/menu/schema'
-import { createSelectionMenuActions } from '@/app/shell/menu/selection-actions'
import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'
import { openFileDialog } from '@/app/shell/menu/use'
import { useAppTheme } from '@/app/shell/theme'
diff --git a/src/app/shell/menu/editor.ts b/src/app/shell/menu/editor.ts
index 6890b2ca3..12d81a71e 100644
--- a/src/app/shell/menu/editor.ts
+++ b/src/app/shell/menu/editor.ts
@@ -3,12 +3,13 @@ import type { EditorCommandId } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { clearRecentFiles, forgetRecentFile, recentLocalFileAt } from '@/app/recent-files'
-import { createSharedEditorMenuActions } from '@/app/shell/menu/editor-actions'
+import { runFocusedCommand } from '@/app/shell/commands/focused'
+import { createSharedEditorMenuActions } from '@/app/shell/menu/actions/editor'
+import { createSelectionMenuActions } from '@/app/shell/menu/actions/selection'
import { openFileDialog, openFileFromPath } from '@/app/shell/menu/files'
import { useNativeMenuEvents } from '@/app/shell/menu/native-events'
import { OPEN_RECENT_EVENT_PREFIX, watchRecentFilesMenu } from '@/app/shell/menu/recent-files'
import { APP_MENU_SCHEMA, type AppMenuEntry } from '@/app/shell/menu/schema'
-import { createSelectionMenuActions } from '@/app/shell/menu/selection-actions'
import { SHELL_MENU_IDS } from '@/app/shell/menu/shell'
import { useAppTheme } from '@/app/shell/theme'
import { saveDocumentToStorage } from '@/app/storage/workspace/save'
@@ -84,7 +85,7 @@ export function useEditorMenu() {
}
if (SHELL_MENU_IDS.has(id)) return
if (COMMAND_MENU_IDS.has(id as EditorCommandId)) {
- runCommand(id as EditorCommandId)
+ runFocusedCommand(store, runCommand, id as EditorCommandId)
return
}
actions[id]?.()
diff --git a/src/app/tauri/http.ts b/src/app/tauri/http.ts
index f86015aaa..0d430ebc0 100644
--- a/src/app/tauri/http.ts
+++ b/src/app/tauri/http.ts
@@ -1,3 +1,5 @@
+import { randomHex } from '@open-pencil/scene-graph/random'
+
import type { FetchFunction } from '@/app/http/types'
export interface ProxyHttpHeader {
@@ -6,6 +8,8 @@ export interface ProxyHttpHeader {
}
export interface ProxyHttpRequest {
+ /** Chosen here so the request can be cancelled before its head arrives. */
+ id: string
url: string
method?: string
headers?: ProxyHttpHeader[]
@@ -15,18 +19,43 @@ export interface ProxyHttpRequest {
timeout_ms?: number
}
-export interface ProxyHttpResponse {
+/** Status and headers; the body streams over the request's channel. */
+export interface ProxyHttpHead {
status: number
headers: ProxyHttpHeader[]
- body: number[]
url: string
}
+/** `network` marks failures to reach the server or read from it. */
+export interface ProxyHttpError {
+ network: boolean
+ message: string
+}
+
+/** Body chunks arrive as raw bytes, then one of these ends the body. */
+export type ProxyHttpBodyMessage = ArrayBuffer | { done: true } | { error: ProxyHttpError }
+
const NULL_BODY_STATUS_CODES = new Set([204, 205, 304])
-function responseBodyForStatus(response: ProxyHttpResponse): BodyInit | null {
- if (NULL_BODY_STATUS_CODES.has(response.status)) return null
- return Uint8Array.from(response.body)
+function isProxyHttpError(error: unknown): error is ProxyHttpError {
+ return (
+ typeof error === 'object' &&
+ error !== null &&
+ 'network' in error &&
+ 'message' in error &&
+ typeof error.message === 'string'
+ )
+}
+
+/**
+ * Fails the way `fetch` does: a network failure is a `TypeError('fetch failed')` whose cause
+ * names it, which the AI SDK and other callers recognise and retry.
+ */
+function fetchError(error: unknown): Error {
+ if (error instanceof Error) return error
+ if (!isProxyHttpError(error)) return new TypeError('fetch failed', { cause: error })
+ if (error.network) return new TypeError('fetch failed', { cause: new Error(error.message) })
+ return new TypeError(error.message)
}
function headersToProxyHeaders(headers: Headers): ProxyHttpHeader[] {
@@ -115,7 +144,7 @@ async function executeTauriFetch(
const request = new Request(input, init)
request.signal.throwIfAborted()
- const { invoke } = await import('@tauri-apps/api/core')
+ const { Channel, invoke } = await import('@tauri-apps/api/core')
request.signal.throwIfAborted()
// Capture generated multipart headers before consuming the Request body.
@@ -127,7 +156,50 @@ async function executeTauriFetch(
bodyData = new Uint8Array(buffer)
}
+ const id = randomHex()
+ let finished = false
+ const cancel = () => {
+ if (finished) return
+ finished = true
+ request.signal.removeEventListener('abort', onAbort)
+ void invoke('cancel_http_request', { id }).catch(() => undefined)
+ }
+ const finish = () => {
+ finished = true
+ request.signal.removeEventListener('abort', onAbort)
+ }
+
+ // Set by the body stream's start(), which runs synchronously in its constructor.
+ let abortBody: ((reason: Error) => void) | undefined
+ const onBody = new Channel<ProxyHttpBodyMessage>()
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ onBody.onmessage = (message) => {
+ if (finished) return
+ if (message instanceof ArrayBuffer) {
+ controller.enqueue(new Uint8Array(message))
+ } else if ('error' in message) {
+ finish()
+ controller.error(fetchError(message.error))
+ } else {
+ finish()
+ controller.close()
+ }
+ }
+ abortBody = (reason) => {
+ cancel()
+ controller.error(reason)
+ }
+ },
+ cancel
+ })
+ function onAbort() {
+ abortBody?.(abortReason(request.signal))
+ }
+ request.signal.addEventListener('abort', onAbort, { once: true })
+
const payload: ProxyHttpRequest = {
+ id,
url: request.url,
method: request.method,
headers,
@@ -136,15 +208,26 @@ async function executeTauriFetch(
follow_redirects: request.redirect === 'follow',
timeout_ms: timeoutMs
}
- request.signal.throwIfAborted()
- const response = await withAbortSignal(
- invoke<ProxyHttpResponse>('proxy_http_request', { request: payload }),
- request.signal
- )
- const proxiedResponse = new Response(responseBodyForStatus(response), {
- status: response.status,
- headers: response.headers.map(({ name, value }): [string, string] => [name, value])
+ let head: ProxyHttpHead
+ try {
+ head = await withAbortSignal(
+ invoke<ProxyHttpHead>('proxy_http_request', { request: payload, onBody }).catch(
+ (error: unknown) => {
+ throw fetchError(error)
+ }
+ ),
+ request.signal
+ )
+ } catch (error) {
+ if (request.signal.aborted) cancel()
+ else finish()
+ throw error
+ }
+
+ const proxiedResponse = new Response(NULL_BODY_STATUS_CODES.has(head.status) ? null : body, {
+ status: head.status,
+ headers: head.headers.map(({ name, value }): [string, string] => [name, value])
})
- Object.defineProperty(proxiedResponse, 'url', { value: response.url })
+ Object.defineProperty(proxiedResponse, 'url', { value: head.url })
return proxiedResponse
}
diff --git a/src/components/chat/transcript/useScrollFollowing.ts b/src/components/chat/transcript/useScrollFollowing.ts
index efdff2fc3..a85c2130f 100644
--- a/src/components/chat/transcript/useScrollFollowing.ts
+++ b/src/components/chat/transcript/useScrollFollowing.ts
@@ -12,7 +12,9 @@ export function useScrollFollowing(
let userScrolling = false
const { arrivedState, measure } = useScroll(viewport, {
onScroll: () => {
- if (userScrolling) following.value = arrivedState.bottom
+ // Reaching the bottom resumes following however it happened; only the reader leaves it.
+ if (arrivedState.bottom) following.value = true
+ else if (userScrolling) following.value = false
},
onStop: () => {
userScrolling = false
@@ -35,20 +37,50 @@ export function useScrollFollowing(
scheduleFollow()
}
- function beginUserScroll() {
+ /**
+ * Only a gesture away from the bottom stops following; reaching the bottom resumes it. A
+ * gesture that cannot move the viewport changes nothing: downward at the bottom, or upward
+ * while the transcript has nothing above it. No scroll event would follow to undo it.
+ */
+ function leaveBottom() {
+ if (!viewport.value || viewport.value.scrollTop <= 0) return
userScrolling = true
following.value = false
}
- useEventListener(viewport, 'wheel', beginUserScroll, { passive: true })
- useEventListener(viewport, 'touchmove', beginUserScroll, { passive: true })
+ let touchY: number | undefined
+ useEventListener(
+ viewport,
+ 'wheel',
+ (event) => {
+ if (event.deltaY < 0) leaveBottom()
+ },
+ { passive: true }
+ )
+ useEventListener(viewport, 'touchstart', (event) => (touchY = event.touches.item(0)?.clientY), {
+ passive: true
+ })
+ useEventListener(
+ viewport,
+ 'touchmove',
+ (event) => {
+ const y = event.touches.item(0)?.clientY
+ // A finger moving down drags the content down, scrolling toward the top.
+ if (y !== undefined && touchY !== undefined && y > touchY) leaveBottom()
+ touchY = y
+ },
+ { passive: true }
+ )
useEventListener(viewport, 'keydown', (event) => {
- if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', 'Space'].includes(event.code))
- beginUserScroll()
+ if (
+ ['ArrowUp', 'PageUp', 'Home'].includes(event.code) ||
+ (event.code === 'Space' && event.shiftKey)
+ )
+ leaveBottom()
})
// Scrollbar dragging is an explicit navigation gesture; ordinary content clicks are not.
useEventListener(viewport, 'pointerdown', (event) => {
- if (event.target === viewport.value) beginUserScroll()
+ if (event.target === viewport.value) leaveBottom()
})
useEventListener(
content,
diff --git a/tests/e2e/app/focused-commands.webkit.spec.ts b/tests/e2e/app/focused-commands.webkit.spec.ts
new file mode 100644
index 000000000..fa5a7d8f4
--- /dev/null
+++ b/tests/e2e/app/focused-commands.webkit.spec.ts
@@ -0,0 +1,86 @@
+import type { EditorCommandId } from '@open-pencil/vue'
+
+import type { runFocusedCommand } from '@/app/shell/commands/focused'
+
+import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetup()
+
+type FocusedCommands = { runFocusedCommand: typeof runFocusedCommand }
+
+/** Runs a command as the native menu does, and returns the commands that reached the editor. */
+function runAsNativeMenu(id: EditorCommandId): Promise<string[]> {
+ return editor.page.evaluate(async (id) => {
+ const modulePath = '/src/app/shell/commands/focused.ts'
+ const commands: FocusedCommands = await import(modulePath)
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const ran: string[] = []
+ commands.runFocusedCommand(store, (command) => ran.push(command), id)
+ return ran
+ }, id)
+}
+
+async function focusTextField(value: string) {
+ await editor.page.evaluate((value) => {
+ const field = document.createElement('input')
+ field.dataset.testId = 'focused-command-field'
+ field.value = value
+ document.body.append(field)
+ }, value)
+ const field = editor.page.getByTestId('focused-command-field')
+ await field.focus()
+ return field
+}
+
+test.afterEach(async () => {
+ await editor.page.evaluate(() =>
+ document.querySelector('[data-test-id="focused-command-field"]')?.remove()
+ )
+})
+
+test('Select All and Undo from the menu edit a focused text field', async () => {
+ const field = await focusTextField('')
+ await field.pressSequentially('hello world')
+
+ expect(await runAsNativeMenu('selection.selectAll')).toEqual([])
+ expect(
+ await field.evaluate((input: HTMLInputElement) => [input.selectionStart, input.selectionEnd])
+ ).toEqual([0, 11])
+
+ expect(await runAsNativeMenu('edit.undo')).toEqual([])
+ await expect(field).toHaveValue('')
+ expect(await runAsNativeMenu('edit.redo')).toEqual([])
+ await expect(field).toHaveValue('hello world')
+})
+
+test('canvas commands wait while a text field has focus, view commands do not', async () => {
+ await focusTextField('Name')
+
+ expect(await runAsNativeMenu('selection.duplicate')).toEqual([])
+ expect(await runAsNativeMenu('selection.group')).toEqual([])
+ expect(await runAsNativeMenu('view.zoomFit')).toEqual(['view.zoomFit'])
+})
+
+test('menu commands act on the document when the canvas has focus', async () => {
+ await editor.page.locator('canvas').first().focus()
+
+ expect(await runAsNativeMenu('selection.selectAll')).toEqual(['selection.selectAll'])
+ expect(await runAsNativeMenu('edit.undo')).toEqual(['edit.undo'])
+})
+
+test('a page field keeps its edits while a canvas text edit stays open', async () => {
+ await editor.canvas.selectTool('text')
+ await editor.canvas.click(300, 300)
+ await editor.page.keyboard.type('Hi')
+ // In the canvas text editor, Select All selects its text and leaves the document alone.
+ expect(await runAsNativeMenu('selection.selectAll')).toEqual([])
+
+ // Focus leaves for a page field; the text edit stays open behind it.
+ const field = await focusTextField('')
+ await field.pressSequentially('abc')
+
+ expect(await runAsNativeMenu('selection.duplicate')).toEqual([])
+ expect(await runAsNativeMenu('edit.undo')).toEqual([])
+ await expect(field).toHaveValue('')
+})
diff --git a/tests/e2e/chat/responses.spec.ts b/tests/e2e/chat/responses.spec.ts
index dd2b72bfb..ae368dd9c 100644
--- a/tests/e2e/chat/responses.spec.ts
+++ b/tests/e2e/chat/responses.spec.ts
@@ -56,6 +56,62 @@ test('opening a tool call at the bottom keeps it in place instead of following',
}
})
+test('scrolling back to the bottom resumes following new output', async ({
+ configuredChat: chat,
+ page
+}) => {
+ await chat.submit('Paused stream')
+ await expect(chat.assistantMessage()).toContainText('Line 39')
+ const viewport = page
+ .locator('[data-reka-scroll-area-viewport]')
+ .filter({ has: chat.assistantMessage() })
+ const atBottom = () =>
+ viewport.evaluate((element) => {
+ return element.scrollTop + element.clientHeight >= element.scrollHeight - 2
+ })
+ const box = await viewport.boundingBox()
+ if (!box) throw new Error('Expected the transcript to be visible')
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
+
+ await page.mouse.wheel(0, -400)
+ await expect.poll(atBottom).toBe(false)
+ await page.mouse.wheel(0, 100_000)
+ await expect.poll(atBottom).toBe(true)
+ // A further tick at the bottom scrolls nothing and must not stop following.
+ await page.mouse.wheel(0, 200)
+ await page.evaluate(() => window.dispatchEvent(new Event('mock-chat-continue')))
+
+ await expect(chat.assistantMessage()).toContainText('Line 79')
+ await expect.poll(atBottom).toBe(true)
+})
+
+test('scrolling up a reply that fits does not stop following', async ({
+ configuredChat: chat,
+ page
+}) => {
+ await chat.submit('Paused short stream')
+ await expect(chat.assistantMessage()).toContainText('Line 1')
+ const viewport = page
+ .locator('[data-reka-scroll-area-viewport]')
+ .filter({ has: chat.assistantMessage() })
+ const box = await viewport.boundingBox()
+ if (!box) throw new Error('Expected the transcript to be visible')
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
+
+ // Nothing is above the reply yet, so the wheel cannot move the transcript.
+ await page.mouse.wheel(0, -400)
+ await page.evaluate(() => window.dispatchEvent(new Event('mock-chat-continue')))
+
+ await expect(chat.assistantMessage()).toContainText('Line 41')
+ await expect
+ .poll(() =>
+ viewport.evaluate(
+ (element) => element.scrollTop + element.clientHeight >= element.scrollHeight - 2
+ )
+ )
+ .toBe(true)
+})
+
test('authentication errors explain the cause and link to Settings', async ({
configuredChat: chat
}) => {
diff --git a/tests/engine/tauri/http.test.ts b/tests/engine/tauri/http.test.ts
index 2a67d615f..77205ef11 100644
--- a/tests/engine/tauri/http.test.ts
+++ b/tests/engine/tauri/http.test.ts
@@ -1,15 +1,46 @@
import { afterEach, describe, expect, test } from 'bun:test'
+import type { Channel } from '@tauri-apps/api/core'
+
import {
createTauriFetch,
tauriFetch,
- type ProxyHttpRequest,
- type ProxyHttpResponse
+ type ProxyHttpBodyMessage,
+ type ProxyHttpError,
+ type ProxyHttpHead,
+ type ProxyHttpRequest
} from '@/app/tauri/http'
import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'
-type InvokeArgs = { request: ProxyHttpRequest }
+type InvokeArgs = { request: ProxyHttpRequest; onBody: Channel<ProxyHttpBodyMessage> }
+
+function bytes(text: string): ArrayBuffer {
+ const encoded = new TextEncoder().encode(text)
+ const buffer = new ArrayBuffer(encoded.byteLength)
+ new Uint8Array(buffer).set(encoded)
+ return buffer
+}
+
+/** Tauri rejects invoke() with the command's serialized error, not an Error. */
+function desktopError(reason: ProxyHttpError): Promise<never> {
+ const failure = Promise.withResolvers<never>()
+ failure.reject(reason)
+ return failure.promise
+}
+
+/** Answers like the desktop command: the head, then the body over the channel. */
+function respond(
+ args: unknown,
+ head: Partial<ProxyHttpHead> & { status: number },
+ body: ProxyHttpBodyMessage[] = []
+): ProxyHttpHead {
+ const { onBody } = args as InvokeArgs
+ setTimeout(() => {
+ for (const message of [...body, { done: true } as const]) onBody.onmessage(message)
+ })
+ return { headers: [], url: '', ...head }
+}
function proxyBodyText(request: ProxyHttpRequest): string {
return new TextDecoder().decode(new Uint8Array(request.body ?? []))
@@ -70,7 +101,7 @@ describe('tauriFetch', () => {
await mockTauriIPC((command, args) => {
expect(command).toBe('proxy_http_request')
received.push((args as InvokeArgs).request.url)
- return { status: 204, headers: [], body: [] }
+ return respond(args, { status: 204 })
})
const fetcher = createTauriFetch({
nativeFetch: async () => {
@@ -87,11 +118,9 @@ describe('tauriFetch', () => {
await mockTauriIPC((command, args) => {
expect(command).toBe('proxy_http_request')
captured.value = args as InvokeArgs
- return {
- status: 201,
- headers: [{ name: 'x-open-pencil', value: 'ok' }],
- body: [...new TextEncoder().encode('OK')]
- }
+ return respond(args, { status: 201, headers: [{ name: 'x-open-pencil', value: 'ok' }] }, [
+ bytes('OK')
+ ])
})
const response = await createTauriFetch({ timeoutMs: 15_000 })('https://example.test/check', {
@@ -115,7 +144,7 @@ describe('tauriFetch', () => {
await mockTauriIPC((command, args) => {
expect(command).toBe('proxy_http_request')
captured.value = args as InvokeArgs
- return { status: 204, headers: [], body: [] }
+ return respond(args, { status: 204 })
})
await tauriFetch(new URL('https://example.test/url-object'))
if (!captured.value) throw new Error('Expected proxy_http_request to be invoked')
@@ -127,7 +156,7 @@ describe('tauriFetch', () => {
await mockTauriIPC((command, args) => {
expect(command).toBe('proxy_http_request')
captured.value = args as InvokeArgs
- return { status: 204, headers: [], body: [] }
+ return respond(args, { status: 204 })
})
const request = new Request('https://example.test/from-request', {
@@ -144,9 +173,9 @@ describe('tauriFetch', () => {
})
test('constructs null bodies for browser null-body response statuses', async () => {
- await mockTauriIPC((command) => {
+ await mockTauriIPC((command, args) => {
expect(command).toBe('proxy_http_request')
- return { status: 204, headers: [{ name: 'x-no-content', value: '1' }], body: [] }
+ return respond(args, { status: 204, headers: [{ name: 'x-no-content', value: '1' }] })
})
await withBrowserStrictNullBodyResponse(async () => {
@@ -163,7 +192,7 @@ describe('tauriFetch', () => {
await mockTauriIPC((command, args) => {
expect(command).toBe('proxy_http_request')
captured.value = args as InvokeArgs
- return { status: 204, headers: [], body: [] }
+ return respond(args, { status: 204 })
})
const formData = new FormData()
@@ -184,9 +213,9 @@ describe('tauriFetch', () => {
test('rejects already-aborted requests before invoking the desktop command', async () => {
let calls = 0
- await mockTauriIPC(() => {
+ await mockTauriIPC((_command, args) => {
calls += 1
- return { status: 204, headers: [], body: [] }
+ return respond(args, { status: 204 })
})
const controller = new AbortController()
controller.abort()
@@ -197,30 +226,98 @@ describe('tauriFetch', () => {
expect(calls).toBe(0)
})
- test('rejects when an in-flight desktop command is aborted', async () => {
- let calls = 0
- let markStarted: (() => void) | null = null
- let resolvePendingResponse: ((value: ProxyHttpResponse) => void) | null = null
- const started = new Promise<void>((resolve) => {
- markStarted = resolve
- })
- await mockTauriIPC(() => {
- calls += 1
- const resolve = markStarted
- if (!resolve) throw new Error('Expected start resolver to be installed')
- resolve()
- return new Promise<ProxyHttpResponse>((pendingResolve) => {
- resolvePendingResponse = pendingResolve
- })
+ test('cancels the desktop request when aborted before the head arrives', async () => {
+ const cancelled: string[] = []
+ const started = Promise.withResolvers<string>()
+ await mockTauriIPC((command, args) => {
+ if (command === 'cancel_http_request') {
+ cancelled.push((args as { id: string }).id)
+ return null
+ }
+ started.resolve((args as InvokeArgs).request.id)
+ return Promise.withResolvers<never>().promise
})
const controller = new AbortController()
const request = tauriFetch('https://example.test/slow', { signal: controller.signal })
- await started
+ const id = await started.promise
controller.abort()
await expect(request).rejects.toHaveProperty('name', 'AbortError')
- expect(calls).toBe(1)
- expect(resolvePendingResponse).toBeTypeOf('function')
+ expect(cancelled).toEqual([id])
+ })
+
+ test('streams body chunks as they arrive', async () => {
+ const channel = Promise.withResolvers<Channel<ProxyHttpBodyMessage>>()
+ await mockTauriIPC((_command, args) => {
+ channel.resolve((args as InvokeArgs).onBody)
+ return { status: 200, headers: [], url: '' }
+ })
+
+ const response = await tauriFetch('https://example.test/stream')
+ const onBody = await channel.promise
+ const reader = response.body?.getReader()
+ if (!reader) throw new Error('Expected a streamed body')
+
+ onBody.onmessage(bytes('data: 1\n\n'))
+ const first = await reader.read()
+ expect(new TextDecoder().decode(first.value)).toBe('data: 1\n\n')
+
+ onBody.onmessage(bytes('data: 2\n\n'))
+ onBody.onmessage({ done: true })
+ const second = await reader.read()
+ expect(new TextDecoder().decode(second.value)).toBe('data: 2\n\n')
+ expect((await reader.read()).done).toBe(true)
+ })
+
+ test('cancels the desktop request and fails the body when aborted mid-stream', async () => {
+ const cancelled: string[] = []
+ await mockTauriIPC((command, args) => {
+ if (command === 'cancel_http_request') {
+ cancelled.push((args as { id: string }).id)
+ return null
+ }
+ return { status: 200, headers: [], url: '' }
+ })
+ const controller = new AbortController()
+
+ const response = await tauriFetch('https://example.test/stream', { signal: controller.signal })
+ controller.abort()
+
+ await expect(response.text()).rejects.toHaveProperty('name', 'AbortError')
+ expect(cancelled).toHaveLength(1)
+ })
+
+ test('reports network failures as fetch does, so callers can retry', async () => {
+ await mockTauriIPC(() => desktopError({ network: true, message: 'operation timed out' }))
+
+ const error = await tauriFetch('https://example.test/down').catch((reason: unknown) => reason)
+
+ expect(error).toBeInstanceOf(TypeError)
+ expect(error).toHaveProperty('message', 'fetch failed')
+ expect(error).toHaveProperty('cause.message', 'operation timed out')
+ })
+
+ test('reports request errors with their message', async () => {
+ await mockTauriIPC(() =>
+ desktopError({ network: false, message: 'Only HTTP(S) requests are supported' })
+ )
+
+ await expect(tauriFetch('https://example.test/')).rejects.toThrow(
+ 'Only HTTP(S) requests are supported'
+ )
+ })
+
+ test('fails the body when the connection drops mid-stream', async () => {
+ await mockTauriIPC((_command, args) =>
+ respond(args, { status: 200 }, [
+ bytes('partial'),
+ { error: { network: true, message: 'connection reset' } }
+ ])
+ )
+
+ const response = await tauriFetch('https://example.test/stream')
+
+ await expect(response.text()).rejects.toHaveProperty('cause.message', 'connection reset')
})
})
diff --git a/tests/helpers/chat/transport.ts b/tests/helpers/chat/transport.ts
index 8b269de22..ee4f30b17 100644
--- a/tests/helpers/chat/transport.ts
+++ b/tests/helpers/chat/transport.ts
@@ -42,6 +42,43 @@ export async function injectMockChatTransport(page: Page): Promise<void> {
throw new Error('Mock connection dropped')
}
+ // Streams 40 lines (2 for a short one), waits for a `mock-chat-continue` event on window,
+ // then streams 40 more, so a test can scroll while no output arrives.
+ if (normalized.includes('paused stream') || normalized.includes('paused short stream')) {
+ const beforePause = normalized.includes('short') ? 2 : 40
+ return new ReadableStream({
+ start(controller) {
+ controller.enqueue({ type: 'start', messageId })
+ controller.enqueue({ type: 'text-start', id: 'text-1' })
+ let line = 0
+ const streamLines = (until: number, done: () => void) => {
+ const timer = setInterval(() => {
+ controller.enqueue({
+ type: 'text-delta',
+ id: 'text-1',
+ delta: `Line ${line}\n\n`
+ })
+ if (++line < until) return
+ clearInterval(timer)
+ done()
+ }, 20)
+ }
+ streamLines(beforePause, () => {
+ window.addEventListener(
+ 'mock-chat-continue',
+ () =>
+ streamLines(beforePause + 40, () => {
+ controller.enqueue({ type: 'text-end', id: 'text-1' })
+ controller.enqueue({ type: 'finish', finishReason: 'stop' })
+ controller.close()
+ }),
+ { once: true }
+ )
+ })
+ }
+ })
+ }
+
return new ReadableStream({
start(controller) {
controller.enqueue({ type: 'start', messageId })