The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Chat: a picture opens in a light viewer, closed with Esc, a click beside it or ×; Download in its right-click menu (#279)
Rick4021feca73a0
diff --git a/.changeset/light-picture-viewer.md b/.changeset/light-picture-viewer.mdnew file mode 100644index 0000000..6c93c11--- /dev/null+++ b/.changeset/light-picture-viewer.md@@ -0,0 +1,5 @@+---+"@openfilm/desktop": patch+---++A picture opened in the chat opens in a light viewer: the window dims, the picture shows at its own size in the middle (at most nine tenths of the window), and Esc, a click beside it or × closes it. Download is in its right-click menu. The full-window frame with its name, size, Fit / 100% and Download is gone for pictures; video, sound and documents open as before. An Esc pressed just after one that closed a viewer no longer stops the running turn.diff --git a/apps/desktop/bench/attachment-preview.test.mjs b/apps/desktop/bench/attachment-preview.test.mjsnew file mode 100644index 0000000..85595d8--- /dev/null+++ b/apps/desktop/bench/attachment-preview.test.mjs@@ -0,0 +1,107 @@+/** The light picture viewer through the real component: closes three ways, Download only in its right-click menu. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { createServer } from 'vite';+import { chromium } from 'playwright-core';+import shellConfig from '../shell/vite.config.ts';++test('a picture opens in a light viewer: dimmed window, picture centered at its own size, Esc, a click beside it or × close it, Download in its right-click menu', { timeout: 60_000 }, async () => {+ const server = await createServer({+ ...shellConfig, configFile: false, root: fileURLToPath(new URL('..', import.meta.url)),+ server: { host: '127.0.0.1', port: 0 }, logLevel: 'error',+ plugins: [...shellConfig.plugins, {+ name: 'attachment-preview-fixture',+ configureServer(app) {+ app.middlewares.use('/attachment-preview', (_req, res, next) => {+ res.setHeader('content-type', 'text/html');+ void app.transformIndexHtml('/attachment-preview', '<!doctype html><html><body><div id="root"></div><script type="module" src="/bench/attachment-preview.tsx"></script></body></html>')+ .then((html) => res.end(html), next);+ });+ },+ }],+ });+ let browser;+ try {+ await server.listen();+ browser = await chromium.launch({ headless: true });+ const page = await browser.newPage({ viewport: { width: 1200, height: 800 }, reducedMotion: 'reduce' });+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/attachment-preview`);+ const open = (which) => page.evaluate((w) => window.attachmentPreviewFixture.open(w), which);+ const dialog = page.getByRole('dialog', { name: 'screenshot.png' });+ const picture = dialog.getByRole('img', { name: 'screenshot.png' });++ await open('picture');+ await picture.waitFor();+ const box = await picture.boundingBox();+ assert.deepEqual([Math.round(box.width), Math.round(box.height)], [600, 400], 'at its own size, not enlarged to the window');+ assert.ok(Math.abs(box.x + box.width / 2 - 600) < 2, 'centered across the window');+ assert.match(await dialog.evaluate((el) => getComputedStyle(el).backgroundColor), /^(?:rgba\(0, 0, 0, |oklab\(0 0 0 \/ )0\.75\)$/, 'the window behind is dimmed');+ assert.equal(await dialog.getByText(/Fit|100%/).count(), 0, 'no Fit / 100% bar');+ assert.equal(await dialog.getByRole('link', { name: 'Download' }).count(), 0, 'no Download until the right-click menu');++ await picture.click({ button: 'right' });+ const download = page.getByRole('menuitem', { name: 'Download' });+ await download.waitFor();+ assert.equal(await download.getAttribute('download'), 'screenshot.png');+ await page.keyboard.press('Escape');+ await download.waitFor({ state: 'hidden' });+ assert.equal(await dialog.isVisible(), true, 'Esc closes the menu first');+ await page.keyboard.press('Escape');+ await dialog.waitFor({ state: 'hidden' });++ /* from the keyboard: the menu key on the picture, its Download focused; Tab stays inside */+ await open('picture');+ await picture.waitFor();+ assert.equal(await picture.evaluate((el) => el === document.activeElement), true, 'the picture has the keys');+ await page.keyboard.press('Shift+F10');+ await download.waitFor();+ assert.equal(await download.evaluate((el) => el === document.activeElement), true, 'its Download focused');+ await page.keyboard.press('Escape');+ await download.waitFor({ state: 'hidden' });+ for (let i = 0; i < 4; i++) {+ await page.keyboard.press(i % 2 ? 'Shift+Tab' : 'Tab');+ assert.equal(await dialog.evaluate((el) => el.contains(document.activeElement)), true, 'Tab stays in the viewer');+ }+ /* right-clicked by the window's edge: the menu stays inside it */+ await page.mouse.click(1195, 795, { button: 'right' });+ await page.mouse.click(895, 595, { button: 'right' });+ const menuBox = await page.getByRole('menu').boundingBox();+ assert.ok(menuBox.x + menuBox.width <= 1200 && menuBox.y + menuBox.height <= 800, 'the menu inside the window');+ await page.keyboard.press('Escape');+ /* a press begun on the picture and let go beside it does not close it */+ const at = await picture.boundingBox();+ await page.mouse.move(at.x + 20, at.y + 20);+ await page.mouse.down();+ await page.mouse.move(20, 780);+ await page.mouse.up();+ assert.equal(await dialog.isVisible(), true, 'a drag out of the picture keeps it open');+ await page.keyboard.press('Escape');+ await dialog.waitFor({ state: 'hidden' });++ await open('picture');+ await picture.click();+ assert.equal(await dialog.isVisible(), true, 'a click on the picture keeps it open');+ await page.mouse.click(20, 780);+ await dialog.waitFor({ state: 'hidden' });++ await open('picture');+ const close = await dialog.getByRole('button', { name: 'Close' }).boundingBox();+ assert.ok(close.x + close.width > 1150 && close.y < 60, 'the × at the top right');+ await dialog.getByRole('button', { name: 'Close' }).click();+ await dialog.waitFor({ state: 'hidden' });++ await open('thumb');+ await picture.waitFor();+ assert.equal(await dialog.getByText(/A thumbnail kept with the message/).isVisible(), true, 'a thumbnail says so');+ await picture.click({ button: 'right' });+ assert.equal(await page.getByRole('menuitem', { name: 'Download' }).count(), 0, 'a thumbnail has no Download: it would pass for the original');+ if (process.env.OPENFILM_PREVIEW_SHOT) await page.screenshot({ path: process.env.OPENFILM_PREVIEW_SHOT });+ await page.keyboard.press('Escape');+ await dialog.waitFor({ state: 'hidden' });+ assert.deepEqual(errors, []);+ } finally { await browser?.close(); await server.close(); }+});diff --git a/apps/desktop/bench/attachment-preview.tsx b/apps/desktop/bench/attachment-preview.tsxnew file mode 100644index 0000000..2547651--- /dev/null+++ b/apps/desktop/bench/attachment-preview.tsx@@ -0,0 +1,38 @@+/** The real attachment preview over a page of its own: a picture, its thumbnail kept with a sent message, and a video. */+import React from 'react';+import { createRoot } from 'react-dom/client';+import { AttachmentPreview, type AttachmentPreviewItem } from '../chat/src/components/AttachmentPreview';+import '../shell/shell.css';+import '../chat/src/chat.css';++/* a 600 × 400 picture, drawn here so the fixture needs no file */+const canvas = document.createElement('canvas');+canvas.width = 600;+canvas.height = 400;+const g = canvas.getContext('2d')!;+g.fillStyle = '#2b6cb0';+g.fillRect(0, 0, 600, 400);+g.fillStyle = '#fff';+g.fillRect(40, 40, 200, 120);+const picture = canvas.toDataURL('image/png');++const items: Record<string, AttachmentPreviewItem> = {+ picture: { name: 'screenshot.png', kind: 'image', url: picture, mediaType: 'image/png' },+ thumb: { name: 'screenshot.png', kind: 'image', url: picture, mediaType: 'image/png', thumbOnly: true },+};++function Fixture() {+ const [open, setOpen] = React.useState<string | null>(null);+ (window as any).attachmentPreviewFixture = { open: setOpen, opened: () => open };+ return (+ <>+ <div className="of-chat" style={{ padding: 16 }}>+ <button type="button" id="behind">Behind</button>+ </div>+ {open ? <AttachmentPreview item={items[open]!} onClose={() => setOpen(null)} /> : null}+ <div id="of-chat-layer" className="of-chat" />+ </>+ );+}++createRoot(document.getElementById('root')!).render(<Fixture />);diff --git a/apps/desktop/chat/src/components/AttachmentPreview.tsx b/apps/desktop/chat/src/components/AttachmentPreview.tsxindex 1e5f862..a242a14 100644--- a/apps/desktop/chat/src/components/AttachmentPreview.tsx+++ b/apps/desktop/chat/src/components/AttachmentPreview.tsx@@ -8,8 +8,13 @@* than show a broken preview.*/import React from 'react';-import { Download } from 'lucide-react';+import { createPortal } from 'react-dom';+import { Download, X } from 'lucide-react';import { PREVIEW_BTN, PreviewFrame, previewMediaFit } from './PreviewFrame';+import { POPOVER_CHROME } from './ComposerCard';+import { chatLayer } from '@/lib/chat-layer';+import { escTaken } from '@/lib/esc-stop';+import { previewTop } from '@/lib/preview-top';import { Tooltip } from './Tooltip';import { attachmentIcon, attachmentKind } from '@/lib/project-resources';import { useT } from '@/i18n';@@ -123,36 +128,33 @@ export function AttachmentPreview({}) {const t = useT();const body = bodyOf(item);- if (body === 'image' && !item.thumbOnly) return <OriginalImagePreview key={item.url} item={item} onClose={onClose} />;+ /* a picture, the original or the thumbnail kept with a sent message: the light viewer */+ if (body === 'image') return <ImageViewer key={item.url} item={item} onClose={onClose} />;const Icon = attachmentIcon(item);- /* The two kinds with their own shape. Audio and documents get a fixed reading area. */- const onStage = body === 'image' || body === 'video';+ /* Video has its own shape. Audio and documents get a fixed reading area. */+ const onStage = body === 'video';return (<PreviewFramename={item.name}onClose={onClose}icon={<Icon size={15} className="shrink-0 text-white/45" />}- /* Images and video fit their own shape, so the black backdrop hugs the picture; a light- surround makes a frame look darker. Text gets a fixed reading area on the paper- color, laid out from the top left, not centered. */+ /* Video fits its own shape, so the black backdrop hugs the picture; a light surround+ makes a frame look darker. Text gets a fixed reading area on the paper color, laid+ out from the top left, not centered. */fit={onStage}bodyClassName={onStage ? 'bg-black' : 'bg-[var(--surface-2)]'}actions={- /* No download for a thumbnail: a 320px copy under the original's name would be- mistaken for the original. */- item.thumbOnly ? null : (- <Tooltip label={t('assets.download')} side="bottom">- <a- href={item.url}- download={item.name}- aria-label={t('assets.download')}- className={`${PREVIEW_BTN} w-8 px-0`}- >- <Download size={14} />- </a>- </Tooltip>- )+ <Tooltip label={t('assets.download')} side="bottom">+ <a+ href={item.url}+ download={item.name}+ aria-label={t('assets.download')}+ className={`${PREVIEW_BTN} w-8 px-0`}+ >+ <Download size={14} />+ </a>+ </Tooltip>}><div@@ -162,43 +164,122 @@ export function AttachmentPreview({><PreviewBody item={item} body={body} /></div>- {item.thumbOnly && (- <p className="shrink-0 border-t border-[var(--border)] px-4 py-2 text-[11.5px] text-[var(--text-faint)]">- {t('composer.thumbOnly')}- </p>- )}</PreviewFrame>);}-/** Uses the original file URL in both modes; 1:1 never stretches a thumbnail. */-function OriginalImagePreview({ item, onClose }: { item: AttachmentPreviewItem; onClose: () => void }) {+/**+ * A picture opened to look at it: the window dimmed, the picture at its own size in the middle (at most nine tenths of+ * the window, never enlarged), a × to close; Esc and a click beside it close it too. Downloading it is in its+ * right-click menu, which the keyboard opens too (the menu key, Shift+F10). A thumbnail kept with a sent message says+ * so under it, and has no Download: a 320px copy under the original's name would be taken for the original.+ */+function ImageViewer({ item, onClose }: { item: AttachmentPreviewItem; onClose: () => void }) {const t = useT();- const [actualSize, setActualSize] = React.useState(false);- const [size, setSize] = React.useState<{ w: number; h: number } | null>(null);- return (- <PreviewFrame name={item.name} onClose={onClose} bodyClassName="bg-black"- actions={<>- {size ? <span className="mr-2 hidden text-[11px] tabular-nums text-white/45 sm:block">{size.w} × {size.h}</span> : null}- <div className="flex rounded-lg bg-white/5 p-0.5">- <button type="button" aria-pressed={!actualSize} onClick={() => setActualSize(false)}- className={`${PREVIEW_BTN} ${!actualSize ? 'bg-white/10 text-white' : ''}`}>{t('assets.imageFit')}</button>- <button type="button" aria-label={t('assets.imageActualSize')} aria-pressed={actualSize} onClick={() => setActualSize(true)}- className={`${PREVIEW_BTN} ${actualSize ? 'bg-white/10 text-white' : ''}`}>100%</button>+ /** where its right-click menu is open, or null */+ const [menu, setMenu] = React.useState<{ x: number; y: number } | null>(null);+ const box = React.useRef<HTMLDivElement>(null);+ const picture = React.useRef<HTMLImageElement>(null);+ const menuBox = React.useRef<HTMLDivElement>(null);+ /** a press that began on the backdrop: only such a click closes it, not one dragged out of the picture */+ const pressedBeside = React.useRef(false);+ const closeRef = React.useRef(onClose);+ closeRef.current = onClose;+ const menuRef = React.useRef(menu);+ menuRef.current = menu;+ const top = previewTop(navigator.platform);+ React.useEffect(() => {+ const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;+ /* the picture takes the keys, so its menu key opens its menu */+ (picture.current ?? box.current)?.focus({ preventScroll: true });+ const onKey = (event: KeyboardEvent) => {+ /* Esc closes the menu first, then the picture; nothing under it takes the key */+ if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ escTaken(event);+ if (menuRef.current) { setMenu(null); picture.current?.focus({ preventScroll: true }); } else closeRef.current();+ return;+ }+ /* Tab goes round what is here, never to the chat behind it (as PreviewFrame's) */+ if (event.key !== 'Tab') return;+ const targets = Array.from(box.current?.querySelectorAll<HTMLElement>('button, a[href], [tabindex="0"]') ?? []).filter((el) => el.getClientRects().length > 0);+ const first = targets[0];+ const last = targets.at(-1);+ if (!first) { event.preventDefault(); return; }+ if (event.shiftKey && (document.activeElement === first || document.activeElement === box.current)) { event.preventDefault(); last?.focus(); }+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }+ };+ window.addEventListener('keydown', onKey, true);+ return () => {+ window.removeEventListener('keydown', onKey, true);+ if (previous?.isConnected) previous.focus({ preventScroll: true });+ };+ }, []);+ /* the menu inside the window, however near its edge it was opened; its item focused, for the keyboard */+ React.useLayoutEffect(() => {+ const el = menuBox.current;+ if (!menu || !el) return;+ const { width, height } = el.getBoundingClientRect();+ const x = Math.max(8, Math.min(menu.x, window.innerWidth - width - 8));+ const y = Math.max(8, Math.min(menu.y, window.innerHeight - height - 8));+ if (x !== menu.x || y !== menu.y) setMenu({ x, y });+ el.querySelector<HTMLElement>('[role="menuitem"]')?.focus({ preventScroll: true });+ }, [menu]);+ /** the menu where it was asked for: at the pointer, or, from the keyboard, the picture's middle */+ const openMenu = (event: React.MouseEvent) => {+ event.preventDefault();+ event.stopPropagation();+ if (item.thumbOnly) return;+ const rect = picture.current?.getBoundingClientRect();+ const onPicture = rect && event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;+ if (onPicture) setMenu({ x: event.clientX, y: event.clientY });+ else if (rect) setMenu({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 });+ };++ if (typeof document === 'undefined') return null;+ return createPortal(+ <div ref={box} tabIndex={-1} role="dialog" aria-modal="true" aria-label={item.name}+ className="fixed inset-0 z-[10100] flex flex-col items-center justify-center gap-3 bg-black/75 outline-none"+ style={{ paddingTop: top, WebkitAppRegion: 'no-drag' } as React.CSSProperties}+ onPointerDown={(event) => { pressedBeside.current = event.target === event.currentTarget; }}+ onClick={(event) => {+ if (menu) { setMenu(null); return; }+ if (event.target === event.currentTarget && pressedBeside.current) onClose();+ }}+ onContextMenu={(event) => { event.preventDefault(); setMenu(null); }}>+ <button type="button" onClick={onClose} aria-label={t('assets.close')}+ className="absolute right-4 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-black/40 text-white/80 transition hover:bg-black/60 hover:text-white"+ /* below the window's own buttons, which Windows draws over the top right (preview-top) */+ style={{ top }}>+ <X size={16} />+ </button>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img ref={picture} src={item.url} alt={item.name} draggable={false} tabIndex={0}+ className="block max-w-[90vw] object-contain shadow-2xl outline-none focus-visible:ring-2 focus-visible:ring-white/60"+ /* nine tenths of the window, less the room above it and the thumbnail's note under it */+ style={{ maxHeight: `calc(90vh - ${top}${item.thumbOnly ? ' - 3rem' : ''})` }}+ onClick={(event) => { event.stopPropagation(); setMenu(null); }}+ onContextMenu={openMenu}+ /* the menu key and Shift+F10 open it on every system: macOS's browser makes no right-click of them */+ onKeyDown={(event) => {+ if (event.key !== 'ContextMenu' && !(event.key === 'F10' && event.shiftKey)) return;+ event.preventDefault();+ const rect = picture.current?.getBoundingClientRect();+ if (rect && !item.thumbOnly) setMenu({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 });+ }} />+ {item.thumbOnly ? <p className="max-w-[90vw] text-center text-[11.5px] text-white/60">{t('composer.thumbOnly')}</p> : null}+ {menu ? (+ <div ref={menuBox} role="menu" className="fixed min-w-[140px] p-1" style={{ ...POPOVER_CHROME, left: menu.x, top: menu.y }}+ onClick={(event) => event.stopPropagation()}>+ <a role="menuitem" href={item.url} download={item.name} onClick={() => setMenu(null)}+ className="flex h-7 items-center gap-2 rounded-[6px] px-2 text-[13px] text-[var(--text)] outline-none hover:bg-[var(--bg-hover)] focus-visible:bg-[var(--bg-hover)]">+ <Download size={13} />{t('assets.download')}+ </a></div>- <Tooltip label={t('assets.download')} side="bottom">- <a href={item.url} download={item.name} aria-label={t('assets.download')} className={`${PREVIEW_BTN} w-8 px-0`}><Download size={14} /></a>- </Tooltip>- </>}>- <div className="flex h-full min-h-0 w-full overflow-auto overscroll-contain">- {/* eslint-disable-next-line @next/next/no-img-element */}- <img src={item.url} alt={item.name} className="m-auto block shrink-0 object-contain"- onLoad={event => setSize({ w: event.currentTarget.naturalWidth, h: event.currentTarget.naturalHeight })}- style={actualSize && size- ? { width: size.w, height: size.h, maxWidth: 'none', maxHeight: 'none' }- : { maxWidth: '100%', maxHeight: '100%', width: 'auto', height: 'auto' }} />- </div>- </PreviewFrame>+ ) : null}+ </div>,+ chatLayer(),);}@@ -206,19 +287,6 @@ function PreviewBody({ item, body }: { item: AttachmentPreviewItem; body: Body }const t = useT();const pdfUrl = useBlobUrl(item.url, body === 'pdf');- if (body === 'image') {- return (- // eslint-disable-next-line @next/next/no-img-element- <img- src={item.url}- alt={item.name}- /* Only maximums, no size: the box is the picture at its own ratio, and a thumbnail- is never scaled up into a blur. */- style={previewMediaFit()}- className={item.thumbOnly ? 'p-6' : undefined}- />- );- }if (body === 'video') return <VideoPreview item={item} />;if (body === 'audio') return <AudioPreview item={item} />;if (body === 'pdf') {diff --git a/apps/desktop/chat/src/components/PreviewFrame.tsx b/apps/desktop/chat/src/components/PreviewFrame.tsxindex 6278108..72cb55e 100644--- a/apps/desktop/chat/src/components/PreviewFrame.tsx+++ b/apps/desktop/chat/src/components/PreviewFrame.tsx@@ -1,6 +1,6 @@'use client';-/** A stable, contained preview workspace for media and documents. */+/** A stable, contained preview workspace for video, audio and documents (pictures have their own light viewer). */import React from 'react';import { createPortal } from 'react-dom';import { X } from 'lucide-react';@@ -8,6 +8,7 @@ import { Tooltip } from './Tooltip';import { useT } from '@/i18n';import { chatLayer } from '@/lib/chat-layer';import { previewTop } from '@/lib/preview-top';+import { escTaken } from '@/lib/esc-stop';/** A button in the top bar. The lightbox is black, so these use shades of white rather than the UI tokens. */export const PREVIEW_BTN =@@ -21,20 +22,16 @@ const AREA_STYLE = {} as React.CSSProperties;/**- * In `fit` mode, the size of an image or video's own box.+ * In `fit` mode, the size of a video's own box, `w`×`h` its frame (or a guess until its metadata arrives).*- * By default only maximums, no size: the element's box is the picture itself (small images aren't enlarged, large- * ones shrink to fit), the outer box hugs it, and the picture shows at its own aspect ratio.- *- * Given dimensions, the width is set too. A `<video>` reports 300×150 until its metadata arrives, and the box hugs- * it, so without a width it flashes a small box before jumping to size. The width is computed as contain up front- * and the height follows from aspect-ratio, so the first frame is final.+ * A `<video>` reports 300×150 until then, and the box hugs it, so without a width it flashes a small box before+ * jumping to size. The width is computed as contain up front and the height follows from aspect-ratio, so the first+ * frame is final.*/-export function previewMediaFit(w?: number, h?: number): React.CSSProperties {- const cap = { maxWidth: 'var(--preview-w)', maxHeight: 'var(--preview-h)' };- if (!(w && h && w > 0 && h > 0)) return cap;+export function previewMediaFit(w: number, h: number): React.CSSProperties {return {- ...cap,+ maxWidth: 'var(--preview-w)',+ maxHeight: 'var(--preview-h)',aspectRatio: `${w} / ${h}`,width: `min(var(--preview-w), calc(var(--preview-h) * ${w} / ${h}))`,};@@ -57,7 +54,7 @@ export function PreviewFrame({icon?: React.ReactNode;/** Buttons at the top right. The close button is added here, no need to pass it. */actions?: React.ReactNode;- /** The content box's classes: black behind images and video, paper behind text. */+ /** The content box's classes: black behind video, paper behind text. */bodyClassName?: string;/** Keep naturally sized content centered; documents and resource players fill the viewport. */fit?: boolean;@@ -75,9 +72,11 @@ export function PreviewFrame({box.current?.focus({ preventScroll: true });const onKey = (event: KeyboardEvent) => {if (event.key === 'Escape') {- if (document.fullscreenElement) return;+ /* it leaves the video's full screen, and is the viewer's all the same */+ if (document.fullscreenElement) { escTaken(event); return; }event.preventDefault();event.stopPropagation();+ escTaken(event);closeRef.current();}if (event.key !== 'Tab') return;diff --git a/apps/desktop/chat/src/i18n/locales/en-US.ts b/apps/desktop/chat/src/i18n/locales/en-US.tsindex 374e697..6a47c04 100644--- a/apps/desktop/chat/src/i18n/locales/en-US.ts+++ b/apps/desktop/chat/src/i18n/locales/en-US.ts@@ -125,8 +125,6 @@ export const enUS = {assets: {close: 'Close',download: 'Download',- imageActualSize: 'Original size',- imageFit: 'Fit',noPreview: 'This file type cannot be previewed here — download it instead',previewFailed: 'This file could not be read',},diff --git a/apps/desktop/chat/src/i18n/locales/es.ts b/apps/desktop/chat/src/i18n/locales/es.tsindex 84e1b5b..d6bcc9f 100644--- a/apps/desktop/chat/src/i18n/locales/es.ts+++ b/apps/desktop/chat/src/i18n/locales/es.ts@@ -125,8 +125,6 @@ export const es: Words = {assets: {close: 'Cerrar',download: 'Descargar',- imageActualSize: 'Tamaño original',- imageFit: 'Ajustar',noPreview: 'Este tipo de archivo no se puede previsualizar aquí: descárgalo',previewFailed: 'No se pudo leer este archivo',},diff --git a/apps/desktop/chat/src/i18n/locales/ja.ts b/apps/desktop/chat/src/i18n/locales/ja.tsindex 09f6a39..eb75d76 100644--- a/apps/desktop/chat/src/i18n/locales/ja.ts+++ b/apps/desktop/chat/src/i18n/locales/ja.ts@@ -125,8 +125,6 @@ export const ja: Words = {assets: {close: '閉じる',download: 'ダウンロード',- imageActualSize: '原寸',- imageFit: '全体を表示',noPreview: 'この種類のファイルはここでプレビューできません。ダウンロードしてください',previewFailed: 'このファイルを読み込めませんでした',},diff --git a/apps/desktop/chat/src/i18n/locales/ko.ts b/apps/desktop/chat/src/i18n/locales/ko.tsindex eb0e8de..8aa7d0b 100644--- a/apps/desktop/chat/src/i18n/locales/ko.ts+++ b/apps/desktop/chat/src/i18n/locales/ko.ts@@ -121,8 +121,6 @@ export const ko: Words = {assets: {close: '닫기',download: '다운로드',- imageActualSize: '원본 크기',- imageFit: '화면에 맞춤',noPreview: '이 파일 형식은 여기서 미리 볼 수 없습니다. 대신 다운로드하세요',previewFailed: '이 파일을 읽을 수 없습니다',},diff --git a/apps/desktop/chat/src/i18n/locales/zh-CN.ts b/apps/desktop/chat/src/i18n/locales/zh-CN.tsindex 4b83fdc..9154471 100644--- a/apps/desktop/chat/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/chat/src/i18n/locales/zh-CN.ts@@ -125,8 +125,6 @@ export const zhCN: Words = {assets: {close: '关闭',download: '下载',- imageActualSize: '原始尺寸',- imageFit: '适应窗口',noPreview: '此类文件无法在这里预览,请下载后查看',previewFailed: '无法读取此文件',},diff --git a/apps/desktop/chat/src/lib/esc-stop.ts b/apps/desktop/chat/src/lib/esc-stop.tsindex 23a2aa8..a940c1f 100644--- a/apps/desktop/chat/src/lib/esc-stop.ts+++ b/apps/desktop/chat/src/lib/esc-stop.ts@@ -2,7 +2,8 @@* Which Esc stops the turn while it runs (the send button's other half): one pressed in the chat (chat-layer.ts* `inChat`). One in Studio closes Studio's menu or dialog, and one already handled is its handler's; neither stops the* agent. Nor does an Esc held down, or pressed again just after one of those: Studio's Settings gives the focus back to- * the chat as it closes, so the key held, or pressed twice to close it, would land in the chat and stop the agent.+ * the chat as it closes, so the key held, or pressed twice to close it, would land in the chat and stop the agent. The+ * chat's own viewers (a picture, a file) keep their Esc from everything under them, so they say so with `escTaken`.** Pure: no React, no bridge, so `node --test` runs it (src/esc-stop.test.mjs).*/@@ -12,12 +13,19 @@ export const ESC_AGAIN_MS = 1000;type EscKey = Pick<KeyboardEvent, 'key' | 'repeat' | 'defaultPrevented' | 'timeStamp'>;+let takenAt = -Infinity;++/** An Esc a viewer closed on and kept from the rest of the chat: the next one, just after, is still closing. */+export function escTaken(event: Pick<KeyboardEvent, 'timeStamp'>): void {+ takenAt = event.timeStamp;+}+/** Hears every key pressed (`inChat`: where it was) and says whether it stops the turn. */export function escStopper(): (event: EscKey, inChat: boolean) => boolean {let elsewhereAt = -Infinity;return (event, inChat) => {if (event.key !== 'Escape') return false;if (event.defaultPrevented || !inChat) { elsewhereAt = event.timeStamp; return false; }- return !event.repeat && event.timeStamp - elsewhereAt >= ESC_AGAIN_MS;+ return !event.repeat && event.timeStamp - Math.max(elsewhereAt, takenAt) >= ESC_AGAIN_MS;};}diff --git a/apps/desktop/src/esc-stop.test.mjs b/apps/desktop/src/esc-stop.test.mjsindex 2d86601..16380a5 100644--- a/apps/desktop/src/esc-stop.test.mjs+++ b/apps/desktop/src/esc-stop.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { ESC_AGAIN_MS, escStopper } from '../chat/src/lib/esc-stop.ts';+import { ESC_AGAIN_MS, escStopper, escTaken } from '../chat/src/lib/esc-stop.ts';const esc = (timeStamp, more = {}) => ({ key: 'Escape', repeat: false, defaultPrevented: false, timeStamp, ...more });@@ -31,3 +31,12 @@ test('an Esc held down, or one already handled in the chat, does not stop the tuassert.equal(stops(esc(8200), true), false);assert.equal(stops(esc(10000), true), true);});++/* last: what a viewer took is kept for the whole module, so it comes after the times the tests above use */+test('an Esc in the chat just after one that closed a picture or file viewer does not stop the turn; one a while later does', () => {+ const stops = escStopper();+ /* the viewer took the first, so the chat never heard it */+ escTaken(esc(20000));+ assert.equal(stops(esc(20300), true), false);+ assert.equal(stops(esc(20000 + ESC_AGAIN_MS), true), true);+});