diff --git a/temp-screenshots/optimize-cancel/desktop-optimizing.png b/temp-screenshots/optimize-cancel/desktop-optimizing.png new file mode 100644 index 000000000000..2b3e986df3d5 Binary files /dev/null and b/temp-screenshots/optimize-cancel/desktop-optimizing.png differ diff --git a/temp-screenshots/optimize-cancel/mobile-after-cancel.png b/temp-screenshots/optimize-cancel/mobile-after-cancel.png new file mode 100644 index 000000000000..5fa458be61e3 Binary files /dev/null and b/temp-screenshots/optimize-cancel/mobile-after-cancel.png differ diff --git a/temp-screenshots/optimize-cancel/mobile-optimizing.png b/temp-screenshots/optimize-cancel/mobile-optimizing.png new file mode 100644 index 000000000000..1981c2274884 Binary files /dev/null and b/temp-screenshots/optimize-cancel/mobile-optimizing.png differ diff --git a/website/playwright/optimize-cancel-mobile.spec.ts b/website/playwright/optimize-cancel-mobile.spec.ts new file mode 100644 index 000000000000..79f3a31ee7a7 --- /dev/null +++ b/website/playwright/optimize-cancel-mobile.spec.ts @@ -0,0 +1,131 @@ +import { test, expect, type Page, type Route } from '@playwright/test' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { json, stubDashboardApi } from '../scripts/lib/stub-dashboard-api.mjs' + +/** + * On a phone, the "Optimizing prompt..." overlay shows a visible, tappable + * Cancel while the optimize runs, and a tap gives back the draft, editable. + * + * Pearce hit this on iPhone Safari (#20003, handoff 11bb0734): the composer + * showed only the status, with no way out. Touch screens get no title tooltip, + * so under a coarse pointer the X grows into a labelled "Cancel" chip with a + * 44px touch target. jsdom evaluates no media queries and computes no layout, + * so only a real browser can check that the label is shown and the target is + * big enough. ChatInput.optimizeCancel.test.tsx pins the abort and late-result + * behaviour; this spec pins what a finger can see and hit. + * + * The phone runs at 390x844 and again at 390x480, the height left above the + * soft keyboard, because the overlay must stay usable while the keyboard is up. + * A desktop control keeps the 28px icon-only X with its tooltip. + */ + +const catalog = (name: string) => JSON.parse(readFileSync(fileURLToPath(new URL(`../src/i18n/locales/${name}`, import.meta.url)), 'utf8')) +const manual = catalog('en.manual.json') +const generated = catalog('en.json') +const label = (key: string): string => { + const value = manual.components.chatInput[key] ?? generated.components?.chatInput?.[key] + if (typeof value !== 'string') throw new Error(`Missing English fixture label: components.chatInput.${key}`) + return value +} +const CANCEL_NAME = label('cancel_optimizing') +const CANCEL_LABEL = label('cancel_optimizing_short') +const OPTIMIZING = label('optimizing_prompt') +const SLOT = 'optimize-cancel-fixture' +const DRAFT = 'look at the failing build and tell me what broke' +const TOUCH_TARGET_PX = 44 + +async function openComposer(page: Page, baseURL: string) { + const errors: string[] = [] + page.on('pageerror', error => errors.push(error.message)) + await page.route('**/*', route => new URL(route.request().url()).origin === new URL(baseURL).origin + ? route.continue() : route.abort('blockedbyclient')) + const optimize = { requests: 0 } + await stubDashboardApi(page, { + localStorageEntries: { 'mc-lang': 'en', 'mc-active-slot': SLOT, 'mc-active-slot-chat': SLOT }, + slots: [{ key: SLOT, title: 'Build triage', running: false, messages: 2, + agent: 'kirocrew', memory_mode: 'persistent', project: '', folder_id: '', + modified: 1788780000, source_links: [], source_links_total: 0 }], + extra: async (path: string, route: Route) => { + if (path === `/api/chat/slots/${SLOT}`) { + await json(route, { running: false, has_more: false, total: 2, queue: [], project: '', messages: [ + { role: 'user', ts: 1788780000, content: 'Hi' }, + { role: 'assistant', ts: 1788780030, content: 'Ready.' }, + ] }) + } else if (path === `/api/chat/slots/${SLOT}/source-links`) { + await json(route, { links: [], total: 0 }) + } else if (path.startsWith('/api/optimizer/optimize')) { + // Never answered: only the page's abort ends the request. + optimize.requests++ + } else return false + return true + }, + }) + const response = await page.goto(`/?slot=${SLOT}`, { waitUntil: 'domcontentloaded' }) + expect(response?.ok()).toBe(true) + // The composer is what this spec drives; the transcript is incidental. + await expect(page.locator('textarea[data-composer-input]')).toBeVisible() + return { errors, optimize } +} + +async function startOptimize(page: Page, touch: boolean) { + const composer = page.locator('textarea[data-composer-input]') + await composer.fill(DRAFT) + const optimizeButton = page.getByRole('button', { name: 'Optimize prompt' }).first() + if (touch) await optimizeButton.tap() + else await optimizeButton.click() + await expect(page.getByText(OPTIMIZING)).toBeVisible() + return composer +} + +for (const height of [844, 480]) { + test.describe(`Phone ${390}x${height}: optimize overlay Cancel`, () => { + test.use({ viewport: { width: 390, height }, hasTouch: true, isMobile: true, reducedMotion: 'reduce' }) + + test('shows a labelled 44px Cancel and a tap returns the draft, editable', async ({ page, baseURL }) => { + const { errors, optimize } = await openComposer(page, baseURL!) + const composer = await startOptimize(page, true) + // The overlay paints on the mutation's start; the fetch can follow it. + await expect.poll(() => optimize.requests).toBe(1) + + const cancel = page.getByRole('button', { name: CANCEL_NAME }) + await expect(cancel).toBeVisible() + await expect(cancel.getByText(CANCEL_LABEL, { exact: true })).toBeVisible() + await expect(cancel).toBeInViewport({ ratio: 1 }) + const box = (await cancel.boundingBox())! + expect(box.height).toBeGreaterThanOrEqual(TOUCH_TARGET_PX) + expect(box.width).toBeGreaterThanOrEqual(TOUCH_TARGET_PX) + // A hit test at the button's centre lands on the button, not the overlay. + const hit = await page.evaluate(([x, y]) => { + const el = document.elementFromPoint(x, y) + return !!el?.closest('.optimize-overlay-cancel') + }, [box.x + box.width / 2, box.y + box.height / 2]) + expect(hit).toBe(true) + + await cancel.tap() + await expect(cancel).toHaveCount(0) + await expect(composer).not.toHaveAttribute('readonly') + await expect(composer).toHaveValue(DRAFT) + await composer.press('End') + await composer.pressSequentially(' please') + await expect(composer).toHaveValue(`${DRAFT} please`) + expect(errors).toEqual([]) + }) + }) +} + +test.describe('Desktop: optimize overlay Cancel stays icon-only', () => { + test.use({ viewport: { width: 1280, height: 800 }, reducedMotion: 'reduce' }) + + test('shows the 28px X without the touch label', async ({ page, baseURL }) => { + const { errors } = await openComposer(page, baseURL!) + await startOptimize(page, false) + const cancel = page.getByRole('button', { name: CANCEL_NAME }) + await expect(cancel).toBeVisible() + await expect(cancel.getByText(CANCEL_LABEL, { exact: true })).toBeHidden() + const box = (await cancel.boundingBox())! + expect(Math.round(box.width)).toBe(28) + expect(Math.round(box.height)).toBe(28) + expect(errors).toEqual([]) + }) +}) diff --git a/website/scripts/capture-optimize-cancel.mjs b/website/scripts/capture-optimize-cancel.mjs new file mode 100644 index 000000000000..9025866b5aff --- /dev/null +++ b/website/scripts/capture-optimize-cancel.mjs @@ -0,0 +1,119 @@ +// Evidence capture: the "Optimizing prompt…" overlay on a phone, with its +// Cancel button, before and after the tap. +// +// Runs the REAL built SPA (website/dist) with the dashboard API stubbed and the +// optimizer request held open, so the overlay stays up until Cancel aborts it. +// Not a test: ChatInput.optimizeCancel.test.tsx pins the behaviour; this shows it. +// +// node scripts/capture-optimize-cancel.mjs [outDir] +import { chromium } from 'playwright' +import { mkdirSync, readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { serveDist } from './lib/serve-dist.mjs' +import { logPageProblems, stubDashboardApi, json } from './lib/stub-dashboard-api.mjs' + +const OUT = process.argv[2] || '../temp-screenshots/optimize-cancel' +mkdirSync(OUT, { recursive: true }) + +const LOCALES = fileURLToPath(new URL('../src/i18n/locales/', import.meta.url)) +const manual = JSON.parse(readFileSync(LOCALES + 'en.manual.json', 'utf-8')) +const CANCEL = manual.components.chatInput.cancel_optimizing +if (!CANCEL) throw new Error('cancel_optimizing missing from en.manual.json') + +const SLOT = 'optimize-demo' +const DRAFT = 'look at the failing build and tell me what broke' +const now = Math.floor(Date.now() / 1000) +const slots = [{ + key: SLOT, title: 'Build triage', running: false, stop_state: 'idle', + last_message: 'Ready.', messages: 2, agent: 'kirocrew', memory_mode: 'persistent', + modified: now, source_links: [], source_links_total: 0, +}] +const detail = { + running: false, has_more: false, total: 2, queue: [], + messages: [ + { role: 'user', ts: now - 120, content: 'Hi' }, + { role: 'assistant', ts: now - 110, content: 'Ready.' }, + ], +} + +async function main() { + const { srv, base } = await serveDist() + const browser = await chromium.launch() + const context = await browser.newContext({ + viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, hasTouch: true, isMobile: true, + }) + const page = await context.newPage() + logPageProblems(page) + let optimizeRequests = 0 + await stubDashboardApi(page, { + slots, + extra: async (path, route) => { + if (path.startsWith('/api/chat/slots/')) { await json(route, detail); return true } + // Never answered: the page's abort is the only thing that ends it. + if (path.startsWith('/api/optimizer/optimize')) { optimizeRequests++; return true } + return false + }, + }) + await page.goto(base + `/chat?sid=${encodeURIComponent(SLOT)}`, { waitUntil: 'domcontentloaded' }) + const box = page.getByRole('textbox', { name: /message/i }).first() + await box.waitFor({ timeout: 15000 }) + await box.fill(DRAFT) + await page.getByRole('button', { name: 'Optimize prompt' }).first().tap() + const cancel = page.getByRole('button', { name: CANCEL }) + await cancel.waitFor({ timeout: 5000 }) + if (optimizeRequests !== 1) throw new Error(`expected 1 optimize request, saw ${optimizeRequests}`) + await page.waitForTimeout(400) + const size = await cancel.boundingBox() + console.log(`cancel target ${Math.round(size.width)}x${Math.round(size.height)} css px`) + await page.screenshot({ path: `${OUT}/mobile-optimizing.png` }) + + await cancel.tap() + await cancel.waitFor({ state: 'detached', timeout: 5000 }) + if (await box.getAttribute('readonly') !== null) throw new Error('composer still read-only after Cancel') + await box.press('End') + await box.type(' please') + const value = await box.inputValue() + if (value !== DRAFT + ' please') throw new Error(`draft not editable after Cancel: ${JSON.stringify(value)}`) + await page.waitForTimeout(300) + await page.screenshot({ path: `${OUT}/mobile-after-cancel.png` }) + await captureDesktop(browser, base) + await browser.close() + srv.close() + console.log(`wrote ${OUT}/{mobile-optimizing,mobile-after-cancel,desktop-optimizing}.png`) +} + +// The mouse-pointer size of the same button (28 px) inside the overlay pill. +async function captureDesktop(browser, base) { + const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 }) + const page = await context.newPage() + logPageProblems(page) + await stubDashboardApi(page, { + slots, + extra: async (path, route) => { + if (path.startsWith('/api/chat/slots/')) { await json(route, detail); return true } + return path.startsWith('/api/optimizer/optimize') + }, + }) + await page.goto(base + `/chat?sid=${encodeURIComponent(SLOT)}`, { waitUntil: 'domcontentloaded' }) + const box = page.getByRole('textbox', { name: /message/i }).first() + await box.waitFor({ timeout: 15000 }) + await box.fill(DRAFT) + await page.getByRole('button', { name: 'Optimize prompt' }).first().click() + const cancel = page.getByRole('button', { name: CANCEL }) + await cancel.waitFor({ timeout: 5000 }) + await page.waitForTimeout(400) + const size = await cancel.boundingBox() + console.log(`desktop cancel target ${Math.round(size.width)}x${Math.round(size.height)} css px`) + const pill = await cancel.evaluate(el => { + const r = el.parentElement.getBoundingClientRect() + return { x: r.x, y: r.y, width: r.width, height: r.height } + }) + const pad = 120 + await page.screenshot({ + path: `${OUT}/desktop-optimizing.png`, + clip: { x: Math.max(0, pill.x - pad * 3), y: Math.max(0, pill.y - pad), width: pill.width + pad * 6, height: pill.height + pad * 2 }, + }) + await context.close() +} + +main().catch(err => { console.error(err); process.exit(1) }) diff --git a/website/src/components/ChatInput.tsx b/website/src/components/ChatInput.tsx index 164d3ed42b6b..829d7371801f 100644 --- a/website/src/components/ChatInput.tsx +++ b/website/src/components/ChatInput.tsx @@ -2,7 +2,7 @@ import { useRef, useEffect, useLayoutEffect, useMemo, useCallback, useId, useSta import { GUIDE_KEEP_CLEAR } from '../guide/trustRoot' import { useGuidePredicate } from '../guide/guidePredicates' import { markComposerResize } from '../utils/composerResize' -import { ArrowUp, Loader2, RotateCw, Sparkles, Target, CheckCircle, Lock, FolderOpen, ClipboardList, PenLine, MoreHorizontal, Terminal, Clock } from 'lucide-react' +import { ArrowUp, Loader2, RotateCw, Sparkles, Target, CheckCircle, Lock, FolderOpen, ClipboardList, PenLine, MoreHorizontal, Terminal, Clock, X } from 'lucide-react' import SketchDialog from './SketchDialog' import QuoteCard from '../pages/chat/QuoteCard' import CopyBranchButton from './CopyBranchButton' @@ -655,9 +655,10 @@ function ChatInput({ setTextareaRef(textarea) attachListContinuation(textarea) }, [setTextareaRef, attachListContinuation]) - const { optimizeError, setOptimizeError, optimizePending, optimizing, optimizePrompt } = usePromptOptimizer({ + const { optimizeError, setOptimizeError, optimizePending, optimizing, optimizePrompt, cancelOptimize } = usePromptOptimizer({ slotId, chatStore, valueRef, pasteBlocks, onChange, onOptimizeResult, lexicalComposer, lexicalLoadFailed, composerControl, inputRef, valueFromUserRef, optimizingRef, appendUndoBoundary: appendBoundary, terminalCommands, optimizerMentionGuard, + composerDisabled: disabled, }) useEffect(() => { onOptimizingChange?.(optimizing) }, [optimizing, onOptimizingChange]) // A locked composer (a memory-mode switch is moving its draft) must not @@ -1289,7 +1290,16 @@ function ChatInput({ micHeldElsewhere={micHeldElsewhere} micHeldElsewhereLabel={micHeldElsewhereLabel} micHeldElsewhereAction={micHeldElsewhereAction} voiceHeldLanded={voiceHeldLanded} /> - {optimizing && {i18nT('components.chatInput.optimizing_prompt')}} + {/* The overlay itself lets taps through; only the pill's Cancel takes + them. Without Cancel a mis-tap on Optimize (it sits beside Send on + a phone) leaves the draft read-only until the request settles. */} + {optimizing && {i18nT('components.chatInput.optimizing_prompt')}} {/* The textarea fallback is seamless for typing (draft intact), but the failure itself must be user-visible, not only a console line: the person who opted into the editor should know they are no longer in diff --git a/website/src/components/chat-input/optimizer.ts b/website/src/components/chat-input/optimizer.ts index b90c180a5012..2585daf4378c 100644 --- a/website/src/components/chat-input/optimizer.ts +++ b/website/src/components/chat-input/optimizer.ts @@ -24,7 +24,7 @@ function keepsFolderMentions(draft: string, rewrite: string): boolean { return after.length === before.size && after.every(rel => before.has(rel)) } -export function usePromptOptimizer({ slotId, chatStore, valueRef, pasteBlocks, onChange, onOptimizeResult, lexicalComposer, lexicalLoadFailed, composerControl, inputRef, valueFromUserRef, optimizingRef, appendUndoBoundary, terminalCommands, optimizerMentionGuard }: { +export function usePromptOptimizer({ slotId, chatStore, valueRef, pasteBlocks, onChange, onOptimizeResult, lexicalComposer, lexicalLoadFailed, composerControl, inputRef, valueFromUserRef, optimizingRef, appendUndoBoundary, terminalCommands, optimizerMentionGuard, composerDisabled }: { slotId: string | null chatStore: ReturnType valueRef: React.MutableRefObject @@ -41,6 +41,8 @@ export function usePromptOptimizer({ slotId, chatStore, valueRef, pasteBlocks, o appendUndoBoundary: (v: string) => void terminalCommands?: ChatInputProps['terminalCommands'] optimizerMentionGuard?: ChatInputProps['optimizerMentionGuard'] + /** The host's `disabled`: the Lexical root stays non-editable on Cancel while it is set. */ + composerDisabled?: boolean }) { // Tracks the prior render's raw pending state so the completion effect can // record a single undo boundary when an optimize actually finishes (as @@ -55,6 +57,8 @@ export function usePromptOptimizer({ slotId, chatStore, valueRef, pasteBlocks, o // In-composer report of a rejected optimize request (the restored prompt // alone says nothing about why the optimizer did not run). const [optimizeError, setOptimizeError] = useState('') + // The in-flight request's abort handle, so the overlay's Cancel can end it. + const abortRef = useRef(null) const setTextUndoable = useCallback((text: string) => { if (lexicalComposer && !lexicalLoadFailed) { @@ -97,13 +101,15 @@ export function usePromptOptimizer({ slotId, chatStore, valueRef, pasteBlocks, o const optimizeMutation = useMutation({ onMutate: () => { setOptimizeError('') }, mutationFn: async ( - { prompt, context, pastes }: { + { prompt, context, pastes, signal }: { prompt: string context: string pastes?: Array<{ seq: number; content: string }> /** The mention check, taken with `prompt` (see onSuccess). */ keepsMentions?: (rewrite: string) => boolean slotId: string | null + /** Aborted by `cancelOptimize`; onError reads it to tell a cancel from a failure. */ + signal?: AbortSignal }, ) => { const resp = await fetch('/api/optimizer/optimize', { @@ -111,11 +117,15 @@ export function usePromptOptimizer({ slotId, chatStore, valueRef, pasteBlocks, o headers: { 'Content-Type': 'application/json', 'x-session-key': 'dashboard:ui' }, credentials: 'same-origin', body: JSON.stringify({ prompt, context, pastes }), + signal, }) if (!resp.ok) throw new Error('optimizer failed') return resp.json() }, onSuccess: (data, variables) => { + // Cancel landed after the body was read: the user already has the draft + // back and may be typing, so the rewrite is dropped. + if (variables.signal?.aborted) return // A rewrite that would change what the draft attaches is discarded, the // way the server discards one that breaks a paste placeholder: it // replaces the whole draft, so a picked file or folder mention it @@ -142,6 +152,11 @@ export function usePromptOptimizer({ slotId, chatStore, valueRef, pasteBlocks, o onOptimizeResult?.(variables.slotId, rewrite ?? variables.prompt) }, onError: (err, variables) => { + // A cancel is the user's own choice, not a failure: no notice, and the + // draft needs no restore because it stayed read-only and untouched for + // the whole request. Cancel is only reachable from the overlay, which + // only renders on the originating session, so there is nothing to route. + if (variables.signal?.aborted) return // eslint-disable-next-line no-console -- surface prompt-optimizer failures to the dev console console.warn('optimizer failed', err) // The user must learn the optimizer failed: restoring the prompt alone is @@ -251,8 +266,43 @@ export function usePromptOptimizer({ slotId, chatStore, valueRef, pasteBlocks, o // file-mention guard when it has one. const keepsFiles = optimizerMentionGuard?.(txt) const keepsMentions = (rewrite: string) => keepsFolderMentions(txt, rewrite) && (keepsFiles?.(rewrite) ?? true) - runOptimize({ prompt: txt, context, pastes, keepsMentions, slotId }) + const controller = new AbortController() + abortRef.current = controller + runOptimize({ prompt: txt, context, pastes, keepsMentions, slotId, signal: controller.signal }) }, [runOptimize, pasteBlocks, slotId, chatStore, valueRef, terminalCommands, optimizerMentionGuard]) - return { optimizeError, setOptimizeError, optimizePending, optimizing, optimizePrompt } + // Abort the in-flight request. The draft is read-only while it runs, so + // aborting is enough to hand it back: the rejection settles the mutation, + // which clears `optimizing` (overlay, readOnly, disabled Send) on its own. + // Focus goes back to the composer here, inside the tap, because the Cancel + // button unmounts with the overlay and mobile browsers only raise the + // keyboard for a focus() made during the user's gesture. readOnly is cleared + // on the element first for the same reason setTextUndoable does it. The + // Lexical root is still contenteditable="false" until React re-renders, and + // a non-editable root takes no focus, so it is made editable here too; the + // re-render's setEditable(!disabled && !readOnly) then agrees with it. A + // disabled host keeps it non-editable: that render's setEditable(false) is a + // no-op on an editor already non-editable, so it would not undo a DOM write. + const cancelOptimize = useCallback(() => { + abortRef.current?.abort() + abortRef.current = null + const end = valueRef.current.length + if (lexicalComposer && !lexicalLoadFailed) { + const control = composerControl() + const root = control?.getRootElement() + if (root && !composerDisabled) root.contentEditable = 'true' + control?.setSelection(end, end) + control?.focus() + return + } + const el = inputRef.current + if (!el) return + // Same rule as the Lexical root: a disabled host keeps the lock, because + // readOnly={optimizing || disabled} stays true and React will not rewrite it. + el.readOnly = !!composerDisabled + el.focus() + el.setSelectionRange(end, end) + }, [valueRef, lexicalComposer, lexicalLoadFailed, composerControl, inputRef, composerDisabled]) + + return { optimizeError, setOptimizeError, optimizePending, optimizing, optimizePrompt, cancelOptimize } } diff --git a/website/src/i18n/locales/bn.json b/website/src/i18n/locales/bn.json index 10b1b018c891..b076a7692121 100644 --- a/website/src/i18n/locales/bn.json +++ b/website/src/i18n/locales/bn.json @@ -6415,6 +6415,8 @@ "sketch_desc": "স্কেচ আঁকুন; ছবি এবং সম্পাদনাযোগ্য উৎস সংযুক্ত করে", "optimize_failed": "প্রম্পট অপ্টিমাইজ করা যায়নি। আপনার মূল লেখা পুনরুদ্ধার করা হয়েছে।", "optimize_failed_elsewhere": "অন্য সেশনে শুরু করা প্রম্পট অপ্টিমাইজ করা যায়নি। সেখানে মূল লেখা পুনরুদ্ধার করা হয়েছে।", + "cancel_optimizing": "অপ্টিমাইজ করা বাতিল করো", + "cancel_optimizing_short": "বাতিল", "more_actions": "আরও অ্যাকশন", "session_control_needs_attention": "নজর দেওয়া দরকার", "session_control_ready": "প্রস্তুত", diff --git a/website/src/i18n/locales/de.json b/website/src/i18n/locales/de.json index 450c10d9d5b2..8e81f5d7aa47 100644 --- a/website/src/i18n/locales/de.json +++ b/website/src/i18n/locales/de.json @@ -6415,6 +6415,8 @@ "sketch_desc": "Skizze zeichnen; hängt ein Bild plus bearbeitbare Quelle an", "optimize_failed": "Der Prompt konnte nicht optimiert werden. Der ursprüngliche Text wurde wiederhergestellt.", "optimize_failed_elsewhere": "Der in einer anderen Sitzung gestartete Prompt konnte nicht optimiert werden. Der ursprüngliche Text wurde dort wiederhergestellt.", + "cancel_optimizing": "Optimierung abbrechen", + "cancel_optimizing_short": "Abbrechen", "more_actions": "Weitere Aktionen", "session_control_needs_attention": "Aktion erforderlich", "session_control_ready": "Bereit", diff --git a/website/src/i18n/locales/en-XA.json b/website/src/i18n/locales/en-XA.json index 10b21c6a7887..77a87c90f5b9 100644 --- a/website/src/i18n/locales/en-XA.json +++ b/website/src/i18n/locales/en-XA.json @@ -5991,6 +5991,8 @@ "agent_default_source": "[Şèţ þèŕ àğèñţ ìñ çøñƒìğ.ĵşøñ (àğèñţş.{{agent}}.àùţøçøɱþàçţ_þçţ). Ṁøṽìñğ ţĥè şĺìðèŕ øṽèŕŕìðèş ìţ ƒøŕ ţĥìş şèşşìøñ. ·······························]", "optimize_failed": "[Çøùĺðñ'ţ øþţìɱìžè ţĥè þŕøɱþţ. Ýøùŕ øŕìğìñàĺ ţèẋţ ẁàş ŕèşţøŕèð. ······················]", "optimize_failed_elsewhere": "[Çøùĺðñ'ţ øþţìɱìžè ţĥè þŕøɱþţ ýøù şţàŕţèð ìñ àñøţĥèŕ şèşşìøñ. Ìţş øŕìğìñàĺ ţèẋţ ẁàş ŕèşţøŕèð ţĥèŕè. ·····························]", + "cancel_optimizing": "[Çàñçèĺ øþţìɱìžìñğ ···············]", + "cancel_optimizing_short": "[Çàñçèĺ ·········]", "session_control_needs_attention": "[Ñèèðş àţţèñţìøñ ··············]", "session_control_ready": "[Ŕèàðý ········]", "session_control_chip_label": "[{{label}} — {{detail}} ·····]", diff --git a/website/src/i18n/locales/en.manual.json b/website/src/i18n/locales/en.manual.json index 68d6b6490497..9de447c9f8ce 100644 --- a/website/src/i18n/locales/en.manual.json +++ b/website/src/i18n/locales/en.manual.json @@ -2136,6 +2136,8 @@ "agent_default_source": "Set per agent in config.json (agents.{{agent}}.autocompact_pct). Moving the slider overrides it for this session.", "optimize_failed": "Couldn't optimize the prompt. Your original text was restored.", "optimize_failed_elsewhere": "Couldn't optimize the prompt you started in another session. Its original text was restored there.", + "cancel_optimizing": "Cancel optimizing", + "cancel_optimizing_short": "Cancel", "session_control_needs_attention": "Needs attention", "session_control_ready": "Ready", "session_control_chip_label": "{{label}} — {{detail}}", diff --git a/website/src/i18n/locales/es.json b/website/src/i18n/locales/es.json index 2449bacead52..090bd197fed4 100644 --- a/website/src/i18n/locales/es.json +++ b/website/src/i18n/locales/es.json @@ -6527,6 +6527,8 @@ "sketch_desc": "Dibuja un boceto; adjunta una imagen y su fuente editable", "optimize_failed": "No se pudo optimizar el prompt. Se restauró tu texto original.", "optimize_failed_elsewhere": "No se pudo optimizar el prompt que iniciaste en otra sesión. Su texto original se restauró allí.", + "cancel_optimizing": "Cancelar la optimización", + "cancel_optimizing_short": "Cancelar", "more_actions": "Más acciones", "session_control_needs_attention": "Requiere atención", "session_control_ready": "Listo", diff --git a/website/src/i18n/locales/fr.json b/website/src/i18n/locales/fr.json index f91c4e5df1cc..ae983c97f467 100644 --- a/website/src/i18n/locales/fr.json +++ b/website/src/i18n/locales/fr.json @@ -6527,6 +6527,8 @@ "sketch_desc": "Dessinez un croquis ; joint une image et sa source modifiable", "optimize_failed": "Impossible d'optimiser le prompt. Ton texte d'origine a été restauré.", "optimize_failed_elsewhere": "Impossible d'optimiser le prompt lancé dans une autre session. Son texte d'origine y a été restauré.", + "cancel_optimizing": "Annuler l'optimisation", + "cancel_optimizing_short": "Annuler", "more_actions": "Plus d'actions", "session_control_needs_attention": "Attention requise", "session_control_ready": "Prêt", diff --git a/website/src/i18n/locales/hi.json b/website/src/i18n/locales/hi.json index 9bfe72713e8f..d52788857ffb 100644 --- a/website/src/i18n/locales/hi.json +++ b/website/src/i18n/locales/hi.json @@ -6415,6 +6415,8 @@ "sketch_desc": "स्केच बनाएं; छवि और संपादन योग्य स्रोत संलग्न करता है", "optimize_failed": "प्रॉम्प्ट ऑप्टिमाइज़ नहीं किया जा सका। मूल टेक्स्ट बहाल कर दिया गया है।", "optimize_failed_elsewhere": "दूसरे सत्र में शुरू किया गया प्रॉम्प्ट ऑप्टिमाइज़ नहीं किया जा सका। वहाँ मूल टेक्स्ट बहाल कर दिया गया है।", + "cancel_optimizing": "ऑप्टिमाइज़ करना रद्द करो", + "cancel_optimizing_short": "रद्द करो", "more_actions": "और कार्रवाइयां", "session_control_needs_attention": "ध्यान देने की ज़रूरत", "session_control_ready": "तैयार", diff --git a/website/src/i18n/locales/it.json b/website/src/i18n/locales/it.json index 7ba5d19794d3..93222602e254 100644 --- a/website/src/i18n/locales/it.json +++ b/website/src/i18n/locales/it.json @@ -6527,6 +6527,8 @@ "sketch_desc": "Disegna uno schizzo; allega un’immagine e la sua origine modificabile", "optimize_failed": "Impossibile ottimizzare il prompt. Il testo originale è stato ripristinato.", "optimize_failed_elsewhere": "Impossibile ottimizzare il prompt avviato in un'altra sessione. Il testo originale è stato ripristinato lì.", + "cancel_optimizing": "Annulla l'ottimizzazione", + "cancel_optimizing_short": "Annulla", "more_actions": "Altre azioni", "session_control_needs_attention": "Richiede attenzione", "session_control_ready": "Pronto", diff --git a/website/src/i18n/locales/ja.json b/website/src/i18n/locales/ja.json index 28151be7277d..0899a2d5d7a5 100644 --- a/website/src/i18n/locales/ja.json +++ b/website/src/i18n/locales/ja.json @@ -6303,6 +6303,8 @@ "sketch_desc": "スケッチを描く。画像と編集可能なソースを添付します", "optimize_failed": "プロンプトを最適化できませんでした。元のテキストを復元しました。", "optimize_failed_elsewhere": "別のセッションで開始したプロンプトを最適化できませんでした。元のテキストはそのセッションに復元されています。", + "cancel_optimizing": "最適化をキャンセル", + "cancel_optimizing_short": "キャンセル", "more_actions": "その他の操作", "session_control_needs_attention": "要対応", "session_control_ready": "準備完了", diff --git a/website/src/i18n/locales/ko.json b/website/src/i18n/locales/ko.json index 20dc122f2dbc..8b4ec04757f6 100644 --- a/website/src/i18n/locales/ko.json +++ b/website/src/i18n/locales/ko.json @@ -6303,6 +6303,8 @@ "sketch_desc": "스케치를 그리기. 이미지와 편집 가능한 원본을 첨부합니다", "optimize_failed": "프롬프트를 최적화할 수 없습니다. 원래 텍스트를 복원했습니다.", "optimize_failed_elsewhere": "다른 세션에서 시작한 프롬프트를 최적화할 수 없습니다. 원래 텍스트는 해당 세션에 복원되었습니다.", + "cancel_optimizing": "최적화 취소", + "cancel_optimizing_short": "취소", "more_actions": "추가 작업", "session_control_needs_attention": "확인 필요", "session_control_ready": "준비됨", diff --git a/website/src/i18n/locales/pt.json b/website/src/i18n/locales/pt.json index fc68d4bf093d..5f21a13e9c25 100644 --- a/website/src/i18n/locales/pt.json +++ b/website/src/i18n/locales/pt.json @@ -6527,6 +6527,8 @@ "sketch_desc": "Desenhe um esboço; anexa uma imagem e sua fonte editável", "optimize_failed": "Não foi possível otimizar o prompt. Seu texto original foi restaurado.", "optimize_failed_elsewhere": "Não foi possível otimizar o prompt iniciado em outra sessão. O texto original foi restaurado lá.", + "cancel_optimizing": "Cancelar otimização", + "cancel_optimizing_short": "Cancelar", "more_actions": "Mais ações", "session_control_needs_attention": "Requer atenção", "session_control_ready": "Pronto", diff --git a/website/src/i18n/locales/ru.json b/website/src/i18n/locales/ru.json index 44a8f1684b33..f47456ec34d4 100644 --- a/website/src/i18n/locales/ru.json +++ b/website/src/i18n/locales/ru.json @@ -6639,6 +6639,8 @@ "sketch_desc": "Нарисуйте эскиз; прикрепляет изображение и его редактируемый исходник", "optimize_failed": "Не удалось оптимизировать промпт. Исходный текст восстановлен.", "optimize_failed_elsewhere": "Не удалось оптимизировать промпт, запущенный в другой сессии. Исходный текст восстановлен там.", + "cancel_optimizing": "Отменить улучшение", + "cancel_optimizing_short": "Отмена", "more_actions": "Другие действия", "session_control_needs_attention": "Требует внимания", "session_control_ready": "Готово", diff --git a/website/src/i18n/locales/zh-CN.json b/website/src/i18n/locales/zh-CN.json index 77451a7e6d9b..d22dd4871e73 100644 --- a/website/src/i18n/locales/zh-CN.json +++ b/website/src/i18n/locales/zh-CN.json @@ -6303,6 +6303,8 @@ "sketch_desc": "画个草图;会附上图片和可编辑源文件", "optimize_failed": "无法优化提示词。已恢复原始文本。", "optimize_failed_elsewhere": "无法优化在另一个会话中发起的提示词。原始文本已在该会话中恢复。", + "cancel_optimizing": "取消优化", + "cancel_optimizing_short": "取消", "more_actions": "更多操作", "session_control_needs_attention": "需要处理", "session_control_ready": "就绪", diff --git a/website/src/styles/chat-transcript.css b/website/src/styles/chat-transcript.css index d9a359a92657..59f2a2a3cb0e 100644 --- a/website/src/styles/chat-transcript.css +++ b/website/src/styles/chat-transcript.css @@ -36,6 +36,14 @@ being hidden behind an opaque grey slab, and picks up the accent so it reads as a first-class app surface in every theme (light/dark/monokai/custom). */ .optimize-overlay{background:color-mix(in srgb,var(--card) 62%,transparent);animation:ft-fade .25s ease-out both} +/* Touch screens get no title tooltip, so the X alone does not say what it does. + Under a coarse pointer the button grows to a 44px-tall labelled "Cancel" chip; + a mouse keeps the 28px icon with its tooltip. */ +.optimize-overlay-cancel-label{display:none} +@media (pointer: coarse){ + .optimize-overlay-cancel{width:auto;min-width:2.75rem;height:2.75rem;padding:0 .875rem 0 .75rem;gap:.375rem;color:var(--text);background:color-mix(in srgb,var(--text) 8%,transparent)} + .optimize-overlay-cancel-label{display:inline} +} .optimize-overlay-pill{background:color-mix(in srgb,var(--accent) 12%,var(--card));border:1px solid color-mix(in srgb,var(--accent) 35%,transparent);box-shadow:0 8px 24px var(--accent-glow),0 1px 3px rgba(0,0,0,.12)} @media (prefers-reduced-motion:reduce){ .optimize-overlay{animation:none} diff --git a/website/src/test/ChatInput.optimizeCancel.test.tsx b/website/src/test/ChatInput.optimizeCancel.test.tsx new file mode 100644 index 000000000000..7112746d1e9e --- /dev/null +++ b/website/src/test/ChatInput.optimizeCancel.test.tsx @@ -0,0 +1,171 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { screen, fireEvent, act } from '@testing-library/react' +import { renderWithProviders } from './helpers' +import ChatInput from '../components/ChatInput' + +/** + * While "Optimize prompt" runs, the composer is read-only and Send is disabled + * until the request settles. A mis-tap on the optimize button (it sits next to + * Send on a phone) used to leave no way out short of waiting: the overlay gave + * no control, so a slow or hung optimizer held the draft hostage. The overlay + * now carries a Cancel button that aborts the request and hands the draft back + * untouched. + */ + +const ORIGINAL = 'my prompt' + +// The Lexical composer is a React.lazy chunk (chat-input/engine.tsx), so its +// first mount can outlast findBy's 1000 ms default on a loaded runner. +const LAZY_COMPOSER_MOUNT = { timeout: 5000 } + +/** An optimizer request that never answers on its own, but honours abort. */ +const hangingOptimizer = (signals: AbortSignal[]) => + vi.fn((url: string, init?: RequestInit) => { + if (typeof url === 'string' && url.includes('/api/optimizer/optimize')) { + return new Promise((_resolve, reject) => { + const signal = init?.signal + if (signal) { + signals.push(signal) + signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))) + } + }) + } + return Promise.resolve({ ok: true, json: async () => [] }) + }) + +const clickOptimize = () => + fireEvent.click(screen.getByRole('button', { name: 'Optimize prompt' })) + +describe('ChatInput optimize: the in-flight overlay can be cancelled', () => { + beforeEach(() => { + vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { + cb(0) + return 0 + }) + }) + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('aborts the request and returns the draft, editable, with no error', async () => { + const signals: AbortSignal[] = [] + const onChange = vi.fn() + vi.stubGlobal('fetch', hangingOptimizer(signals)) + + renderWithProviders( + , + ) + clickOptimize() + + const textbox = screen.getByRole('textbox') as HTMLTextAreaElement + await vi.waitFor(() => expect(textbox.readOnly).toBe(true)) + + const cancel = await screen.findByRole('button', { name: 'Cancel optimizing' }) + await act(async () => { fireEvent.click(cancel) }) + + expect(signals).toHaveLength(1) + expect(signals[0].aborted).toBe(true) + await vi.waitFor(() => expect(screen.queryByRole('button', { name: 'Cancel optimizing' })).toBeNull()) + expect(textbox.readOnly).toBe(false) + expect(screen.queryByTestId('optimize-error')).toBeNull() + // The draft is the user's own text: a cancel writes nothing back. + expect(onChange).not.toHaveBeenCalled() + expect(screen.getByRole('button', { name: 'Optimize prompt' })).not.toBeDisabled() + }) + + it('puts focus back in the composer so the keyboard returns without a second tap', async () => { + vi.stubGlobal('fetch', hangingOptimizer([])) + renderWithProviders( + , + ) + clickOptimize() + const cancel = await screen.findByRole('button', { name: 'Cancel optimizing' }) + cancel.focus() + await act(async () => { fireEvent.click(cancel) }) + + const textbox = screen.getByRole('textbox') as HTMLTextAreaElement + expect(document.activeElement).toBe(textbox) + expect(textbox.selectionStart).toBe(ORIGINAL.length) + }) + + it('makes the Lexical composer editable inside the tap, so a phone raises its keyboard', async () => { + vi.stubGlobal('fetch', hangingOptimizer([])) + renderWithProviders( + , + ) + const root = await screen.findByRole('textbox', undefined, LAZY_COMPOSER_MOUNT) + clickOptimize() + await vi.waitFor(() => expect(root.getAttribute('contenteditable')).toBe('false')) + const cancel = await screen.findByRole('button', { name: 'Cancel optimizing' }) + + // Record the attribute at the moment focus() is called: a mobile browser + // only raises the keyboard for a focus() on an element that is already + // editable while the user's gesture is still running, before React + // re-renders the composer out of read-only. + let editableAtFocus: string | null = null + const realFocus = root.focus.bind(root) + vi.spyOn(root, 'focus').mockImplementation((opts?: FocusOptions) => { + editableAtFocus ??= root.getAttribute('contenteditable') + realFocus(opts) + }) + await act(async () => { fireEvent.click(cancel) }) + + expect(editableAtFocus).toBe('true') + expect(document.activeElement).toBe(root) + }) + + it('leaves the Lexical composer non-editable when the host disabled it during the optimize', async () => { + vi.stubGlobal('fetch', hangingOptimizer([])) + const props = { value: ORIGINAL, onChange: vi.fn(), onSend: vi.fn(), connected: true, lexicalComposer: true } + const { rerender } = renderWithProviders() + const root = await screen.findByRole('textbox', undefined, LAZY_COMPOSER_MOUNT) + clickOptimize() + await screen.findByRole('button', { name: 'Cancel optimizing' }) + rerender() + await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Cancel optimizing' })) }) + + // Lexical's setEditable(false) is a no-op on an editor that is already + // non-editable, so a DOM write here would never be undone. + expect(root.getAttribute('contenteditable')).toBe('false') + }) + + it('leaves the textarea read-only when the host disabled it during the optimize', async () => { + vi.stubGlobal('fetch', hangingOptimizer([])) + const props = { value: ORIGINAL, onChange: vi.fn(), onSend: vi.fn(), connected: true } + const { rerender } = renderWithProviders() + clickOptimize() + await screen.findByRole('button', { name: 'Cancel optimizing' }) + rerender() + await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Cancel optimizing' })) }) + + // readOnly={optimizing || disabled} stays true across the settle, so React + // never rewrites the attribute and a DOM write here would never be undone. + expect((screen.getByRole('textbox') as HTMLTextAreaElement).readOnly).toBe(true) + }) + + it('drops a rewrite whose body was already read when Cancel landed', async () => { + const onChange = vi.fn() + let answer: (v: unknown) => void = () => {} + vi.stubGlobal('fetch', vi.fn((url: string) => { + if (typeof url === 'string' && url.includes('/api/optimizer/optimize')) { + // The response is in hand; only its body read is still pending, and + // that read ignores the abort signal. + return Promise.resolve({ + ok: true, + json: () => new Promise((resolve) => { answer = resolve }), + }) + } + return Promise.resolve({ ok: true, json: async () => [] }) + })) + renderWithProviders( + , + ) + clickOptimize() + const cancel = await screen.findByRole('button', { name: 'Cancel optimizing' }) + await act(async () => { fireEvent.click(cancel) }) + await act(async () => { answer({ changed: true, optimized: 'a rewrite' }) }) + + await vi.waitFor(() => expect(screen.queryByRole('button', { name: 'Cancel optimizing' })).toBeNull()) + expect(onChange).not.toHaveBeenCalled() + }) +})