diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 54c7c3e1..c303dfab 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -855,7 +855,8 @@ fn run_embedded() { eprintln!("[strata] {e}"); Box::::from(e) })?; - open_window(app, port)?; + let shell_token = handle.state::().0.lock().unwrap().clone().unwrap_or_default(); + open_window(app, port, &shell_token)?; Ok(()) }) .on_window_event(|window, event| { @@ -873,13 +874,17 @@ fn run_embedded() { } /// The one window, on the host's own origin so the page and its API share an origin exactly as the browser build does. -fn open_window(app: &tauri::App, port: u16) -> Result<(), Box> { +#[cfg_attr(windows, allow(unused_variables))] +fn open_window(app: &tauri::App, port: u16, shell_token: &str) -> Result<(), Box> { let origin = format!("http://127.0.0.1:{port}"); let url = origin.parse().expect("a valid loopback URL"); - // The shell's own file-drop handler is off: with it on, Windows hands a dropped file to the shell and the page never sees it, so pictures - // could not be dropped on the chat (QA report 1, item 4). With it off the page gets ordinary drag and drop events (apps/host DropZone), the - // same as in a browser, on every system. - let builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url)).title("Strata").inner_size(1440.0, 920.0).min_inner_size(900.0, 600.0).disable_drag_drop_handler(); + let builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url)).title("Strata").inner_size(1440.0, 920.0).min_inner_size(900.0, 600.0); + // Dropping pictures on the chat (QA report 1, item 4). Windows: the shell's own file-drop handler is off, because with it on the system hands + // the dropped file to the shell and the page never sees it; with it off the page gets ordinary drag and drop events (apps/host DropZone), as + // in a browser. Linux and macOS: the page gets the drag events but WebKit gives it no files, so the handler stays on and the shell passes the + // drop on (see drop_script and hand_over_drop below). + #[cfg(windows)] + let builder = builder.disable_drag_drop_handler(); // WebKitGTK (2.50 to 2.52 at least) dereferences a null pointer in AcceleratedBackingStore::update in its UI process when a page calls // document.startViewTransition (the web process asks the UI process to enter accelerated compositing, and the backing store is not // there). The page itself does not call it on that engine (apps/host/src/lib/router.ts), and this line keeps any other script from doing @@ -888,10 +893,64 @@ fn open_window(app: &tauri::App, port: u16) -> Result<(), Box { let _ = target.eval(&drag_script("enter")); } + tauri::DragDropEvent::Leave => { let _ = target.eval(&drag_script("leave")); } + tauri::DragDropEvent::Drop { paths, .. } => { + let _ = target.eval(&drag_script("leave")); + let paths: Vec = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect(); + hand_over_drop(target.clone(), port, token.clone(), paths); + } + _ => {} + } + } + }); + } Ok(()) } +/// The script that tells the page a file drag is over the window (`state` is "enter" or "leave"); the page shows its drop box (apps/host DropZone). +#[cfg_attr(windows, allow(dead_code))] +fn drag_script(state: &str) -> String { + format!("window.dispatchEvent(new CustomEvent('strata:native-drag', {{ detail: '{state}' }}));") +} + +/// The script that tells the page which dropped files the host holds for it (`files_json` is the host's own JSON array of { id, name, type, size }). +#[cfg_attr(windows, allow(dead_code))] +fn drop_script(files_json: &str) -> String { + format!("window.dispatchEvent(new CustomEvent('strata:native-drop', {{ detail: {files_json} }}));") +} + +/// The files of one drop, by path, to the host (which reads them and keeps each for the page to fetch once); then the page is told. +/// Off the window's own thread, so the window never waits for a big picture to be read. +#[cfg(not(windows))] +fn hand_over_drop(window: tauri::WebviewWindow, port: u16, token: String, paths: Vec) { + std::thread::spawn(move || { + let body = serde_json::json!({ "paths": paths }).to_string(); + let answer = http_request_body( + "POST", + &format!("http://127.0.0.1:{port}/api/app/drop"), + &[("x-strata-shutdown", token.as_str()), ("content-type", "application/json")], + Some(&body), + ); + let files = match answer { + Ok((status, text)) if status.contains(" 200") => serde_json::from_str::(&text).ok().and_then(|v| v.get("files").cloned()), + Ok((status, _)) => { eprintln!("[strata] the host did not take the dropped files: {status}"); None } + Err(e) => { eprintln!("[strata] the dropped files could not be handed to the host: {e}"); None } + }; + let json = files.map(|f| f.to_string()).unwrap_or_else(|| "[]".to_string()); + let _ = window.eval(&drop_script(&json)); + }); +} + /// Linux window process: shows the page of the host the shell started and registers the app updater with it. It starts no host and /// stops nothing: when the window closes it just exits, and the shell stops the host. If WebKit crashes this process, only this /// process dies; the shell moves to browser mode. @@ -937,7 +996,7 @@ fn run_window_process() -> ! { eprintln!("[strata] the app updater could not be registered with the host: {e}"); } } - open_window(app, port) + open_window(app, port, &token) }) .on_window_event(|window, event| { if let tauri::WindowEvent::Destroyed = event { @@ -954,6 +1013,15 @@ fn run_window_process() -> ! { mod tests { use super::*; + #[test] + fn the_scripts_the_shell_sends_the_page_for_a_file_drop() { + assert_eq!(drag_script("enter"), "window.dispatchEvent(new CustomEvent('strata:native-drag', { detail: 'enter' }));"); + let files = r#"[{"id":"a","name":"x.png","type":"image/png","size":3}]"#; + let script = drop_script(files); + assert!(script.starts_with("window.dispatchEvent(new CustomEvent('strata:native-drop', { detail: [{")); + assert!(script.contains("x.png") && script.ends_with("}));")); + } + #[test] fn the_window_origin_is_stable_unless_the_port_is_taken() { // free (or already ours from a previous run): the same port every launch, so browser storage survives a restart diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index f9c7b48c..7f9f3e02 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -49,6 +49,7 @@ import { CONTEXT_TOKENS, VARIANTS, localModels, variant } from './catalog.mjs'; import { browseLocalModels, inspectLocalModel } from './local-models.mjs'; import { EventHub, error, json, readBody, readRaw, uid } from './util.mjs'; import { createUploads } from './chat-uploads.mjs'; +import { createNativeDrops } from './native-drop.mjs'; import { createVisionProbe, effectiveVision, readsPicturesByDefault } from './vision-probe.mjs'; import { RequestQueue } from './request-queue.mjs'; import { selectSkills, skillInstructions } from './skill-selection.mjs'; @@ -464,6 +465,7 @@ function loadWorkspaces() { let workspaces = loadWorkspaces(); /* The folder each chat works in ("Select a folder"): the agent's working folder and sandbox for that chat. */ const chatAttachments = createAttachments(); +const nativeDrops = createNativeDrops(); const uploads = createUploads({ dir: join(store.DATA_DIR, 'uploads'), folderOf: chatId => chatFolders.get(chatId) ?? workspaces[0]?.path ?? WORKSPACE, attachments: chatAttachments }); try { uploads.sweep(); } catch { /* best effort */ } const chatFolders = createChatFolders({ file: join(store.DATA_DIR, 'chat-folders.json') }); @@ -1271,6 +1273,18 @@ async function api(req, res, path, method, url) { return; } + // Files dropped on the app window (Linux, macOS): the shell hands over the paths, the page fetches each file once (native-drop.mjs). + if (path === '/api/app/drop' && method === 'POST') { + if (!fromShell()) return error(res, 403, 'Not allowed.'); + try { return json(res, 200, { files: await nativeDrops.add((await readBody(req)).paths) }); } catch (err) { return error(res, 400, err.message); } + } + const dropGet = /^\/api\/app\/drop\/([0-9a-f-]{36})$/.exec(path); + if (dropGet && method === 'GET') { + const file = nativeDrops.take(dropGet[1]); + if (!file) return error(res, 404, 'That file is no longer available. Drop it again.'); + res.writeHead(200, { 'content-type': file.type, 'content-length': file.bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(file.bytes); return undefined; + } + if (path === '/api/setup' && method === 'GET') return json(res, 200, setupState()); if (path === '/api/updates/check' && method === 'GET' && control?.updateCheck) return json(res, 200, await checkComponentUpdates({ control, appUpdater, appVersion: process.env.STRATA_APP_VERSION || null })); if (path === '/api/updates/check' && method === 'GET') return json(res, 200, await checkUpdates({ appVersion:native.state().version??setupState().app.version, engineVersion:native.state().available?(native.state().installed?.engine?.version??null):(await engine.config()).engine.version })); diff --git a/apps/host/server/native-drop.mjs b/apps/host/server/native-drop.mjs new file mode 100644 index 00000000..cb7b9351 --- /dev/null +++ b/apps/host/server/native-drop.mjs @@ -0,0 +1,48 @@ +/** + * Files dropped on the app window (Linux and macOS). + * + * The page cannot read a dragged file there: WebKit gives it the drag events but no files. The app shell sees the drop with the real paths and + * hands them to the host with its shell secret (POST /api/app/drop); the host reads the files and keeps them for a short time under + * unguessable ids; the page asks for each id once (GET /api/app/drop/) and attaches the files as if they had been dropped in a browser. + * Only regular files up to MAX_BYTES, at most MAX_FILES per drop; folders and anything else are skipped. + */ +import { randomUUID } from 'node:crypto'; +import { readFile, stat } from 'node:fs/promises'; +import { basename, extname, isAbsolute } from 'node:path'; + +export const MAX_FILES = 10, MAX_BYTES = 25 * 1024 * 1024, KEEP_MS = 2 * 60_000; + +const TYPES = { + png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', bmp: 'image/bmp', + txt: 'text/plain', md: 'text/markdown', markdown: 'text/markdown', csv: 'text/csv', json: 'application/json', log: 'text/plain', + html: 'text/html', htm: 'text/html', xml: 'text/xml', yaml: 'text/yaml', yml: 'text/yaml', pdf: 'application/pdf', +}; +export const typeOfName = name => TYPES[extname(String(name)).slice(1).toLowerCase()] ?? 'application/octet-stream'; + +export function createNativeDrops({ now = Date.now, read = readFile, info = stat } = {}) { + const held = new Map(); // id -> { name, type, bytes, at } + const sweep = () => { for (const [id, f] of held) if (now() - f.at > KEEP_MS) held.delete(id); }; + return { + /** Read the dropped paths; answer what the page may ask for: [{ id, name, type, size }]. */ + async add(paths) { + sweep(); + const out = []; + for (const raw of (Array.isArray(paths) ? paths : []).slice(0, MAX_FILES)) { + const path = typeof raw === 'string' ? raw : ''; + if (!path || path.includes('\0') || !isAbsolute(path)) continue; + try { + const st = await info(path); + if (!st.isFile() || st.size > MAX_BYTES) continue; + const bytes = await read(path); + const id = randomUUID(); + const name = basename(path); + held.set(id, { name, type: typeOfName(name), bytes, at: now() }); + out.push({ id, name, type: typeOfName(name), size: bytes.length }); + } catch { /* an unreadable file is skipped, the rest still arrive */ } + } + return out; + }, + /** One use per id. */ + take(id) { sweep(); const f = held.get(id); if (f) held.delete(id); return f ?? null; }, + }; +} diff --git a/apps/host/src/components/DropZone.tsx b/apps/host/src/components/DropZone.tsx index 2c8fce5b..c0b1f976 100644 --- a/apps/host/src/components/DropZone.tsx +++ b/apps/host/src/components/DropZone.tsx @@ -1,4 +1,6 @@ -import { useRef, useState, type ReactNode } from 'react'; +import { useEffect, useRef, useState, type ReactNode } from 'react'; +import { NATIVE_DRAG_EVENT, NATIVE_DROP_EVENT, dragHasFiles, fetchDropped, readDroppedRefs } from '../lib/native-drop'; +import { pushToast } from '../lib/store'; import { tr } from '../lib/i18n'; import { Icon } from './ui'; @@ -16,10 +18,32 @@ export function pastedFiles(data: DataTransfer | null | undefined): File[] { } const hasFiles = (e: React.DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes('Files'); +/** A file dropped outside the chat must not take the window to that file: the page ignores it (called once at start). */ +export function installDropGuard() { + const guard = (e: DragEvent) => { if (!e.defaultPrevented && dragHasFiles(e.dataTransfer?.types)) e.preventDefault(); }; + window.addEventListener('dragover', guard); + window.addEventListener('drop', guard); +} + /** The conversation column, with a calm highlight while something is dragged over it. */ export function DropZone({ children, className }: { children: ReactNode; className?: string }) { const [over, setOver] = useState(false); const depth = useRef(0); + // Linux and macOS: the app shell reports the drag and the drop (the page is not given the files there). + useEffect(() => { + const drag = (e: Event) => setOver((e as CustomEvent).detail === 'enter'); + const drop = (e: Event) => { + setOver(false); depth.current = 0; + const refs = readDroppedRefs((e as CustomEvent).detail); + if (!refs.length) return; + void fetchDropped(refs).then(files => { + if (files.length) window.dispatchEvent(new CustomEvent(DROP_EVENT, { detail: files })); + else pushToast('error', tr('The file was not added'), tr('Try dropping it again.')); + }); + }; + window.addEventListener(NATIVE_DRAG_EVENT, drag); window.addEventListener(NATIVE_DROP_EVENT, drop); + return () => { window.removeEventListener(NATIVE_DRAG_EVENT, drag); window.removeEventListener(NATIVE_DROP_EVENT, drop); }; + }, []); return
{ if (!hasFiles(e)) return; e.preventDefault(); depth.current++; setOver(true); }} onDragOver={e => { if (!hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }} diff --git a/apps/host/src/lib/native-drop.ts b/apps/host/src/lib/native-drop.ts new file mode 100644 index 00000000..e85a1ec5 --- /dev/null +++ b/apps/host/src/lib/native-drop.ts @@ -0,0 +1,34 @@ +/** + * Files dropped on the app window on Linux and macOS. The page gets the drag events there but not the files (WebKit hides them), so the app + * shell reads the drop, hands the paths to the host, and tells the page with these two events (apps/desktop/src-tauri/src/main.rs): + * strata:native-drag detail 'enter' | 'leave' the drop box shows or goes away + * strata:native-drop detail [{ id, name, type }] the host holds each file once under its id + */ +export const NATIVE_DRAG_EVENT = 'strata:native-drag'; +export const NATIVE_DROP_EVENT = 'strata:native-drop'; +export interface DroppedRef { id: string; name: string; type: string } + +/** The files the shell announced; anything that is not a well-formed entry is left out. */ +export function readDroppedRefs(detail: unknown): DroppedRef[] { + if (!Array.isArray(detail)) return []; + return detail.flatMap(x => { + const r = x as Record; + return typeof r?.id === 'string' && /^[0-9a-f-]{36}$/.test(r.id) && typeof r.name === 'string' && r.name + ? [{ id: r.id, name: r.name, type: typeof r.type === 'string' ? r.type : 'application/octet-stream' }] : []; + }).slice(0, 10); +} + +/** Fetch each announced file from the host and make it a File, the way a browser drop would have delivered it. A file that cannot be fetched is skipped. */ +export async function fetchDropped(refs: DroppedRef[], fetcher: (url: string) => Promise<{ ok: boolean; blob(): Promise }> = url => fetch(url)): Promise { + const files: File[] = []; + for (const ref of refs) { + try { + const response = await fetcher(`/api/app/drop/${ref.id}`); + if (response.ok) files.push(new File([await response.blob()], ref.name, { type: ref.type })); + } catch { /* skipped */ } + } + return files; +} + +/** True for a drag that carries files, as far as the page can tell (WebKit lists them as text/uri-list, others as Files). */ +export const dragHasFiles = (types: ArrayLike | null | undefined) => Array.from(types ?? []).some(t => t === 'Files' || t === 'text/uri-list'); diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 2319be2a..2778b793 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -3246,5 +3246,7 @@ "s3233": "Er liegt in deinem Downloads-Ordner.", "s3234": "Der Screenshot wurde nicht gespeichert", "s3235": "Versuche es noch einmal oder mache stattdessen einen Screenshot dieses Fensters.", - "s3236": "Das Ordnerfenster hat sich nicht geöffnet. Gib stattdessen den Ordnerpfad ein." + "s3236": "Das Ordnerfenster hat sich nicht geöffnet. Gib stattdessen den Ordnerpfad ein.", + "s3237": "Die Datei wurde nicht hinzugefügt", + "s3238": "Versuche, sie noch einmal abzulegen." } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index 5f569cd3..d699c0dc 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -3246,5 +3246,7 @@ "s3233": "It is in your Downloads folder.", "s3234": "The screenshot was not saved", "s3235": "Try again, or take a screenshot of this window instead.", - "s3236": "The folder window did not open. Type the folder path instead." + "s3236": "The folder window did not open. Type the folder path instead.", + "s3237": "The file was not added", + "s3238": "Try dropping it again." } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index 43f87ae0..f14cafba 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -3246,5 +3246,7 @@ "s3233": "Está en tu carpeta de Descargas.", "s3234": "No se guardó la captura", "s3235": "Inténtalo de nuevo o haz una captura de esta ventana.", - "s3236": "La ventana de carpetas no se abrió. Escribe la ruta de la carpeta." + "s3236": "La ventana de carpetas no se abrió. Escribe la ruta de la carpeta.", + "s3237": "No se añadió el archivo", + "s3238": "Inténtalo de nuevo soltándolo otra vez." } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index 76120838..f5aa833f 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3246,5 +3246,7 @@ "s3233": "ダウンロードフォルダーにあります。", "s3234": "スクリーンショットを保存できませんでした", "s3235": "もう一度試すか、このウィンドウのスクリーンショットを撮ってください。", - "s3236": "フォルダーの画面が開きませんでした。代わりにフォルダーのパスを入力してください。" + "s3236": "フォルダーの画面が開きませんでした。代わりにフォルダーのパスを入力してください。", + "s3237": "ファイルを追加できませんでした", + "s3238": "もう一度ドロップしてみてください。" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index c4460f1d..80d7dcf1 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3246,5 +3246,7 @@ "s3233": "다운로드 폴더에 있습니다.", "s3234": "스크린샷을 저장하지 못했습니다", "s3235": "다시 시도하거나 이 창을 직접 캡처하세요.", - "s3236": "폴더 창이 열리지 않았습니다. 대신 폴더 경로를 입력하세요." + "s3236": "폴더 창이 열리지 않았습니다. 대신 폴더 경로를 입력하세요.", + "s3237": "파일을 추가하지 못했습니다", + "s3238": "다시 끌어다 놓아 보세요." } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 6b144b1e..23816cc6 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -3246,5 +3246,7 @@ "s3233": "Ela está na sua pasta Downloads.", "s3234": "A captura de tela não foi salva", "s3235": "Tente de novo ou tire uma captura desta janela.", - "s3236": "A janela de pastas não abriu. Digite o caminho da pasta." + "s3236": "A janela de pastas não abriu. Digite o caminho da pasta.", + "s3237": "O arquivo não foi adicionado", + "s3238": "Tente soltá-lo de novo." } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index dfb1e7e9..a4188cee 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3246,5 +3246,7 @@ "s3233": "Он находится в папке «Загрузки».", "s3234": "Снимок экрана не сохранён", "s3235": "Попробуйте ещё раз или сделайте снимок этого окна.", - "s3236": "Окно выбора папки не открылось. Введите путь к папке вручную." + "s3236": "Окно выбора папки не открылось. Введите путь к папке вручную.", + "s3237": "Файл не добавлен", + "s3238": "Попробуйте перетащить его ещё раз." } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index f0055fb6..40736978 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3246,5 +3246,7 @@ "s3233": "它在你的“下载”文件夹中。", "s3234": "截图未能保存", "s3235": "请重试,或改为对此窗口截屏。", - "s3236": "文件夹窗口没有打开。请改为输入文件夹路径。" + "s3236": "文件夹窗口没有打开。请改为输入文件夹路径。", + "s3237": "文件未能添加", + "s3238": "请再拖放一次。" } diff --git a/apps/host/src/main.tsx b/apps/host/src/main.tsx index fff41c25..a35e3f83 100644 --- a/apps/host/src/main.tsx +++ b/apps/host/src/main.tsx @@ -4,10 +4,13 @@ import './styles/kit/tokens.css'; import './styles/kit/components.css'; import './styles/app.css'; import { App } from './app/App'; +import { installDropGuard } from './components/DropZone'; const el = document.getElementById('root'); if (!el) throw new Error('#root missing'); +installDropGuard(); + createRoot(el).render( diff --git a/apps/host/tests/split-qa2-drop.test.mjs b/apps/host/tests/split-qa2-drop.test.mjs new file mode 100644 index 00000000..e8c9eb00 --- /dev/null +++ b/apps/host/tests/split-qa2-drop.test.mjs @@ -0,0 +1,84 @@ +// Files dropped on the app window on Linux and macOS: the shell hands the paths to the host, the page fetches each file once. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { mkdtemp, mkdir, rm, writeFile, readFile } from 'node:fs/promises'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { transform } from 'esbuild'; +import { createNativeDrops, typeOfName, MAX_FILES } from '../server/native-drop.mjs'; + +const root = resolve(import.meta.dirname, '..'); +async function loadTs(path) { + const { code } = await transform(await readFile(new URL(path, import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); + return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +} +const { readDroppedRefs, fetchDropped, dragHasFiles } = await loadTs('../src/lib/native-drop.ts'); + +test('the host keeps only regular files it can read, each for one fetch, for a short time', async () => { + const dir = await mkdtemp(join(tmpdir(), 'strata-drop-')); + try { + await writeFile(join(dir, 'a.PNG'), Buffer.from([1, 2, 3])); await writeFile(join(dir, 'notes.md'), '# hi'); await writeFile(join(dir, 'thing.bin'), 'x'); + await mkdir(join(dir, 'folder')); + let clock = 1000; + const drops = createNativeDrops({ now: () => clock }); + const got = await drops.add([join(dir, 'a.PNG'), join(dir, 'folder'), join(dir, 'missing.txt'), 'relative/path.txt', 42, join(dir, 'notes.md'), join(dir, 'thing.bin')]); + assert.deepEqual(got.map(f => [f.name, f.type, f.size]), [['a.PNG', 'image/png', 3], ['notes.md', 'text/markdown', 4], ['thing.bin', 'application/octet-stream', 1]]); + assert.match(got[0].id, /^[0-9a-f-]{36}$/); + assert.deepEqual([...drops.take(got[0].id).bytes], [1, 2, 3]); + assert.equal(drops.take(got[0].id), null, 'one fetch per file'); + clock += 3 * 60_000; + assert.equal(drops.take(got[1].id), null, 'gone after a couple of minutes'); + assert.deepEqual(await drops.add('not a list'), []); + const many = await drops.add(Array.from({ length: 30 }, () => join(dir, 'notes.md'))); + assert.equal(many.length, MAX_FILES); + const big = createNativeDrops({ info: async () => ({ isFile: () => true, size: 26 * 1024 * 1024 }) }); + assert.deepEqual(await big.add([join(dir, 'notes.md')]), [], 'a file over 25 MB is left out'); + assert.equal(typeOfName('x.JPG'), 'image/jpeg'); + } finally { await rm(dir, { recursive: true, force: true, maxRetries: 3 }); } +}); + +test('only the app shell can hand files over; the page fetches each file once', { timeout: 60000 }, async () => { + const home = await mkdtemp(join(tmpdir(), 'strata-drop-host-')); + const socket = createServer(); await new Promise(r => socket.listen(0, '127.0.0.1', r)); + const port = socket.address().port; await new Promise(r => socket.close(r)); + const secret = 'a'.repeat(40); + const child = spawn(process.execPath, ['server/index.mjs'], { cwd: root, env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_REAL_ENGINE: '0', STRATA_WORKSPACE: join(home, 'work'), STRATA_SHUTDOWN_TOKEN: secret }, stdio: 'ignore', windowsHide: true }); + const base = `http://127.0.0.1:${port}`; + try { + for (let i = 0; i < 100; i++) { try { if ((await fetch(base + '/api/skills')).ok) break; } catch { /* not up */ } await new Promise(r => setTimeout(r, 100)); } + const picture = join(home, 'qa.png'); await writeFile(picture, Buffer.from([137, 80, 78, 71])); + const post = (headers) => fetch(base + '/api/app/drop', { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify({ paths: [picture] }) }); + assert.equal((await post({})).status, 403, 'a page cannot hand over paths'); + assert.equal((await post({ 'x-strata-shutdown': 'b'.repeat(40) })).status, 403); + const ok = await post({ 'x-strata-shutdown': secret }); + assert.equal(ok.status, 200); + const [file] = (await ok.json()).files; + assert.deepEqual([file.name, file.type, file.size], ['qa.png', 'image/png', 4]); + const first = await fetch(`${base}/api/app/drop/${file.id}`); + assert.equal(first.status, 200); assert.equal(first.headers.get('content-type'), 'image/png'); + assert.deepEqual([...new Uint8Array(await first.arrayBuffer())], [137, 80, 78, 71]); + assert.equal((await fetch(`${base}/api/app/drop/${file.id}`)).status, 404, 'once'); + assert.equal((await fetch(`${base}/api/app/drop/not-an-id`)).status, 404); + } finally { child.kill(); await new Promise(r => setTimeout(r, 300)); await rm(home, { recursive: true, force: true, maxRetries: 3 }).catch(() => {}); } +}); + +test('the page reads what the shell announced and makes Files of it', async () => { + const id = '123e4567-e89b-12d3-a456-426614174000'; + assert.deepEqual(readDroppedRefs([{ id, name: 'a.png', type: 'image/png', size: 3 }, { id: 'bad', name: 'x' }, { id, name: '' }, null, 7]), [{ id, name: 'a.png', type: 'image/png' }]); + assert.deepEqual(readDroppedRefs('nope'), []); + const files = await fetchDropped([{ id, name: 'a.png', type: 'image/png' }, { id: id.replace('0', '1'), name: 'gone.png', type: 'image/png' }], + async url => url.endsWith(id) ? { ok: true, blob: async () => new Blob([new Uint8Array([1, 2])]) } : { ok: false, blob: async () => new Blob([]) }); + assert.deepEqual(files.map(f => [f.name, f.type, f.size]), [['a.png', 'image/png', 2]]); + assert.equal(dragHasFiles(['text/uri-list', 'text/html']), true); assert.equal(dragHasFiles(['Files']), true); assert.equal(dragHasFiles(['text/plain']), false); assert.equal(dragHasFiles(null), false); +}); + +test('the window passes the drop on (Linux and macOS) and ignores a file dropped outside the chat', async () => { + const rust = await readFile(new URL('../../desktop/src-tauri/src/main.rs', import.meta.url), 'utf8'); + assert.match(rust, /#\[cfg\(windows\)\]\s+let builder = builder\.disable_drag_drop_handler\(\);/); + assert.match(rust, /window\.on_webview_event\(/); assert.match(rust, /\/api\/app\/drop/); + const zone = await readFile(new URL('../src/components/DropZone.tsx', import.meta.url), 'utf8'); + assert.match(zone, /NATIVE_DROP_EVENT/); assert.match(zone, /export function installDropGuard/); + assert.match(await readFile(new URL('../src/main.tsx', import.meta.url), 'utf8'), /installDropGuard\(\);/); +}); diff --git a/apps/host/tests/split-qa2-fields.test.mjs b/apps/host/tests/split-qa2-fields.test.mjs index 52735d95..7fb615bc 100644 --- a/apps/host/tests/split-qa2-fields.test.mjs +++ b/apps/host/tests/split-qa2-fields.test.mjs @@ -68,7 +68,7 @@ test('O02: the screenshot Download button saves the picture and then says so', a test('item 1: the desktop window leaves file drops to the page, and the drop box is animated', async () => { const rust = await readFile(new URL('../../desktop/src-tauri/src/main.rs', import.meta.url), 'utf8'); - assert.match(rust, /\.min_inner_size\(900\.0, 600\.0\)\.disable_drag_drop_handler\(\);/); + assert.match(rust, /#\[cfg\(windows\)\]\s+let builder = builder\.disable_drag_drop_handler\(\);/); const css = await readFile(new URL('../src/styles/app.css', import.meta.url), 'utf8'); assert.match(css, /\.dropzone \{ animation: dropzone-in/); assert.match(css, /prefers-reduced-motion: reduce\) \{ \.dropzone/);