Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Browser: intercept the page's own file picker in the live view (#578)

Oleksandr Ivanchenko2221e4cd3c2c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e3a5df0c..c04328d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
+### Fixed
+- In the live browser view, a page's own file picker (TikTok Studio's "Select video", for one) now opens kwant's own **Choose file…** sheet instead of doing nothing, since the screencast can't show Chrome's native dialog. Choose a file, watch it upload, and the page gets it as if you'd picked it yourself.
+- The page's own file picker: dropping a file onto the sheet, a focused OK when the page itself closed the picker, a Cancel while uploading, a byte-count progress bar, and a failed answer (not just a lost picker) can now be retried instead of always going "gone". (#578)
+
## [Mac 0.9.7] - 2026-11-13
kwant 0.9.7: your bot itself at work while a reply is coming, a mark on each bot's avatar for the AI it runs on and one search box to find a tool and add it.
diff --git a/frontend/src/browserInput.ts b/frontend/src/browserInput.ts
index b5503b3e..e61e3e8d 100644
--- a/frontend/src/browserInput.ts
+++ b/frontend/src/browserInput.ts
@@ -393,6 +393,20 @@ export interface PageDialog {
default_prompt: string;
}
+/** The page's own file picker, intercepted instead of Chrome drawing it natively. */
+export interface FileChooserRequest {
+ /** The server's own per-connection counter, not the client's action-correlation id. */
+ id: number;
+ accept: string;
+ multiple: boolean;
+}
+
+/** A `file_chooser_error`: `too_big`, `gone` or `failed` (the brief's codes); `error` is ready to show. */
+export interface FileChooserFailure {
+ code: string;
+ error: string;
+}
+
export function parseSelect(m: unknown): SelectRequest | null {
const v = m as Record<string, unknown> | null;
if (!v || !Array.isArray(v.options)) return null;
@@ -416,6 +430,50 @@ export function parseDialog(m: unknown): PageDialog | null {
return { kind, message: String(v.message ?? ''), default_prompt: String(v.default_prompt ?? '') };
}
+export function parseFileChooser(m: unknown): FileChooserRequest | null {
+ const v = m as Record<string, unknown> | null;
+ const id = typeof v?.id === 'number' && Number.isFinite(v.id) ? v.id : NaN;
+ if (!Number.isFinite(id)) return null;
+ return { id, accept: typeof v?.accept === 'string' ? v.accept : '', multiple: v?.multiple === true };
+}
+
+export function parseFileChooserFailure(m: unknown): FileChooserFailure | null {
+ const v = m as Record<string, unknown> | null;
+ if (typeof v?.id !== 'number') return null;
+ return { code: typeof v.code === 'string' ? v.code : 'failed', error: typeof v.error === 'string' ? v.error : FILE_CHOOSER_FAILED_TEXT };
+}
+
+/** The one text shown for any server-side file-chooser failure that isn't `too_big` or `gone`. */
+export const FILE_CHOOSER_FAILED_TEXT = 'Couldn’t send that file to the page.';
+
+const CHOOSER_VIDEO_EXT = /\.(mp4|mov|m4v|webm|avi|mkv)$/i;
+const CHOOSER_IMAGE_EXT = /\.(jpg|jpeg|png|gif|webp|heic|avif)$/i;
+const isVideoToken = (t: string) => /^video\//i.test(t) || CHOOSER_VIDEO_EXT.test(t);
+const isImageToken = (t: string) => /^image\//i.test(t) || CHOOSER_IMAGE_EXT.test(t);
+
+/** Which kind an `accept` string names, by the rule `fileChooserTitle` and the drop handler share: every comma-separated token must agree, or it's `'file'`. */
+export function acceptKind(accept: string): 'video' | 'image' | 'file' {
+ const tokens = accept.split(',').map((t) => t.trim()).filter(Boolean);
+ if (tokens.length > 0 && tokens.every(isVideoToken)) return 'video';
+ if (tokens.length > 0 && tokens.every(isImageToken)) return 'image';
+ return 'file';
+}
+
+/** Does a dropped file match what this chooser's `accept` asks for (by mime type, or the name's extension when there's no mime)? `'file'` takes anything. */
+export function fileMatchesAccept(file: { type?: string; name: string }, kind: 'video' | 'image' | 'file'): boolean {
+ if (kind === 'file') return true;
+ const test = kind === 'video' ? isVideoToken : isImageToken;
+ return test(file.type || '') || test(file.name);
+}
+
+/** The sheet's title, from the input's own `accept` (every comma-separated token must agree on a kind, so `image/*,video/*` falls back to "file"). */
+export function fileChooserTitle(accept: string, multiple = false): string {
+ const kind = acceptKind(accept);
+ if (kind === 'video') return multiple ? 'Choose videos' : 'Choose a video';
+ if (kind === 'image') return multiple ? 'Choose photos' : 'Choose a photo';
+ return multiple ? 'Choose files' : 'Choose a file';
+}
+
/** Type-ahead: the first enabled option after `from` (wrapping) whose label starts with `typed`. */
export function matchOption(options: SelectOption[], typed: string, from: number): number {
const q = typed.toLocaleLowerCase();
diff --git a/frontend/src/components/BrowserControlOverlay.tsx b/frontend/src/components/BrowserControlOverlay.tsx
index eab5d600..bbaf22a9 100644
--- a/frontend/src/components/BrowserControlOverlay.tsx
+++ b/frontend/src/components/BrowserControlOverlay.tsx
@@ -20,7 +20,7 @@ import { resizeFor } from '../browserInput';
import { domainOf } from '../humanSteps';
import { haptic } from '../haptics';
import type { BrowserStream } from '../useBrowserStream';
-import { PageDialogModal, SelectPopover } from './BrowserPopups';
+import { FileChooserModal, FileChooserToast, PageDialogModal, SelectPopover } from './BrowserPopups';
/** Sends one gesture to the page: presses, releases, taps and text wait for an ack, moves don't. */
export function sendPageInput(send: (payload: Record<string, unknown>, input?: boolean) => void, input: PageInput) {
@@ -281,8 +281,11 @@ export interface BrowserControlOverlayProps {
onHandBack: () => void;
/** The page's viewport size in CSS px (1280×800 unless the desktop stage resized it). */
page?: Size;
- /** For the page's own <select> lists and alert/confirm/prompt, which the screencast can't show. */
- stream?: Pick<BrowserStream, 'select' | 'dialog' | 'clearSelect' | 'clearDialog'>;
+ /** For the page's own <select> lists, alert/confirm/prompt and file picker, which the screencast can't show. */
+ stream?: Pick<
+ BrowserStream,
+ 'select' | 'dialog' | 'clearSelect' | 'clearDialog' | 'fileChooser' | 'fileChooserError' | 'fileChooserDone' | 'answerFileChooser' | 'cancelFileChooser' | 'clearFileChooserError' | 'clearFileChooserDone'
+ >;
/** An open sign-in, code or other step for this browser: its Done sits on the status line. */
step?: { need: string; doneLabel: string; onDone: () => Promise<string | void> | void } | null;
/** The person controls the page (or a human step lets their input through): size it to the stage. */
@@ -574,6 +577,26 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
/>
</div>
)}
+ {stream?.fileChooser && (
+ <div className="absolute inset-x-0 bottom-0 z-50" style={{ top: barHeight }} data-dialog-area>
+ <FileChooserModal
+ key={stream.fileChooser.id}
+ request={stream.fileChooser}
+ failure={stream.fileChooserError}
+ onAnswer={(attachmentIds) => stream.answerFileChooser(stream.fileChooser!.id, attachmentIds)}
+ onCancel={() => stream.cancelFileChooser(stream.fileChooser!.id)}
+ onClearFailure={stream.clearFileChooserError}
+ compact
+ />
+ </div>
+ )}
+ {stream && !stream.fileChooser && stream.fileChooserDone && (
+ <FileChooserToast
+ names={stream.fileChooserDone.names}
+ onDone={stream.clearFileChooserDone}
+ style={{ top: barHeight + 12 }}
+ />
+ )}
<div className="shrink-0" style={{ height: 'env(safe-area-inset-bottom)' }} />
diff --git a/frontend/src/components/BrowserPopups.tsx b/frontend/src/components/BrowserPopups.tsx
index b2a536dd..60894843 100644
--- a/frontend/src/components/BrowserPopups.tsx
+++ b/frontend/src/components/BrowserPopups.tsx
@@ -1,6 +1,21 @@
import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
import { Check, Globe } from 'lucide-react';
-import { PageDialog, Rect, SelectRequest, Size, matchOption, nextEnabled, popoverPlacement } from '../browserInput';
+import {
+ FILE_CHOOSER_FAILED_TEXT,
+ FileChooserFailure,
+ FileChooserRequest,
+ PageDialog,
+ Rect,
+ SelectRequest,
+ Size,
+ acceptKind,
+ fileChooserTitle,
+ fileMatchesAccept,
+ matchOption,
+ nextEnabled,
+ popoverPlacement,
+} from '../browserInput';
+import { filesFrom, preflightFile, uploadProgressText, uploadWithRetry } from '../attachments';
const PAGE_STEP = 8;
const TYPEAHEAD_MS = 500;
@@ -316,3 +331,268 @@ export function PageDialogModal({ dialog, host, onAnswer, compact = false }: { d
</div>
);
}
+
+type ChooserPhase = 'picking' | 'uploading' | 'sending';
+
+/**
+ * The page's own file picker, intercepted instead of Chrome drawing it natively (the screencast
+ * can't show it either). Modeled on `PageDialogModal` — not anchored to any on-page rect, so it's
+ * a centered card the same way. `failure` is the server's `file_chooser_error` for this chooser
+ * (already filtered by id in `useBrowserStream`); a client-side preflight/upload failure is kept
+ * local instead, since the server never sees it.
+ */
+export function FileChooserModal({
+ request,
+ failure,
+ onAnswer,
+ onCancel,
+ onClearFailure,
+ compact = false,
+}: {
+ request: FileChooserRequest;
+ failure: FileChooserFailure | null;
+ onAnswer: (attachmentIds: string[]) => void;
+ onCancel: () => void;
+ onClearFailure: () => void;
+ /** Phone: the page area is short, so the card sits 16 px down, not 96 */
+ compact?: boolean;
+}) {
+ const [phase, setPhase] = useState<ChooserPhase>('picking');
+ const [name, setName] = useState('');
+ const [size, setSize] = useState(0);
+ const [progress, setProgress] = useState(0);
+ const [localError, setLocalError] = useState<string | null>(null);
+ const [dragging, setDragging] = useState(false);
+ const dragDepth = useRef(0);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const chooseRef = useRef<HTMLButtonElement>(null);
+ const tryAgainRef = useRef<HTMLButtonElement>(null);
+ const okRef = useRef<HTMLButtonElement>(null);
+ const cancelUploadRef = useRef<HTMLButtonElement>(null);
+ const cardRef = useRef<HTMLDivElement>(null);
+ const abortRef = useRef<AbortController | null>(null);
+ const titleId = useId();
+
+ const error = failure?.error ?? localError;
+ const gone = failure?.code === 'gone';
+ const kind = acceptKind(request.accept);
+ const button = 'h-8 [@media(pointer:coarse)]:h-11 px-3 rounded-[10px] text-[13px] max-sm:flex-1';
+
+ useLayoutEffect(() => {
+ if (error) (gone ? okRef : tryAgainRef).current?.focus({ preventScroll: true });
+ else if (phase === 'picking') chooseRef.current?.focus({ preventScroll: true });
+ else if (phase === 'uploading') cancelUploadRef.current?.focus({ preventScroll: true });
+ else cardRef.current?.focus({ preventScroll: true });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [phase, error === null, gone]);
+ useEffect(() => () => abortRef.current?.abort(), []);
+
+ const pick = async (files: File[]) => {
+ const list = files.slice(0, request.multiple ? undefined : 1);
+ if (list.length === 0) return;
+ if (kind !== 'file' && !list.every((f) => fileMatchesAccept(f, kind))) {
+ setLocalError(`This page asks for ${kind === 'video' ? 'a video.' : 'a photo.'}`);
+ return;
+ }
+ for (const f of list) {
+ const problem = preflightFile(f);
+ if (problem) {
+ setLocalError(problem);
+ return;
+ }
+ }
+ setLocalError(null);
+ setPhase('uploading');
+ const controller = new AbortController();
+ abortRef.current = controller;
+ const ids: string[] = [];
+ try {
+ for (let i = 0; i < list.length; i++) {
+ setName(list.length > 1 ? `${list[i].name} (${i + 1} of ${list.length})` : list[i].name);
+ setSize(list[i].size);
+ setProgress(0);
+ const attachment = await uploadWithRetry(list[i], setProgress, controller.signal);
+ ids.push(attachment.id);
+ }
+ setPhase('sending');
+ onAnswer(ids);
+ } catch (err) {
+ if (err instanceof DOMException && err.name === 'AbortError') return;
+ setLocalError(err instanceof Error ? err.message : FILE_CHOOSER_FAILED_TEXT);
+ setPhase('picking');
+ }
+ };
+
+ const retry = () => {
+ abortRef.current?.abort();
+ setLocalError(null);
+ setPhase('picking');
+ if (failure) onClearFailure();
+ };
+
+ const cancelUpload = () => {
+ abortRef.current?.abort();
+ onCancel();
+ };
+
+ const onDrop: React.DragEventHandler = (e) => {
+ e.preventDefault();
+ dragDepth.current = 0;
+ setDragging(false);
+ if (phase !== 'picking') return;
+ void pick(filesFrom(e.dataTransfer?.files ?? null));
+ };
+
+ return (
+ <div
+ className={`absolute inset-0 z-50 flex justify-center items-start px-4 sm:px-0 ${compact ? 'pt-4' : 'pt-24'} bg-[rgb(10_7_25/0.6)]`}
+ data-browser-popup
+ onPointerDown={(e) => e.stopPropagation()}
+ onMouseDown={(e) => e.stopPropagation()}
+ onWheel={(e) => e.stopPropagation()}
+ onDragOver={(e) => e.preventDefault()}
+ onDragEnter={(e) => {
+ e.preventDefault();
+ dragDepth.current += 1;
+ if (phase === 'picking') setDragging(true);
+ }}
+ onDragLeave={(e) => {
+ e.preventDefault();
+ dragDepth.current = Math.max(0, dragDepth.current - 1);
+ if (dragDepth.current === 0) setDragging(false);
+ }}
+ onDrop={onDrop}
+ >
+ <div
+ ref={cardRef}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={titleId}
+ tabIndex={-1}
+ data-escape-layer
+ data-file-chooser
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === 'Escape' && phase !== 'sending') {
+ e.preventDefault();
+ onCancel();
+ }
+ }}
+ className={`w-full sm:w-[420px] rounded-[14px] border p-4 shadow-[0_24px_64px_rgb(0_0_0/0.55)] text-zinc-100 kw-pop-in focus:outline-none ${
+ dragging ? 'border-[#9d8fff] bg-[#201a44]' : 'border-white/[0.14] bg-[#1a1538]'
+ }`}
+ >
+ <p id={titleId} className="text-[15px] font-semibold text-zinc-100">
+ {fileChooserTitle(request.accept, request.multiple)}
+ </p>
+ {!error && phase === 'picking' && (
+ <p className="mt-1 text-[13px] text-zinc-400">
+ From this device<span className="[@media(pointer:coarse)]:hidden">, or drop it here</span>.{' '}
+ {kind === 'video' ? 'Up to 100 MB.' : 'Up to 20 MB (videos 100 MB).'}
+ </p>
+ )}
+
+ {error ? (
+ gone ? (
+ <>
+ <p role="alert" className="mt-3 text-sm text-rose-300">
+ The page moved on and closed its file picker. Click its upload button again if you still need it.
+ </p>
+ <div className="mt-4 flex items-center justify-end">
+ <button ref={okRef} type="button" onClick={onCancel} className={`${button} ${PRIMARY_BUTTON}`}>
+ OK
+ </button>
+ </div>
+ </>
+ ) : (
+ <>
+ <p role="alert" className="mt-3 text-sm text-rose-300">
+ {error}
+ </p>
+ <div className="mt-4 flex flex-wrap items-center gap-2">
+ <button type="button" onClick={onCancel} className={`${button} ${GHOST_BUTTON}`}>
+ Cancel
+ </button>
+ <button ref={tryAgainRef} type="button" onClick={retry} className={`${button} ${PRIMARY_BUTTON}`}>
+ Try again
+ </button>
+ </div>
+ </>
+ )
+ ) : phase === 'picking' ? (
+ <div className="mt-4 flex flex-wrap items-center gap-2">
+ <input
+ ref={inputRef}
+ type="file"
+ accept={request.accept || undefined}
+ multiple={request.multiple}
+ className="sr-only"
+ tabIndex={-1}
+ onChange={(e) => {
+ void pick(Array.from(e.target.files ?? []));
+ e.target.value = '';
+ }}
+ />
+ <button type="button" onClick={onCancel} className={`${button} ${GHOST_BUTTON}`}>
+ Cancel
+ </button>
+ <button ref={chooseRef} type="button" onClick={() => inputRef.current?.click()} className={`${button} ${PRIMARY_BUTTON}`}>
+ Choose file…
+ </button>
+ </div>
+ ) : (
+ <div className="mt-4" aria-live="polite">
+ <p className="text-sm text-zinc-300 truncate">{phase === 'sending' ? 'Sending to the page…' : name}</p>
+ <div
+ role="progressbar"
+ aria-label={phase === 'sending' ? 'Sending to the page' : 'Uploading'}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round((phase === 'sending' ? 1 : progress) * 100)}
+ className="mt-2 h-1.5 rounded-full bg-[#2c2552] overflow-hidden"
+ >
+ <div
+ className="h-full w-full origin-left bg-[#6c58e0] transition-transform duration-150 ease-out motion-reduce:transition-none"
+ style={{ transform: `scaleX(${phase === 'sending' ? 1 : progress})` }}
+ />
+ </div>
+ {phase === 'uploading' && (
+ <div className="mt-1 flex items-center justify-between">
+ <span className="text-xs text-zinc-400">{uploadProgressText(progress, size)}</span>
+ <button ref={cancelUploadRef} type="button" onClick={cancelUpload} className={`h-7 px-2.5 rounded-[8px] text-[12px] ${GHOST_BUTTON}`}>
+ Cancel
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * "Added {name}", shown once the page has the file; same spot the select/dialog sheets land.
+ * `style` lets a phone-sized host move it below its own status bar (`top-3` would sit under it);
+ * the desktop takeover stage, with no such bar, leaves it unset and gets the default `top-3`.
+ */
+export function FileChooserToast({ names, onDone, style }: { names: string[]; onDone: () => void; style?: React.CSSProperties }) {
+ useEffect(() => {
+ const t = setTimeout(onDone, 4000);
+ return () => clearTimeout(t);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ const text = names.length === 0 ? 'Added' : names.length === 1 ? `Added ${names[0]}` : `Added ${names.length} files`;
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ data-browser-popup
+ title={text}
+ style={style}
+ className={`absolute left-1/2 z-50 max-w-[calc(100%-24px)] truncate -translate-x-1/2 rounded-[10px] border border-[rgb(94_234_212/0.2)] bg-[#1a1538] px-3 py-1.5 text-xs text-[#5eead4] shadow-[0_12px_32px_rgb(0_0_0/0.45)] kw-pop-in ${style ? '' : 'top-3'}`}
+ >
+ {text}
+ </div>
+ );
+}
diff --git a/frontend/src/components/BrowserTakeoverStage.tsx b/frontend/src/components/BrowserTakeoverStage.tsx
index ef2c968c..95fd008c 100644
--- a/frontend/src/components/BrowserTakeoverStage.tsx
+++ b/frontend/src/components/BrowserTakeoverStage.tsx
@@ -20,7 +20,7 @@ import { PageInput, Pt, createGestureTracker } from '../browserGestures';
import { domainOf } from '../humanSteps';
import type { BrowserStream } from '../useBrowserStream';
import { BOT_BUSY_TEXT } from '../useBrowserStream';
-import { GHOST_BUTTON, PRIMARY_BUTTON, PageDialogModal, SelectPopover } from './BrowserPopups';
+import { FileChooserModal, FileChooserToast, GHOST_BUTTON, PRIMARY_BUTTON, PageDialogModal, SelectPopover } from './BrowserPopups';
import { ModernAvatar } from './ModernAvatar';
import { sendPageInput } from './BrowserControlOverlay';
@@ -216,7 +216,7 @@ export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botN
const wheel = useMemo(() => createWheelCoalescer(raf, (m) => sendRef.current({ ...m })), [raf]);
const keyboard = useMemo(() => createKeyboard(mac, (m) => sendRef.current(m as unknown as Record<string, unknown>)), [mac]);
- const popupOpen = !!stream.select || !!stream.dialog;
+ const popupOpen = !!stream.select || !!stream.dialog || !!stream.fileChooser;
const popupRef = useRef(popupOpen);
popupRef.current = popupOpen;
@@ -777,6 +777,20 @@ export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botN
}}
/>
)}
+ {stream.fileChooser && (
+ <FileChooserModal
+ key={stream.fileChooser.id}
+ request={stream.fileChooser}
+ failure={stream.fileChooserError}
+ onAnswer={(attachmentIds) => stream.answerFileChooser(stream.fileChooser!.id, attachmentIds)}
+ onCancel={() => {
+ stream.cancelFileChooser(stream.fileChooser!.id);
+ focusPage();
+ }}
+ onClearFailure={stream.clearFileChooserError}
+ />
+ )}
+ {!stream.fileChooser && stream.fileChooserDone && <FileChooserToast names={stream.fileChooserDone.names} onDone={stream.clearFileChooserDone} />}
<textarea
ref={sinkRef}
diff --git a/frontend/src/useBrowserStream.ts b/frontend/src/useBrowserStream.ts
index a9a133d0..b7b6b873 100644
--- a/frontend/src/useBrowserStream.ts
+++ b/frontend/src/useBrowserStream.ts
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { browserStreamUrl } from './browserViewport';
-import { PageDialog, SelectRequest, Size, parseDialog, parseSelect, streamErrorText } from './browserInput';
+import { FileChooserFailure, FileChooserRequest, PageDialog, SelectRequest, Size, parseDialog, parseFileChooser, parseFileChooserFailure, parseSelect, streamErrorText } from './browserInput';
import { onRecordingFrame } from './showOnce';
import { POINT_TIMEOUT_MS, PointError, pointErrorCode } from './point';
@@ -50,6 +50,11 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
const [viewport, setViewport] = useState<Size | null>(null);
const [select, setSelect] = useState<SelectRequest | null>(null);
const [dialog, setDialog] = useState<PageDialog | null>(null);
+ // The page's own file picker; a ref too, since ws.onmessage is set up once and never sees fresh state
+ const [fileChooser, setFileChooser] = useState<FileChooserRequest | null>(null);
+ const fileChooserRef = useRef<FileChooserRequest | null>(null);
+ const [fileChooserError, setFileChooserError] = useState<FileChooserFailure | null>(null);
+ const [fileChooserDone, setFileChooserDone] = useState<{ names: string[] } | null>(null);
const [cursor, setCursor] = useState<string>('default');
// The last resize was answered `ignored`: the page follows a real window and keeps its size
const [resizeIgnored, setResizeIgnored] = useState(false);
@@ -68,6 +73,12 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
}
waiters.current.clear();
};
+ const resetFileChooser = () => {
+ fileChooserRef.current = null;
+ setFileChooser(null);
+ setFileChooserError(null);
+ setFileChooserDone(null);
+ };
useEffect(() => {
if (!id || id === 'default' || !visible) return;
@@ -122,11 +133,33 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
takingControl.current = false;
setControlling(!!message.active);
if (message.viewport && message.viewport.width > 0) setViewport({ width: message.viewport.width, height: message.viewport.height });
- if (!message.active) { setSelect(null); setDialog(null); setCursor('default'); }
+ if (!message.active) { setSelect(null); setDialog(null); setCursor('default'); resetFileChooser(); }
break;
case 'select': setSelect(parseSelect(message)); break;
case 'dialog': setDialog(parseDialog(message)); break;
case 'dialog_closed': setDialog(null); break;
+ case 'file_chooser': {
+ const parsed = parseFileChooser(message);
+ if (parsed) {
+ fileChooserRef.current = parsed;
+ setFileChooser(parsed);
+ setFileChooserError(null);
+ setFileChooserDone(null);
+ }
+ break;
+ }
+ case 'file_chooser_done':
+ if (typeof message.id === 'number' && fileChooserRef.current?.id === message.id) {
+ fileChooserRef.current = null;
+ setFileChooser(null);
+ }
+ setFileChooserDone({ names: Array.isArray(message.names) ? message.names.filter((n: unknown) => typeof n === 'string') : [] });
+ break;
+ case 'file_chooser_error':
+ if (typeof message.id === 'number' && fileChooserRef.current?.id === message.id) {
+ setFileChooserError(parseFileChooserFailure(message));
+ }
+ break;
case 'cursor': if (typeof message.cursor === 'string') setCursor(message.cursor); break;
case 'clipboard':
if (typeof message.text === 'string' && message.text) navigator.clipboard?.writeText(message.text).catch(() => {});
@@ -172,6 +205,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
lastImage.current = null;
setSelect(null);
setDialog(null);
+ resetFileChooser();
setResizeIgnored(false);
setError((current) => current || 'Browser disconnected. Reconnecting…');
reconnect = setTimeout(connect, Math.min(1000 * 2 ** attempts++, 10000));
@@ -196,6 +230,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
setTapFocus(null);
setSelect(null);
setDialog(null);
+ resetFileChooser();
setViewport(null);
setResizeIgnored(false);
};
@@ -260,11 +295,33 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?
const clearDialog = useCallback(() => setDialog(null), []);
const clearError = useCallback(() => setError(null), []);
+ /**
+ * Answers the open file chooser with already-uploaded attachment ids. Its `id` is the server's
+ * own chooser id, not `sequence.current` — `send()` would stomp on it, so this talks to the
+ * socket directly, the same way `acknowledgeFrame` and `restoreViewport` do.
+ */
+ const answerFileChooser = useCallback((chooserId: number, attachmentIds: string[]) => {
+ const ws = socket.current;
+ if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ action: 'file_chooser', id: chooserId, attachment_ids: attachmentIds }));
+ }, []);
+
+ /** No reply is expected for a cancel, so the sheet closes right away. */
+ const cancelFileChooser = useCallback((chooserId: number) => {
+ const ws = socket.current;
+ if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ action: 'file_chooser', id: chooserId, cancel: true }));
+ if (fileChooserRef.current?.id === chooserId) resetFileChooser();
+ }, []);
+
+ const clearFileChooserError = useCallback(() => setFileChooserError(null), []);
+ const clearFileChooserDone = useCallback(() => setFileChooserDone(null), []);
+
return {
/** The page the connected stream shows, null for the server's default (meaningful while `connected`). */
page: livePage,
connected, controlling, busy, error, frame, location, tapFocus, viewport, select, dialog, cursor, unsupported, resizeIgnored, signIn,
+ fileChooser, fileChooserError, fileChooserDone,
send, request, acknowledgeFrame, restoreViewport, clearSelect, clearDialog, clearError,
+ answerFileChooser, cancelFileChooser, clearFileChooserError, clearFileChooserDone,
};
}
diff --git a/frontend/tests/browserFileChooser.test.mjs b/frontend/tests/browserFileChooser.test.mjs
new file mode 100644
index 00000000..8ccf30c2
--- /dev/null
+++ b/frontend/tests/browserFileChooser.test.mjs
@@ -0,0 +1,175 @@
+// Part A: the page's own file picker, intercepted instead of Chrome drawing it natively. Covers
+// the wire parsing (browserInput.ts) and the stream hook's chooser state machine
+// (useBrowserStream.ts) — asks, upload/done, inline errors, cancel, and clearing on hand-back and
+// on a fresh server push racing an old one. The sheet component itself (FileChooserModal) isn't
+// rendered here: this suite follows the existing convention (see browserStreamAck.test.mjs) of
+// testing the hook's state, not component DOM.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_default', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const sockets = [];
+class FakeWebSocket {
+ static OPEN = 1;
+ constructor(url) { this.url = url; this.readyState = 1; this.sent = []; sockets.push(this); }
+ send(text) { this.sent.push(JSON.parse(text)); }
+ close() { this.readyState = 3; }
+ receive(message) { this.onmessage?.({ data: JSON.stringify(message) }); }
+}
+g.WebSocket = g.window.WebSocket = FakeWebSocket;
+
+const b = await loadBundled(`export * from './src/browserInput';`);
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export { useBrowserStream } from './src/useBrowserStream';
+`);
+const settle = async () => { for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); };
+
+test('fileChooserTitle reads the accept attribute per the brief’s draft wording', () => {
+ assert.equal(b.fileChooserTitle('video/*'), 'Choose a video');
+ assert.equal(b.fileChooserTitle('image/*'), 'Choose a photo');
+ assert.equal(b.fileChooserTitle('VIDEO/MP4'), 'Choose a video', 'case-insensitive');
+ assert.equal(b.fileChooserTitle(''), 'Choose a file');
+ assert.equal(b.fileChooserTitle('application/pdf'), 'Choose a file');
+ assert.equal(b.fileChooserTitle('image/*,video/*'), 'Choose a file', 'mixed kinds agree on neither, so it falls back');
+ assert.equal(b.fileChooserTitle('video/*', true), 'Choose videos', 'multiple pluralizes');
+ assert.equal(b.fileChooserTitle('image/*', true), 'Choose photos');
+ assert.equal(b.fileChooserTitle('', true), 'Choose files');
+});
+
+test('parseFileChooser needs a numeric id; accept/multiple default safely', () => {
+ assert.deepEqual(b.parseFileChooser({ id: 3, accept: 'video/*', multiple: true }), { id: 3, accept: 'video/*', multiple: true });
+ assert.deepEqual(b.parseFileChooser({ id: 3 }), { id: 3, accept: '', multiple: false });
+ assert.equal(b.parseFileChooser({ accept: 'video/*' }), null, 'no id: not a chooser');
+ assert.equal(b.parseFileChooser(null), null);
+});
+
+test('parseFileChooserFailure needs a numeric id; code/error default to the generic failure text', () => {
+ assert.deepEqual(b.parseFileChooserFailure({ id: 3, code: 'too_big', error: 'That’s more than this browser can take: 100 MB in all. Pick a smaller file.' }), { code: 'too_big', error: 'That’s more than this browser can take: 100 MB in all. Pick a smaller file.' });
+ assert.deepEqual(b.parseFileChooserFailure({ id: 3 }), { code: 'failed', error: 'Couldn’t send that file to the page.' });
+ assert.equal(b.parseFileChooserFailure({ code: 'gone' }), null, 'no id: ignored, same as a stray ack would be');
+});
+
+async function mountStream() {
+ const ref = {};
+ function Probe() {
+ ref.stream = m.useBrowserStream('k1', true);
+ return null;
+ }
+ const root = m.createRoot(document.createElement('div'));
+ m.flushSync(() => root.render(m.React.createElement(Probe)));
+ await settle();
+ const ws = sockets.at(-1);
+ ws.onopen?.();
+ await settle();
+ return { ref, ws, root };
+}
+
+test('a file_chooser push opens the sheet; file_chooser_done closes it and leaves the toast text', async () => {
+ const { ref, ws, root } = await mountStream();
+ assert.equal(ref.stream.fileChooser, null);
+
+ ws.receive({ type: 'file_chooser', id: 1, accept: 'video/*', multiple: false });
+ await settle();
+ assert.deepEqual(ref.stream.fileChooser, { id: 1, accept: 'video/*', multiple: false });
+ assert.equal(ref.stream.fileChooserError, null);
+ assert.equal(ref.stream.fileChooserDone, null);
+
+ ref.stream.answerFileChooser(1, ['att_1']);
+ assert.deepEqual(ws.sent.at(-1), { action: 'file_chooser', id: 1, attachment_ids: ['att_1'] }, 'answers with the chooser’s own id, not sequence.current');
+
+ ws.receive({ type: 'file_chooser_done', id: 1, names: ['clip.mp4'] });
+ await settle();
+ assert.equal(ref.stream.fileChooser, null, 'the sheet closes');
+ assert.deepEqual(ref.stream.fileChooserDone, { names: ['clip.mp4'] }, 'the toast gets the name to show');
+
+ ref.stream.clearFileChooserDone();
+ await settle();
+ assert.equal(ref.stream.fileChooserDone, null);
+ m.flushSync(() => root.unmount());
+});
+
+test('cancelFileChooser sends cancel:true and closes the sheet locally with no reply expected', async () => {
+ const { ref, ws, root } = await mountStream();
+ ws.receive({ type: 'file_chooser', id: 2, accept: '', multiple: false });
+ await settle();
+ assert.ok(ref.stream.fileChooser);
+
+ ref.stream.cancelFileChooser(2);
+ assert.deepEqual(ws.sent.at(-1), { action: 'file_chooser', id: 2, cancel: true });
+ await settle();
+ assert.equal(ref.stream.fileChooser, null, 'the sheet closes right away, optimistically');
+ m.flushSync(() => root.unmount());
+});
+
+test('file_chooser_error shows inline on the sheet it belongs to, and is ignored for a different one', async () => {
+ const { ref, ws, root } = await mountStream();
+ ws.receive({ type: 'file_chooser', id: 3, accept: 'image/*', multiple: true });
+ await settle();
+
+ // A stray error for some other (already-gone) chooser id doesn't touch the open sheet
+ ws.receive({ type: 'file_chooser_error', id: 99, code: 'gone', error: 'The page moved on.' });
+ await settle();
+ assert.equal(ref.stream.fileChooserError, null);
+ assert.ok(ref.stream.fileChooser, 'the open sheet is untouched');
+
+ ws.receive({ type: 'file_chooser_error', id: 3, code: 'too_big', error: 'That’s more than this browser can take: 100 MB in all. Pick a smaller file.' });
+ await settle();
+ assert.deepEqual(ref.stream.fileChooserError, { code: 'too_big', error: 'That’s more than this browser can take: 100 MB in all. Pick a smaller file.' });
+ assert.ok(ref.stream.fileChooser, 'the sheet itself stays open so Try again can retry');
+
+ ref.stream.clearFileChooserError();
+ await settle();
+ assert.equal(ref.stream.fileChooserError, null);
+ m.flushSync(() => root.unmount());
+});
+
+test('a newer file_chooser push supersedes an older one and clears its error', async () => {
+ const { ref, ws, root } = await mountStream();
+ ws.receive({ type: 'file_chooser', id: 4, accept: '', multiple: false });
+ ws.receive({ type: 'file_chooser_error', id: 4, code: 'failed', error: 'Couldn’t send that file to the page.' });
+ await settle();
+ assert.ok(ref.stream.fileChooserError);
+
+ ws.receive({ type: 'file_chooser', id: 5, accept: 'video/*', multiple: false });
+ await settle();
+ assert.deepEqual(ref.stream.fileChooser, { id: 5, accept: 'video/*', multiple: false });
+ assert.equal(ref.stream.fileChooserError, null, 'the new chooser starts with a clean sheet');
+ m.flushSync(() => root.unmount());
+});
+
+test('hand-back clears an open chooser the same way it closes select/dialog, with no dedicated message', async () => {
+ const { ref, ws, root } = await mountStream();
+ ws.receive({ type: 'file_chooser', id: 6, accept: '', multiple: false });
+ await settle();
+ assert.ok(ref.stream.fileChooser);
+
+ ws.receive({ type: 'control', active: false, viewport: { width: 1280, height: 800 } });
+ await settle();
+ assert.equal(ref.stream.fileChooser, null);
+ assert.equal(ref.stream.fileChooserError, null);
+ assert.equal(ref.stream.fileChooserDone, null);
+ m.flushSync(() => root.unmount());
+});
+
+test('a disconnect clears the open chooser so a reconnect never shows a stale sheet', async () => {
+ const { ref, ws, root } = await mountStream();
+ ws.receive({ type: 'file_chooser', id: 7, accept: '', multiple: false });
+ await settle();
+ assert.ok(ref.stream.fileChooser);
+
+ ws.onclose?.();
+ await settle();
+ assert.equal(ref.stream.fileChooser, null);
+ m.flushSync(() => root.unmount());
+});
diff --git a/frontend/tests/rigel_chooser_sheet.test.mjs b/frontend/tests/rigel_chooser_sheet.test.mjs
new file mode 100644
index 00000000..38743818
--- /dev/null
+++ b/frontend/tests/rigel_chooser_sheet.test.mjs
@@ -0,0 +1,92 @@
+// Rigel QA for #578 (Round 2): the FileChooserModal sheet itself, rendered with jsdom + react-dom.
+// Adapted from her original evidence (rigel-evidence/rigel_chooser_sheet.test.mjs) for Mira's
+// Round 2 fix: a "gone" failure now shows a single focused OK button, not Cancel + Try again.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body><div id=root></div></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'KeyboardEvent', 'MouseEvent', 'DragEvent', 'File', 'FileList', 'DataTransfer', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+const m = await loadBundled(`
+ import React from 'react';
+ import { createRoot } from 'react-dom/client';
+ import { flushSync } from 'react-dom';
+ import { FileChooserModal } from './src/components/BrowserPopups';
+ export { React, createRoot, flushSync, FileChooserModal };
+`);
+const { React, createRoot, flushSync, FileChooserModal } = m;
+// the shared bundle helper builds React in production mode, where act() is unavailable: flush by hand
+async function act(fn) { let p; flushSync(() => { p = fn(); }); await p; await new Promise((r) => setTimeout(r, 30)); }
+
+async function mount(props) {
+ const host = document.getElementById('root'); host.innerHTML = '';
+ const root = createRoot(host);
+ const calls = { answer: [], cancel: 0, clear: 0 };
+ const el = (p) => React.createElement(FileChooserModal, { request: { id: 1, accept: 'video/*', multiple: false }, failure: null, onAnswer: (ids) => calls.answer.push(ids), onCancel: () => calls.cancel++, onClearFailure: () => calls.clear++, ...p, ...props });
+ await act(async () => { root.render(el()); });
+ return { host, calls, root, rerender: (p) => act(async () => { root.render(el(p)); }) };
+}
+const buttons = (host) => [...host.querySelectorAll('button')].map((b) => b.textContent.trim());
+
+test('asks: title from accept, Choose file… focused first, Cancel present', async () => {
+ const { host } = await mount();
+ assert.match(host.textContent, /Choose a video/);
+ assert.deepEqual(buttons(host), ['Cancel', 'Choose file…']);
+ assert.equal(document.activeElement?.textContent?.trim(), 'Choose file…', 'focus starts on the primary button');
+});
+test('titles for image and other', async () => {
+ let { host } = await mount({ request: { id: 2, accept: 'image/png', multiple: false } });
+ assert.match(host.textContent, /Choose a photo/);
+ ({ host } = await mount({ request: { id: 3, accept: '', multiple: false } }));
+ assert.match(host.textContent, /Choose a file/);
+});
+test('Escape cancels', async () => {
+ const { host, calls } = await mount();
+ const dlg = host.querySelector('[role=dialog]');
+ await act(async () => { dlg.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); });
+ assert.equal(calls.cancel, 1);
+});
+test('"gone": a single focused OK button, no Try again (Mira item 2)', async () => {
+ const { host } = await mount({ failure: { code: 'gone', error: 'The page moved on.' } });
+ assert.match(host.textContent, /The page moved on and closed its file picker/);
+ assert.deepEqual(buttons(host), ['OK']);
+ assert.equal(document.activeElement?.textContent?.trim(), 'OK', 'OK is focused');
+});
+test('a recoverable failure (not gone): message + Try again returns to picking', async () => {
+ const { host, calls, rerender } = await mount();
+ await rerender({ failure: { code: 'failed', error: 'Couldn’t send that file to the page.' } });
+ assert.match(host.textContent, /Couldn’t send that file to the page\./);
+ assert.deepEqual(buttons(host), ['Cancel', 'Try again']);
+ const retry = [...host.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Try again');
+ await act(async () => { retry.click(); });
+ assert.equal(calls.clear, 1);
+});
+test('client-side preflight: a .docx is refused inline with the supported list', async () => {
+ const { host } = await mount({ request: { id: 4, accept: '', multiple: false } });
+ const input = host.querySelector('input[type=file]');
+ const f = new dom.window.File(['x'.repeat(10)], 'cv.docx', { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
+ Object.defineProperty(input, 'files', { value: [f], configurable: true });
+ await act(async () => { input.dispatchEvent(new dom.window.Event('change', { bubbles: true })); });
+ assert.ok(host.querySelector('[role=alert]'));
+});
+test('input accept/multiple follow the request', async () => {
+ const { host } = await mount({ request: { id: 5, accept: 'video/*', multiple: true } });
+ const input = host.querySelector('input[type=file]');
+ assert.equal(input.getAttribute('accept'), 'video/*');
+ assert.equal(input.multiple, true);
+});
+test('dropping a mismatched file on the sheet is refused inline (Mira item 1)', async () => {
+ const { host } = await mount({ request: { id: 6, accept: 'video/*', multiple: false } });
+ const dlg = host.querySelector('[role=dialog]');
+ const f = new dom.window.File(['x'], 'photo.jpg', { type: 'image/jpeg' });
+ const ev = new dom.window.Event('drop', { bubbles: true, cancelable: true });
+ ev.dataTransfer = { files: [f], items: [{ kind: 'file', getAsFile: () => f }], types: ['Files'] };
+ await act(async () => { dlg.dispatchEvent(ev); });
+ assert.ok(ev.defaultPrevented, 'the drop is handled, not left to the browser');
+ assert.match(host.textContent, /This page asks for a video\./);
+});
diff --git a/src/server/browser_input.rs b/src/server/browser_input.rs
index 43b62cbb..e80b2bda 100644
--- a/src/server/browser_input.rs
+++ b/src/server/browser_input.rs
@@ -384,6 +384,45 @@ pub const COPY_JS: &str = r#"(() => {
/// Longest text `copy` returns.
pub const COPY_MAX: usize = 65536;
+/// Called on a file input (resolved into the recorder's isolated world) to start one file: a
+/// fresh list of Blob parts, with the name, type and `lastModified` to give the finished `File`.
+pub const UPLOAD_BEGIN_FN: &str = r#"function (meta) {
+ if (!this.__kwntUpload) this.__kwntUpload = { files: [] };
+ this.__kwntUpload.files.push({ name: meta.name, mime: meta.mime, lastModified: meta.lastModified, chunks: [] });
+ return true;
+}"#;
+
+/// Appends one base64-decoded chunk (at most 1 MB before encoding) to the file `UPLOAD_BEGIN_FN`
+/// last started. Kept as `Uint8Array`s, not a plain byte array, so a 100 MB file doesn't balloon
+/// into thirty-odd million boxed numbers in a small container.
+pub const UPLOAD_CHUNK_FN: &str = r#"function (b64) {
+ const u = this.__kwntUpload;
+ if (!u || !u.files.length) return false;
+ const bin = atob(b64);
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+ u.files[u.files.length - 1].chunks.push(bytes);
+ return true;
+}"#;
+
+/// Builds the `File`s from their chunks, sets them on the input through a `DataTransfer` (the
+/// only way to set `.files` from script) and fires bubbling input and change, as a real pick
+/// does. Then tells the recorder, in this same world, so Show it once logs the label, never the
+/// name (capture.rs S-C13); a no-op where nothing is recording.
+pub const UPLOAD_FINISH_FN: &str = r#"function () {
+ const u = this.__kwntUpload;
+ if (!u || !u.files.length) return false;
+ const dt = new DataTransfer();
+ u.files.forEach((f) => dt.items.add(new File(f.chunks, f.name, { type: f.mime, lastModified: f.lastModified })));
+ this.files = dt.files;
+ delete this.__kwntUpload;
+ this.dispatchEvent(new Event('input', { bubbles: true }));
+ this.dispatchEvent(new Event('change', { bubbles: true }));
+ const rec = globalThis.__kwntRecorderUpload;
+ if (typeof rec === 'function') rec(this);
+ return true;
+}"#;
+
pub fn cursor_js(x: f64, y: f64) -> String {
format!(
"(() => {{ const e = document.elementFromPoint({x}, {y}); if (!e) return 'auto'; const c = getComputedStyle(e).cursor; \
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 55cbf1dc..c8bac6fe 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -9,6 +9,7 @@ use super::browser_input::{self as bi, KeyEvent, KeyKind, MouseButton, RateLimit
use super::point;
use super::{routes::PageRefusal, AppState};
use super::show_once::{capture as recorder, stage::{Act, StageRecorder}};
+use crate::db::attachments::Attachment;
use crate::sandbox::app_links::{self, AppLinkWatch, Verdict};
use crate::sandbox::browser::{web_address, BrowserController, BrowserError, HeldPointer, PersonLease, ViewClaim, ViewRelease, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};
use crate::sandbox::browser_history::HistoryDirection;
@@ -32,6 +33,17 @@ const SELECT_GROUP: &str = "kwnt-select";
/// A frame the client has not acked for this long is let go, so a lost ack costs one stale
/// picture instead of the stream (and the person's control).
const FRAME_STALL: Duration = Duration::from_secs(4);
+/// Chrome somewhere else has no shared filesystem with kwnt, so a file chooser answer there goes
+/// in as base64 chunks instead of a real path; the compose browser's own container caps at
+/// mem_limit 1536m, so the files sent that way are capped well under it.
+const REMOTE_UPLOAD_CAP_BYTES: u64 = 100 * 1024 * 1024;
+/// Per `Runtime.callFunctionOn` call, before base64 encoding.
+const UPLOAD_CHUNK_BYTES: usize = 1_000_000;
+/// How long a local-delivery temp copy (named after the attachment, not its content hash) stays
+/// after `DOM.setFileInputFiles`, since the page may only read it later (e.g. only once the person
+/// clicks "Post"). An opportunistic sweep of older orphans runs on every new chooser as a backstop.
+const CHOOSER_TMP_TTL: Duration = Duration::from_secs(600);
+const CHOOSER_TMP_ORPHAN_AGE: Duration = Duration::from_secs(3600);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -793,6 +805,19 @@ struct Worker {
open_select: Option<String>,
}
+/// A page's file picker, intercepted instead of letting Chrome draw its own natively. Lives in
+/// `stream()`'s locals next to `dialog_open` — per-connection, latest wins, cleared on navigation
+/// and Hand back, never a bot's concern (nothing is sent to the client during a bot's turn).
+#[derive(Clone)]
+struct OpenChooser {
+ /// This connection's own counter, not a CDP id: lets the client tell which sheet a
+ /// `file_chooser_done`/error belongs to even if it raced a newer chooser.
+ id: u64,
+ backend_node_id: i64,
+ frame_id: String,
+ multiple: bool,
+}
+
fn ack(id: &Value, extra: Value) -> Value {
let mut ack = json!({"type":"ack","id":id});
if let (Some(ack), Value::Object(extra)) = (ack.as_object_mut(), extra) {
@@ -805,6 +830,21 @@ fn error(id: &Value, error: impl std::fmt::Display) -> Value {
json!({"type":"error","id":id,"error":error.to_string()})
}
+/// A file chooser failure, with a machine-readable `code` (`too_big`, `gone`, `failed`) so the
+/// sheet can show the right inline message. Its own type, never `error`: the chooser's `id`
+/// comes from the server's own per-connection counter, not the client's action-correlation
+/// counter `error`/`ack` are matched against, so reusing `error`'s envelope could misroute this
+/// into an unrelated pending action or G3 Point wait by sheer numeric coincidence.
+fn chooser_error(id: &Value, code: &str, message: impl std::fmt::Display) -> Value {
+ json!({"type":"file_chooser_error","id":id,"code":code,"error":message.to_string()})
+}
+
+/// The one thing people ever see for a server-side file-chooser failure (a copy/CDP/lookup error):
+/// never the raw OS or CDP error text, which goes to the server's own log instead.
+fn file_chooser_failed() -> (&'static str, String) {
+ ("failed", "Couldn’t send that file to the page.".to_string())
+}
+
fn protocol(message: &str) -> BrowserError {
BrowserError::Protocol(message.into())
}
@@ -1234,6 +1274,10 @@ struct Page {
/// guard and the screencast.
async fn watch_page(cdp: &Cdp, shared: &Shared) -> Result<(), BrowserError> {
cdp.call("Page.enable", json!({}), Duration::from_secs(10)).await?;
+ // Chrome would otherwise draw its own native file picker, which nobody watching the live
+ // view can see (headless: closed at once; headful on a virtual display: off-screen).
+ // Intercepting it turns it into a `Page.fileChooserOpened` event instead.
+ cdp.call("Page.setInterceptFileChooserDialog", json!({"enabled": true}), Duration::from_secs(10)).await?;
// A Chrome window behind other apps on a Mac doesn't have the OS's focus, so its page
// can act unfocused and drop typed keys. While anyone watches or controls it, the page
// behaves as focused (as Playwright does for every page). It ends with this connection.
@@ -1329,7 +1373,7 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
let local = service.mode() == crate::sandbox::computer::ComputerMode::Local;
let window = if local && service.local_window() { None } else { Some(local && crate::sandbox::computer::window_reason().is_none()) };
let mut signin = crate::sandbox::signin_gate::LiveNotice::new(window);
- let result = stream(&mut socket, &ctrl, &cdp, &mut events, &mut page, &shared, &client_tx, &mut client_rx, &jobs, &mut rec, &pointer, &mut signin).await;
+ let result = stream(&mut socket, &ctrl, &cdp, &mut events, &mut page, &shared, &client_tx, &mut client_rx, &jobs, &mut rec, &pointer, &mut signin, &state, local).await;
// a recording live on this socket stops here (Show it once: `closed`), its steps kept, after
// the edit still pending in the page, if the page can still be reached
if rec.is_live() {
@@ -1362,6 +1406,8 @@ async fn stream(
rec: &mut StageRecorder,
pointer: &Arc<Pointer>,
signin: &mut crate::sandbox::signin_gate::LiveNotice,
+ state: &AppState,
+ local: bool,
) -> (Result<(), BrowserError>, Option<PersonLease>) {
let mut lease: Option<PersonLease> = None;
// the Show it once recorder's script on new documents, while a recording is live
@@ -1382,6 +1428,14 @@ async fn stream(
let mut location_tick = tokio::time::interval(Duration::from_secs(2));
let mut moves = RateLimit::new(bi::MOVES_PER_SECOND, 10.0, std::time::Instant::now());
let mut dialog_open = false;
+ // the page's file picker, intercepted instead of Chrome drawing its own; latest wins
+ let mut chooser: Option<OpenChooser> = None;
+ let mut chooser_seq: u64 = 0;
+ // the validate/inject work for an answer runs off this loop, in `tokio::spawn`; it reports
+ // back a reply to forward plus, for a recoverable (not "gone") failure, the chooser to put
+ // back so Try again can reuse the same id — one message, so the restore and the reply the
+ // client reacts to can never be seen out of order
+ let (chooser_reply_tx, mut chooser_reply_rx) = mpsc::unbounded_channel::<(Option<OpenChooser>, Value)>();
let mut app_links = AppLinkWatch::default();
// the events of the page the view moved to: a popup the page opened, or back from it
let mut moved: Option<mpsc::Receiver<Value>> = None;
@@ -1391,6 +1445,7 @@ async fn stream(
frames = FrameGate::default();
app_links = AppLinkWatch::default();
dialog_open = false;
+ chooser = None;
pointer.forget_world();
// Show it once records on the page in front too
if rec.is_live() {
@@ -1455,6 +1510,12 @@ async fn stream(
}
}
Some(value) = client_rx.recv() => send(socket, value).await?,
+ Some((restore, value)) = chooser_reply_rx.recv() => {
+ // a newer chooser (a fresh pick, a navigation) already took the slot: never
+ // clobber it with a stale one
+ if let Some(open) = restore { if chooser.is_none() { chooser = Some(open); } }
+ send(socket, value).await?;
+ }
event = events.recv() => {
let Some(event) = event else {
// the page's socket closed: a popup that closed, with its opener in front again
@@ -1469,6 +1530,10 @@ async fn stream(
// a new document: the old title goes now, the new one follows on DOMContentLoaded
if let Some(url) = navigated_to(method, params) {
pointer.forget_world();
+ // its backendNodeId won't resolve to the new document's input
+ if let Some(open) = chooser.take() {
+ let _ = client_tx.send(chooser_error(&json!(open.id), "gone", "The page moved on."));
+ }
let _ = client_tx.send(json!({"type":"location","url":url,"title":""}));
if let Some(notice) = signin.update(&url, lease.is_some() || ctrl.is_held_for_person()) {
let _ = client_tx.send(notice);
@@ -1516,6 +1581,19 @@ async fn stream(
dialog_open = false;
send(socket, json!({"type":"dialog_closed","accepted":params["result"]})).await?;
}
+ // during a bot's turn, nothing goes to the client: Part B covers bots
+ "Page.fileChooserOpened" if lease.is_some() || ctrl.is_held_for_person() => {
+ if let (Some(backend_node_id), Some(frame_id)) =
+ (params["backendNodeId"].as_i64(), params["frameId"].as_str())
+ {
+ let multiple = params["mode"].as_str() == Some("selectMultiple");
+ let accept = describe_accept(cdp, backend_node_id).await;
+ chooser_seq += 1;
+ let id = chooser_seq;
+ chooser = Some(OpenChooser { id, backend_node_id, frame_id: frame_id.to_string(), multiple });
+ send(socket, json!({"type":"file_chooser","id":id,"accept":accept,"multiple":multiple})).await?;
+ }
+ }
_ => {}
}
}
@@ -1562,6 +1640,7 @@ async fn stream(
if rec.is_live() {
recorder_acts(socket, ctrl, cdp, shared, rec, vec![Act::Flush], &mut recorder_script).await?;
}
+ chooser = None;
let (done, wait) = oneshot::channel();
if jobs.send(Job::HandBack(Some(done))).is_ok() {
let _ = timeout(Duration::from_secs(8), wait).await;
@@ -1578,6 +1657,39 @@ async fn stream(
"restore_viewport" => { let _ = jobs.send(Job::Restore(id)); }
// G3 Point at it: read-only, so watching is enough
"point_at" | "point_neighbour" | "point_pick" => pointer.handle(&value, id, shared),
+ "file_chooser" => {
+ if lease.is_none() && !ctrl.is_held_for_person() {
+ send(socket, chooser_error(&id, "failed", not_in_control(ctrl.control.try_read().is_err()))).await?;
+ continue;
+ }
+ let Some(seq) = value["id"].as_u64() else { send(socket, chooser_error(&id, "failed", protocol("Missing id"))).await?; continue; };
+ if chooser.as_ref().map(|c| c.id) != Some(seq) {
+ send(socket, chooser_error(&id, "gone", "The page moved on.")).await?;
+ continue;
+ }
+ let open = chooser.take().expect("checked above");
+ if value["cancel"] == true {
+ // the sheet already knows it cancelled; no reply needed
+ continue;
+ }
+ let ids: Vec<String> = value["attachment_ids"].as_array().cloned().unwrap_or_default()
+ .into_iter().filter_map(|v| v.as_str().map(str::to_string)).collect();
+ let (state, cdp, reply_tx) = (state.clone(), cdp.clone(), chooser_reply_tx.clone());
+ tokio::spawn(async move {
+ let (restore, reply) = match answer_file_chooser(&state, &cdp, local, &open, ids).await {
+ Ok(names) => (None, json!({"type":"file_chooser_done","id":open.id,"names":names})),
+ Err((code, message)) => {
+ // "gone" means the picker itself is really gone (the page
+ // navigated, or CDP lost the node); anything else is a
+ // failure the same picker can still answer, so Try again
+ // needs its id to still mean something
+ let restore = (code != "gone").then(|| open.clone());
+ (restore, chooser_error(&json!(open.id), code, message))
+ }
+ };
+ let _ = reply_tx.send((restore, reply));
+ });
+ }
_ => {
if lease.is_none() && !ctrl.is_held_for_person() {
send(socket, error(&id, not_in_control(ctrl.control.try_read().is_err()))).await?;
@@ -1618,6 +1730,189 @@ async fn stream(
(result, lease)
}
+/// Reads the `accept` attribute straight off the DOM node CDP already named in
+/// `Page.fileChooserOpened`'s `backendNodeId`, with no `DOM.resolveNode`/`Runtime.callFunctionOn`
+/// round trip just for this. `multiple` comes from the event's own `mode` instead (never raced).
+async fn describe_accept(cdp: &Cdp, backend_node_id: i64) -> String {
+ let Ok(described) = cdp.call("DOM.describeNode", json!({"backendNodeId": backend_node_id}), PROBE_WAIT).await else {
+ return String::new();
+ };
+ accept_attr(described["node"]["attributes"].as_array().map(Vec::as_slice).unwrap_or_default())
+}
+
+/// `DOM.describeNode`'s `attributes` is a flat `[name, value, name, value, ...]` array; this picks
+/// out `accept`'s value, or `""` when the input has none (any file type).
+fn accept_attr(attributes: &[Value]) -> String {
+ attributes
+ .chunks(2)
+ .find(|pair| pair.first().and_then(Value::as_str) == Some("accept"))
+ .and_then(|pair| pair.get(1))
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string()
+}
+
+/// Validates the client's answer (known ids, belongs to this person's own unsent uploads, not
+/// over the remote cap), then puts the files into the page. Names on success, or a coded error
+/// for the sheet (`too_big`, `gone`, `failed` — matching the brief exactly).
+async fn answer_file_chooser(
+ state: &AppState,
+ cdp: &Cdp,
+ local: bool,
+ open: &OpenChooser,
+ ids: Vec<String>,
+) -> Result<Vec<String>, (&'static str, String)> {
+ if ids.is_empty() {
+ return Err(("failed", "No file was chosen.".to_string()));
+ }
+ let ids: Vec<String> = if open.multiple { ids } else { ids.into_iter().take(1).collect() };
+ let attachments = super::attachments::check_uploads(state, &ids).await.map_err(|e| {
+ tracing::warn!("file chooser: check_uploads refused the answer: {}", e);
+ file_chooser_failed()
+ })?;
+ if !local {
+ let total: i64 = attachments.iter().map(|a| a.size).sum();
+ if total < 0 || total as u64 > REMOTE_UPLOAD_CAP_BYTES {
+ return Err(("too_big", "That’s more than this browser can take: 100 MB in all. Pick a smaller file.".to_string()));
+ }
+ }
+ let names = attachments.iter().map(|a| a.name.clone()).collect();
+ if local {
+ set_file_input_files_local(state, cdp, open, &attachments).await?;
+ } else {
+ inject_files_remote(state, cdp, open, &attachments).await?;
+ }
+ Ok(names)
+}
+
+/// Local Chrome shares kwnt's filesystem, but `DOM.setFileInputFiles` names the file from the
+/// path's own basename, not from any metadata, and the blob is named by its sha256 with no
+/// extension. A copy named after the attachment's real name fixes that — the same workaround
+/// Playwright's own buffer-based `setInputFiles` uses internally. The page may only read the
+/// bytes later (e.g. only once the person clicks "Post"), so the copy can't be removed right
+/// after this call returns: it's scheduled for removal after `CHOOSER_TMP_TTL`, with an
+/// opportunistic sweep of older orphans on every new chooser as a backstop if kwnt restarts.
+async fn set_file_input_files_local(
+ state: &AppState,
+ cdp: &Cdp,
+ open: &OpenChooser,
+ attachments: &[Attachment],
+) -> Result<(), (&'static str, String)> {
+ let root = super::attachments::root(state);
+ let tmp_root = root.join("chooser-tmp");
+ sweep_chooser_tmp(&tmp_root).await;
+ let dir = tmp_root.join(uuid::Uuid::new_v4().to_string());
+ tokio::fs::create_dir_all(&dir).await.map_err(|e| {
+ tracing::warn!("file chooser: couldn't create {}: {}", dir.display(), e);
+ file_chooser_failed()
+ })?;
+ let mut paths = Vec::with_capacity(attachments.len());
+ for a in attachments {
+ let Some(blob) = super::attachments::blob_path(&root, &a.sha256) else {
+ tracing::warn!("file chooser: no blob for attachment {}", a.id);
+ return Err(file_chooser_failed());
+ };
+ let dest = dir.join(super::attachments::clean_name(&a.name));
+ tokio::fs::copy(&blob, &dest).await.map_err(|e| {
+ tracing::warn!("file chooser: couldn't copy {} to {}: {}", blob.display(), dest.display(), e);
+ file_chooser_failed()
+ })?;
+ paths.push(dest);
+ }
+ let result = cdp
+ .call(
+ "DOM.setFileInputFiles",
+ json!({"files": paths.iter().map(|p| p.to_string_lossy().to_string()).collect::<Vec<_>>(), "backendNodeId": open.backend_node_id}),
+ ACTION_WAIT,
+ )
+ .await;
+ let cleanup_dir = dir.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(CHOOSER_TMP_TTL).await;
+ let _ = tokio::fs::remove_dir_all(&cleanup_dir).await;
+ });
+ result.map(|_| ()).map_err(|_| ("gone", "The page moved on.".to_string()))
+}
+
+/// Deletes any `chooser-tmp` directory older than `CHOOSER_TMP_ORPHAN_AGE`, a backstop for the
+/// scheduled cleanup in [`set_file_input_files_local`] if the process restarted before it ran.
+async fn sweep_chooser_tmp(tmp_root: &std::path::Path) {
+ let Ok(mut entries) = tokio::fs::read_dir(tmp_root).await else { return };
+ let cutoff = std::time::SystemTime::now() - CHOOSER_TMP_ORPHAN_AGE;
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ if entry.metadata().await.ok().and_then(|m| m.modified().ok()).is_some_and(|m| m < cutoff) {
+ let _ = tokio::fs::remove_dir_all(entry.path()).await;
+ }
+ }
+}
+
+/// Chrome somewhere else (`KWNT_BROWSER_CDP_URL`) has no filesystem shared with kwnt, so the
+/// bytes go in as base64 chunks instead, evaluated in the recorder's own isolated world (reusing
+/// `Page.fileChooserOpened`'s own `frameId` — no extra `Page.getFrameTree` round trip, unlike
+/// `record_pick`) so the upload's own finish call can tell the recorder directly (S-C13: the
+/// label only, never the file's name). Kept as `Uint8Array`s in the page, not concatenated into a
+/// JS number array, so a 100 MB file doesn't balloon past the compose browser's 1536m container.
+async fn inject_files_remote(
+ state: &AppState,
+ cdp: &Cdp,
+ open: &OpenChooser,
+ attachments: &[Attachment],
+) -> Result<(), (&'static str, String)> {
+ use base64::Engine;
+ let gone = || ("gone", "The page moved on.".to_string());
+ let failed = file_chooser_failed;
+ let world = cdp
+ .call("Page.createIsolatedWorld", json!({"frameId": open.frame_id, "worldName": recorder::WORLD}), PROBE_WAIT)
+ .await
+ .map_err(|_| gone())?;
+ let context = world["executionContextId"].as_i64().ok_or_else(gone)?;
+ let resolved = cdp
+ .call("DOM.resolveNode", json!({"backendNodeId": open.backend_node_id, "executionContextId": context}), PROBE_WAIT)
+ .await
+ .map_err(|_| gone())?;
+ let object = resolved["object"]["objectId"].as_str().map(str::to_string).ok_or_else(gone)?;
+ let root = super::attachments::root(state);
+ let outcome = async {
+ for a in attachments {
+ let blob = super::attachments::blob_path(&root, &a.sha256).ok_or_else(failed)?;
+ let bytes = tokio::fs::read(&blob).await.map_err(|_| failed())?;
+ let began = cdp
+ .call(
+ "Runtime.callFunctionOn",
+ json!({
+ "objectId": object, "functionDeclaration": bi::UPLOAD_BEGIN_FN,
+ "arguments": [{"value": {"name": a.name.clone(), "mime": a.mime.clone(), "lastModified": a.created_at.timestamp_millis()}}],
+ "returnByValue": true,
+ }),
+ ACTION_WAIT,
+ )
+ .await;
+ if !began.is_ok_and(|r| r["result"]["value"] == true) { return Err(failed()); }
+ for chunk in bytes.chunks(UPLOAD_CHUNK_BYTES) {
+ let b64 = base64::engine::general_purpose::STANDARD.encode(chunk);
+ let chunked = cdp
+ .call(
+ "Runtime.callFunctionOn",
+ json!({"objectId": object, "functionDeclaration": bi::UPLOAD_CHUNK_FN, "arguments": [{"value": b64}], "returnByValue": true}),
+ ACTION_WAIT,
+ )
+ .await;
+ if !chunked.is_ok_and(|r| r["result"]["value"] == true) { return Err(failed()); }
+ }
+ }
+ let finished = cdp
+ .call(
+ "Runtime.callFunctionOn",
+ json!({"objectId": object, "functionDeclaration": bi::UPLOAD_FINISH_FN, "returnByValue": true}),
+ ACTION_WAIT,
+ )
+ .await;
+ if finished.is_ok_and(|r| r["result"]["value"] == true) { Ok(()) } else { Err(failed()) }
+ }.await;
+ let _ = cdp.call("Runtime.releaseObject", json!({"objectId": object}), PROBE_WAIT).await;
+ outcome
+}
+
/// Keeps links to another app from freezing the tab while the live view is open (see
/// [`app_links`]), and has the guard say when it stopped one. Runtime is enabled for that call
/// and Log for Chrome's own refusals.
@@ -2024,4 +2319,27 @@ mod tests {
assert!(events.iter().all(|e| e["type"] == "mouseReleased" && e["x"] == 3.0 && e["y"] == 4.0));
assert!(release_events(HeldPointer { x: 0.0, y: 0.0, buttons: 0 }).is_empty());
}
+
+ /// Its own `type`, never `error`/`ack`: those are matched against the client's own
+ /// `sequence.current` id-space, which the chooser's server-assigned id can collide with.
+ #[test]
+ fn a_file_chooser_failure_never_looks_like_a_generic_error() {
+ let wire = chooser_error(&json!(7), "too_big", "That's bigger than kwnt can send here (100 MB).");
+ assert_eq!(wire["type"], "file_chooser_error");
+ assert_eq!(wire["id"], 7);
+ assert_eq!(wire["code"], "too_big");
+ assert_eq!(wire["error"], "That's bigger than kwnt can send here (100 MB).");
+ assert_ne!(wire["type"], "error");
+ assert_ne!(wire["type"], "ack");
+ }
+
+ #[test]
+ fn accept_reads_the_flat_attribute_pairs_or_falls_back_to_any_file() {
+ assert_eq!(accept_attr(&[json!("id"), json!("f1"), json!("accept"), json!("video/*")]), "video/*");
+ assert_eq!(accept_attr(&[json!("accept"), json!("image/*"), json!("multiple"), json!("")]), "image/*");
+ assert_eq!(accept_attr(&[json!("id"), json!("f1")]), "", "no accept attribute: any file type");
+ assert_eq!(accept_attr(&[]), "");
+ // a dangling name with no paired value doesn't panic
+ assert_eq!(accept_attr(&[json!("accept")]), "");
+ }
}
diff --git a/src/server/show_once/recorder.js b/src/server/show_once/recorder.js
index ce075474..39830378 100644
--- a/src/server/show_once/recorder.js
+++ b/src/server/show_once/recorder.js
@@ -166,6 +166,17 @@
return true;
} });
+ // The person picked a file kwnt's own sheet put in (the live view can't show Chrome's native
+ // picker): the page sees an untrusted change, which the listener below ignores. kwnt's server
+ // calls this, in this world only, right after setting the input's files, so the upload is still
+ // logged as an `upload` step like a native pick, label only, never the file's name (S-C13).
+ Object.defineProperty(globalThis, '__kwntRecorderUpload', { value: function (el) {
+ if (!el || el.nodeType !== 1 || el.tagName !== 'INPUT' || String(el.type).toLowerCase() !== 'file') return false;
+ var ff = facts(el);
+ post({ kind: 'upload', field: ff, label: label(ff) });
+ return true;
+ } });
+
document.addEventListener('change', function (e) {
var el = e.target;
if (!e.isTrusted) { if (isTextField(el)) scripted.add(el); return; }
diff --git a/tests/browser_file_chooser_test.rs b/tests/browser_file_chooser_test.rs
new file mode 100644
index 00000000..2d34e84e
--- /dev/null
+++ b/tests/browser_file_chooser_test.rs
@@ -0,0 +1,320 @@
+//! The page's own file picker (`<input type=file>`), the way TikTok Studio's "Select video" opens
+//! one: the screencast can't show Chrome's native dialog, so it's intercepted
+//! (`Page.setInterceptFileChooserDialog`) and the live view shows its own sheet instead. Covers a
+//! visible input and a hidden-input-behind-a-button page (the TikTok shape), answering with an
+//! attachment already uploaded through `/api/attachments`, cancelling, and a chooser cleared by
+//! navigation. Skipped when no Chrome is installed. Local delivery only — there's no remote Chrome
+//! in this environment to exercise the base64/DataTransfer path.
+#[path = "support/chrome_guard.rs"]
+mod chrome_guard;
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+};
+use chrome_guard::ChromeGuard;
+use futures::{SinkExt, StreamExt};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::Kwant, spaces::SpaceId, Database},
+ router::LayaRouter,
+ sandbox::{computer, BrowserController},
+ server::{create_router, routes::get_or_create_browser_controller, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tower::ServiceExt;
+use tokio_tungstenite::{connect_async, tungstenite::{client::IntoClientRequest, Message as WsMessage}};
+
+/// A visible file input over the whole page, reporting what it got in its title.
+const VISIBLE: &str = "<!doctype html><html><head><title>visible</title></head><body style=margin:0>\
+<input type=file id=f style='position:fixed;inset:0;opacity:0.01'>\
+<script>f.onchange=function(){document.title='picked:'+Array.from(f.files).map(function(x){return x.name}).join(',')}</script>\
+</body></html>";
+/// TikTok-like: the real input is hidden, a button over the whole page opens it.
+const HIDDEN: &str = "<!doctype html><html><head><title>hidden</title></head><body style=margin:0>\
+<input type=file id=f style=display:none accept=video/*>\
+<button onclick=f.click() style='position:fixed;inset:0'>Select video</button>\
+<script>f.onchange=function(){document.title='picked:'+Array.from(f.files).map(function(x){return x.name}).join(',')}</script>\
+</body></html>";
+
+async fn serve() -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = [0u8; 4096];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let req = String::from_utf8_lossy(&buf[..n]).to_string();
+ let page = match req.split_whitespace().nth(1).unwrap_or("/") {
+ "/visible" => VISIBLE,
+ "/hidden" => HIDDEN,
+ _ => "<!doctype html><title>plain</title>",
+ };
+ let reply = format!("HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{page}", page.len());
+ let _ = stream.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://127.0.0.1:{port}")
+}
+
+struct Env {
+ state: AppState,
+ bot: Kwant,
+ tmp: TempDir,
+}
+
+/// kwnt in Local mode, so the bot's browser is a real Chrome on this machine and uploads share its
+/// filesystem (the `DOM.setFileInputFiles` path, not the base64 one).
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.set_setting(computer::SETTING_KEY, "local").await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ Env { state, bot, tmp }
+}
+
+/// Uploads a small file through the real `/api/attachments` route (the same one the chat compose
+/// box uses), returning its id — exactly the id a `file_chooser` answer carries.
+async fn upload(state: &AppState, name: &str, bytes: &'static [u8]) -> String {
+ let app = create_router(state.clone());
+ let req = Request::builder()
+ .method("POST")
+ .uri(format!("/api/attachments?name={name}"))
+ .header("content-type", "application/octet-stream")
+ .body(Body::from(bytes))
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::CREATED);
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let v: Value = serde_json::from_slice(&body).unwrap();
+ v["id"].as_str().expect("attachment id").to_string()
+}
+
+async fn cdp(ctrl: &BrowserController, method: &str, params: Value) -> Option<Value> {
+ tokio::time::timeout(Duration::from_secs(10), ctrl.send_cdp_command(method, params)).await.ok()?.ok()
+}
+
+async fn title_becomes(ctrl: &BrowserController, want: &str) -> String {
+ let mut title = String::new();
+ for _ in 0..50 {
+ let value = cdp(ctrl, "Runtime.evaluate", json!({"expression": "document.title", "returnByValue": true})).await;
+ title = value.and_then(|v| v["result"]["value"].as_str().map(str::to_string)).unwrap_or_default();
+ if title == want { break; }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ title
+}
+
+type Ws = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
+
+/// The next live-view message of `kind` that `matches`, answering pings/frames meanwhile; `None`
+/// after 10 s. Same as `browser_popups_test.rs`'s helper, but doesn't fail on `"error"`: a couple
+/// of these tests expect one (a mismatched/stale chooser id).
+async fn next_message(ws: &mut Ws, kind: &str, matches: impl Fn(&Value) -> bool) -> Option<Value> {
+ tokio::time::timeout(Duration::from_secs(10), async {
+ loop {
+ let message = ws.next().await?.ok()?;
+ let WsMessage::Text(text) = message else { continue };
+ let value: Value = serde_json::from_str(&text).unwrap_or_default();
+ if value["type"] == "ping" { ws.send(WsMessage::Text(json!({"action": "pong"}).to_string())).await.ok()?; }
+ if value["type"] == "frame" { ws.send(WsMessage::Text(json!({"action": "frame_ack", "id": value["id"]}).to_string())).await.ok()?; }
+ if value["type"] == kind && matches(&value) { return Some(value); }
+ }
+ }).await.ok().flatten()
+}
+
+async fn connect(state: &AppState, bot_id: &str) -> (Ws, tokio::task::JoinHandle<()>) {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let app = create_router(state.clone());
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let mut request = format!("ws://127.0.0.1:{port}/api/sandbox/{bot_id}/stream").into_client_request().unwrap();
+ request.headers_mut().insert("Origin", format!("http://127.0.0.1:{port}").parse().unwrap());
+ let (ws, _) = connect_async(request).await.unwrap();
+ (ws, server)
+}
+
+async fn take_control(ws: &mut Ws) {
+ ws.send(WsMessage::Text(json!({"action": "take_control"}).to_string())).await.unwrap();
+ assert!(next_message(ws, "control", |c| c["active"] == true).await.is_some());
+}
+
+#[tokio::test]
+async fn picking_a_visible_input_uploads_and_delivers_the_file() {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let e = setup().await;
+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));
+ let base = serve().await;
+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");
+ ctrl.navigate(&format!("{base}/visible")).await.unwrap();
+ assert_eq!(title_becomes(&ctrl, "visible").await, "visible");
+
+ let attachment_id = upload(&e.state, "clip.mp4", b"\0\0\0\x18ftypisom\0\0\x02\0isomiso2mp41 not really a video, just test bytes").await;
+ let (mut ws, server) = connect(&e.state, &e.bot.id).await;
+ assert!(next_message(&mut ws, "frame", |_| true).await.is_some());
+ take_control(&mut ws).await;
+
+ ws.send(WsMessage::Text(json!({"action": "click", "x": 40, "y": 40, "id": 1}).to_string())).await.unwrap();
+ let opened = next_message(&mut ws, "file_chooser", |_| true).await.expect("the click opens the intercepted chooser");
+ assert_eq!(opened["multiple"], false);
+ let chooser_id = opened["id"].clone();
+
+ ws.send(WsMessage::Text(json!({"action": "file_chooser", "id": chooser_id, "attachment_ids": [attachment_id]}).to_string())).await.unwrap();
+ let done = next_message(&mut ws, "file_chooser_done", |_| true).await.expect("the server answers once the file lands");
+ assert_eq!(done["id"], chooser_id);
+ assert_eq!(done["names"], json!(["clip.mp4"]));
+ assert_eq!(title_becomes(&ctrl, "picked:clip.mp4").await, "picked:clip.mp4", "the page's own change handler saw the file, as a real pick would");
+
+ ws.close(None).await.unwrap();
+ server.abort();
+}
+
+#[tokio::test]
+async fn a_tiktok_style_hidden_input_behind_a_button_is_intercepted_too() {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let e = setup().await;
+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));
+ let base = serve().await;
+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");
+ ctrl.navigate(&format!("{base}/hidden")).await.unwrap();
+ assert_eq!(title_becomes(&ctrl, "hidden").await, "hidden");
+
+ let attachment_id = upload(&e.state, "post.mov", b"\0\0\0\x18ftypqt \0\0\x02\0qt more test bytes, still not a real video").await;
+ let (mut ws, server) = connect(&e.state, &e.bot.id).await;
+ assert!(next_message(&mut ws, "frame", |_| true).await.is_some());
+ take_control(&mut ws).await;
+
+ ws.send(WsMessage::Text(json!({"action": "click", "x": 40, "y": 40, "id": 1}).to_string())).await.unwrap();
+ let opened = next_message(&mut ws, "file_chooser", |_| true).await.expect("clicking the button over the hidden input still opens the intercepted chooser");
+ assert_eq!(opened["accept"], "video/*", "the sheet gets the real input's accept, read straight off the DOM node");
+
+ ws.send(WsMessage::Text(json!({"action": "file_chooser", "id": opened["id"], "attachment_ids": [attachment_id]}).to_string())).await.unwrap();
+ let done = next_message(&mut ws, "file_chooser_done", |_| true).await.expect("answered the same way as a visible input");
+ assert_eq!(done["names"], json!(["post.mov"]));
+ assert_eq!(title_becomes(&ctrl, "picked:post.mov").await, "picked:post.mov");
+
+ ws.close(None).await.unwrap();
+ server.abort();
+}
+
+#[tokio::test]
+async fn cancelling_the_sheet_gets_no_reply_and_leaves_the_page_untouched() {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let e = setup().await;
+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));
+ let base = serve().await;
+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");
+ ctrl.navigate(&format!("{base}/visible")).await.unwrap();
+ assert_eq!(title_becomes(&ctrl, "visible").await, "visible");
+
+ let (mut ws, server) = connect(&e.state, &e.bot.id).await;
+ assert!(next_message(&mut ws, "frame", |_| true).await.is_some());
+ take_control(&mut ws).await;
+
+ ws.send(WsMessage::Text(json!({"action": "click", "x": 40, "y": 40, "id": 1}).to_string())).await.unwrap();
+ let opened = next_message(&mut ws, "file_chooser", |_| true).await.expect("chooser opened");
+
+ ws.send(WsMessage::Text(json!({"action": "file_chooser", "id": opened["id"], "cancel": true}).to_string())).await.unwrap();
+ // Nothing more should come back for this chooser: clicking again must open a brand new one
+ // (an old `file_chooser_done`/error lingering would prove the cancel got an unwanted reply).
+ ws.send(WsMessage::Text(json!({"action": "click", "x": 40, "y": 40, "id": 2}).to_string())).await.unwrap();
+ let reopened = next_message(&mut ws, "file_chooser", |_| true).await.expect("a fresh click opens a fresh chooser");
+ assert_ne!(reopened["id"], opened["id"], "cancel actually cleared the old chooser, this is a new one");
+ assert_eq!(title_becomes(&ctrl, "visible").await, "visible", "no file ever reached the page");
+
+ ws.close(None).await.unwrap();
+ server.abort();
+}
+
+/// Rigel's finding 1: `chooser.take()` used to run before the answer was validated, so a recoverable
+/// failure (here, an unknown attachment id) consumed the chooser and "Try again" always got `gone`.
+/// Answering the same id again after a `failed` reply must now actually reach the page.
+#[tokio::test]
+async fn retrying_the_same_chooser_after_a_failed_answer_still_delivers_the_file() {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let e = setup().await;
+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));
+ let base = serve().await;
+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");
+ ctrl.navigate(&format!("{base}/visible")).await.unwrap();
+ assert_eq!(title_becomes(&ctrl, "visible").await, "visible");
+
+ let attachment_id = upload(&e.state, "retry.mp4", b"\0\0\0\x18ftypisom\0\0\x02\0isomiso2mp41 the one that should land on retry").await;
+ let (mut ws, server) = connect(&e.state, &e.bot.id).await;
+ assert!(next_message(&mut ws, "frame", |_| true).await.is_some());
+ take_control(&mut ws).await;
+
+ ws.send(WsMessage::Text(json!({"action": "click", "x": 40, "y": 40, "id": 1}).to_string())).await.unwrap();
+ let opened = next_message(&mut ws, "file_chooser", |_| true).await.expect("chooser opened");
+ let chooser_id = opened["id"].clone();
+
+ // First answer: an unknown attachment id, a recoverable failure (not "gone").
+ ws.send(WsMessage::Text(json!({"action": "file_chooser", "id": chooser_id, "attachment_ids": ["00000000-0000-4000-8000-000000000000"]}).to_string())).await.unwrap();
+ let failed = next_message(&mut ws, "file_chooser_error", |_| true).await.expect("an unknown id is refused");
+ assert_eq!(failed["code"], "failed");
+ assert_eq!(failed["id"], chooser_id);
+
+ // Retry with the same chooser id and a real attachment: it must be delivered, not "gone".
+ ws.send(WsMessage::Text(json!({"action": "file_chooser", "id": chooser_id, "attachment_ids": [attachment_id]}).to_string())).await.unwrap();
+ let done = next_message(&mut ws, "file_chooser_done", |_| true).await.expect("the retry is answered, not left as gone");
+ assert_eq!(done["id"], chooser_id);
+ assert_eq!(done["names"], json!(["retry.mp4"]));
+ assert_eq!(title_becomes(&ctrl, "picked:retry.mp4").await, "picked:retry.mp4", "the page actually got the file on retry");
+
+ ws.close(None).await.unwrap();
+ server.abort();
+}
+
+#[tokio::test]
+async fn navigating_away_while_the_sheet_is_open_clears_it() {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let e = setup().await;
+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));
+ let base = serve().await;
+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");
+ ctrl.navigate(&format!("{base}/visible")).await.unwrap();
+ assert_eq!(title_becomes(&ctrl, "visible").await, "visible");
+
+ let attachment_id = upload(&e.state, "late.mp4", b"\0\0\0\x18ftypisom\0\0\x02\0isomiso2mp41 arrives after the page already moved on").await;
+ let (mut ws, server) = connect(&e.state, &e.bot.id).await;
+ assert!(next_message(&mut ws, "frame", |_| true).await.is_some());
+ take_control(&mut ws).await;
+
+ ws.send(WsMessage::Text(json!({"action": "click", "x": 40, "y": 40, "id": 1}).to_string())).await.unwrap();
+ let opened = next_message(&mut ws, "file_chooser", |_| true).await.expect("chooser opened");
+
+ ctrl.send_cdp_command("Page.navigate", json!({"url": format!("{base}/plain")})).await.expect("navigate away while the sheet is still open");
+ let gone = next_message(&mut ws, "file_chooser_error", |_| true).await.expect("the sheet is told the chooser is gone");
+ assert_eq!(gone["code"], "gone");
+
+ // Answering the now-stale id gets the same "gone" treatment, not a generic protocol error.
+ ws.send(WsMessage::Text(json!({"action": "file_chooser", "id": opened["id"], "attachment_ids": [attachment_id]}).to_string())).await.unwrap();
+ let stale = next_message(&mut ws, "file_chooser_error", |_| true).await.expect("answering a cleared chooser still gets a file_chooser_error");
+ assert_eq!(stale["code"], "gone");
+
+ ws.close(None).await.unwrap();
+ server.abort();
+}