Skip to content

The agent that grows with you

fix(desktop): make preview-pane typing reliably replace field values

creeklava-svgabc5938895be
diff --git a/apps/desktop/src/app/chat/right-rail/preview-act.test.ts b/apps/desktop/src/app/chat/right-rail/preview-act.test.ts
index 6bae5752db4..e5369175111 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-act.test.ts
+++ b/apps/desktop/src/app/chat/right-rail/preview-act.test.ts
@@ -2,6 +2,8 @@ import { types } from 'node:util'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { isMacPlatform } from '@/lib/platform'
+
import { $rightRailActiveTabId } from '@/store/layout'
import { closeRightRail, openPreview, type PreviewTarget } from '@/store/preview'
@@ -281,13 +283,149 @@ describe('actOnActivePreview (drive_preview tool)', () => {
// paragraph under the cursor whenever the target turns out not to be a
// field, and the agent was leaving pages with their body text highlighted.
expect(events.filter(event => event.type === 'mouseDown').map(event => event.clickCount)).toEqual([1])
+ // Select-all must use the OS's real chord — Cmd+A on macOS, Ctrl+A elsewhere.
+ // Sending BOTH modifiers is not a chord any platform acts on, so the select
+ // silently no-ops and typing APPENDS to the field (9.99 + "19.99" = corruption).
expect(events.filter(event => event.type === 'keyDown' && event.keyCode === 'a')[0]).toMatchObject({
- modifiers: ['control', 'meta']
+ modifiers: isMacPlatform() ? ['meta'] : ['control']
})
// The chord must not send a `char` phase, or select-all types a literal 'a'.
expect(chars).toEqual(['h', 'i', 'Enter'])
})
+ /** A pane whose field STATE is scriptable, so the driver's verify-and-
+ * fallback clear logic can be exercised. `selectWorks` decides whether the
+ * select-all chord empties the field (a re-render that throws the selection
+ * away makes it false); `clearable` decides whether End/Backspace actually
+ * empties it (false models a field that keeps refilling). The field starts
+ * at `initial` chars. Every input event is recorded on `send`. */
+ const withTypingPane = (opts: { initial: number; selectWorks: boolean; clearable: boolean }) => {
+ const tabId = openBrowserTab()
+ const send = vi.fn()
+ let fieldLen = opts.initial
+ const isSelectAll = (e: { type: string; keyCode: string; modifiers?: string[] }) =>
+ e.type === 'keyDown' && e.keyCode === 'a' && !!e.modifiers?.length
+
+ send.mockImplementation((e: { type: string; keyCode: string; modifiers?: string[] }) => {
+ if (isSelectAll(e)) {
+ if (opts.selectWorks && opts.clearable) fieldLen = 0
+ return
+ }
+ if (e.type === 'keyDown' && e.keyCode === 'Backspace' && fieldLen > 0 && opts.clearable) fieldLen--
+ })
+
+ cleanups.push(
+ registerPreviewScriptRunner(tabId, async code =>
+ code.includes('document.activeElement')
+ ? JSON.stringify({ success: true, field: true, len: fieldLen })
+ : code.includes('"kind":"locate"')
+ ? JSON.stringify({
+ acted: 'looking at textbox "Price"',
+ point: { x: 120, y: 80 },
+ success: true,
+ typable: true
+ })
+ : JSON.stringify({ elements: [], hit: { tag: 'INPUT', trusted: true }, success: true })
+ )
+ )
+ cleanups.push(registerPreviewInput(tabId, { focus: vi.fn(), send }))
+
+ return send
+ }
+
+ const charKeys = (send: ReturnType<typeof vi.fn>) =>
+ send.mock.calls.map(([e]) => e).filter((e: { type: string }) => e.type === 'char').map((e: { keyCode: string }) => e.keyCode)
+
+ const keyDowns = (send: ReturnType<typeof vi.fn>) =>
+ send.mock.calls.map(([e]) => e).filter((e: { type: string }) => e.type === 'keyDown').map((e: { keyCode: string }) => e.keyCode)
+
+ it('verifies the select emptied the field before typing (select works)', async () => {
+ const send = withTypingPane({ initial: 4, selectWorks: true, clearable: true })
+
+ await actOnActivePreview({ kind: 'type', ref: '@e1', text: 'hi' })
+ const keys = keyDowns(send)
+
+ // Select-all cleared it on the first pass (len read back as 0) — no End or
+ // Backspace fallback should fire, and the typed chars should just land.
+ expect(keys).not.toContain('End')
+ expect(keys).not.toContain('Backspace')
+ expect(charKeys(send)).toEqual(['h', 'i'])
+ })
+
+ it('falls back to End+Backspace when a re-render throws the select away', async () => {
+ const send = withTypingPane({ initial: 4, selectWorks: false, clearable: true })
+
+ await actOnActivePreview({ kind: 'type', ref: '@e1', text: 'hi' })
+ const keys = keyDowns(send)
+
+ // select-all did nothing (the page replaced the node), so the driver must
+ // End + Backspace the whole old value (4 chars) before typing — and never
+ // append onto stale content.
+ expect(keys.filter(k => k === 'Backspace').length).toBeGreaterThanOrEqual(4)
+ expect(charKeys(send)).toEqual(['h', 'i'])
+ })
+
+ it('fails the action instead of typing when the field keeps refilling AND direct-set also fails', async () => {
+ const tabId = openBrowserTab()
+ const send = vi.fn()
+
+ // Every read reports the field as non-empty (it never clears), and the
+ // direct-set fallback reports failure too — so the action must hard-stop.
+ cleanups.push(
+ registerPreviewScriptRunner(tabId, async code =>
+ code.includes('"kind":"locate"')
+ ? JSON.stringify({
+ acted: 'looking at textbox "Price"',
+ point: { x: 120, y: 80 },
+ success: true,
+ typable: true
+ })
+ : code.includes('getOwnPropertyDescriptor') // direct-set also fails
+ ? JSON.stringify({ success: false, error: 'mask refuses' })
+ : code.includes('document.activeElement')
+ ? JSON.stringify({ success: true, field: true, len: 6 })
+ : JSON.stringify({ elements: [], hit: { tag: 'INPUT', trusted: true }, success: true })
+ )
+ )
+ cleanups.push(registerPreviewInput(tabId, { focus: vi.fn(), send }))
+
+ const result = await actOnActivePreview({ kind: 'type', ref: '@e1', text: 'hi' })
+
+ // Nothing can clear it and the fallback failed, so nothing may be typed.
+ expect(result.success).toBe(false)
+ expect(charKeys(send)).not.toContain('h')
+ })
+
+ it('falls back to a direct DOM value-set when real keys cannot clear a masked field', async () => {
+ const tabId = openBrowserTab()
+ const send = vi.fn()
+
+ cleanups.push(
+ registerPreviewScriptRunner(tabId, async code =>
+ code.includes('"kind":"locate"')
+ ? JSON.stringify({
+ acted: 'looking at textbox "Price"',
+ point: { x: 120, y: 80 },
+ success: true,
+ typable: true
+ })
+ : !code.includes('__hermesAct') && code.includes('getOwnPropertyDescriptor')
+ ? JSON.stringify({ success: true }) // the direct-set fallback succeeded (no preamble)
+ : !code.includes('__hermesAct') && code.includes('document.activeElement')
+ ? JSON.stringify({ success: true, field: true, len: 4 }) // field-state read
+ : JSON.stringify({ elements: [], hit: { tag: 'INPUT', trusted: true }, success: true }) // finish trip
+ )
+ )
+ cleanups.push(registerPreviewInput(tabId, { focus: vi.fn(), send }))
+
+ const result = await actOnActivePreview({ kind: 'type', ref: '@e1', text: '19.99' })
+
+ // Real keystrokes couldn't clear the mask, but the direct-set fallback
+ // committed the value, so the action reports success without typing chars.
+ expect(result.success).toBe(true)
+ expect(charKeys(send)).not.toContain('1')
+ })
+
it('hovers by walking the pointer over and leaving it there', async () => {
const send = withDrivenPane()
diff --git a/apps/desktop/src/app/chat/right-rail/preview-act.ts b/apps/desktop/src/app/chat/right-rail/preview-act.ts
index 00636efd7fc..ee0ab5c997b 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-act.ts
+++ b/apps/desktop/src/app/chat/right-rail/preview-act.ts
@@ -30,7 +30,7 @@
import { actEngineSource, type PreviewActAction, type PreviewActResult } from '@/lib/preview-act/act-in-page'
import { watchInPage } from '@/lib/preview-act/watch-in-page'
-import { clickAt, glideTo, pointerPlaced, pressKey, selectAll, typeText, wheelBy } from './preview-drive'
+import { clickAt, clearCharsBack, glideTo, pointerPlaced, pressKey, selectAll, typeText, wheelBy } from './preview-drive'
import { activePreviewInput, type PreviewInputHandle } from './preview-input'
import { activePreviewNav, type PreviewNavHandle } from './preview-nav'
import { activePreviewScriptRunner, type PreviewScriptRunner } from './preview-script-runner'
@@ -45,6 +45,24 @@ const NAV_ACTIONS: readonly (keyof PreviewNavHandle)[] = ['back', 'forward', 're
* wrong one. That trade is worth several hundred ms on every single step. */
const SETTLE_MS = 220
+/** Let a focus/click-triggered re-render COMMIT before aiming a select-all at
+ * the field. The whole bug is that select-all fired against the node the
+ * re-render was about to replace, so its selection died and typing appended.
+ * Short on purpose — the verify + backspace fallback below catches a render
+ * that outlives this window. */
+const TYPE_RENDER_SETTLE_MS = 120
+
+/** How many deterministic backspace-clear passes before giving up instead of
+ * typing into a field we could not empty. Bounded so a pathological page
+ * cannot stall the turn. */
+const TYPE_CLEAR_ATTEMPTS = 2
+
+const TYPE_FAILED_CLEAR =
+ 'The field kept refilling while it was being cleared, so nothing was typed — ' +
+ 'typing would only append to its old value. Click it again and retype, or set the value directly.'
+
+const waitMs = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
+
/** Cap on one round trip into the guest page. A click that starts a navigation
* tears the document down mid-settle, so the injected promise dies with it and
* `executeJavaScript` never settles — without this the tool eats its whole
@@ -306,6 +324,154 @@ ${preamble()}
})()`
}
+/** Report what is focused and would receive keystrokes: its text length and
+ * whether it is a selection-bearing text control (real INPUT/TEXTAREA). Read
+ * AFTER the click so it reflects the node the click's re-render actually left
+ * in place, not the pre-render one. Standalone (no preamble/engine) because it
+ * only reads `document.activeElement`, which is exactly who receives keys. */
+function buildFieldStateScript(): string {
+ return `(function () {
+ try {
+ var el = document.activeElement;
+ if (!el) { return JSON.stringify({ success: true, field: false, len: -1 }); }
+ var value = '';
+ var hasStart = false;
+ try {
+ if (el.value !== undefined) { value = String(el.value || ''); }
+ else if (el.isContentEditable) { value = el.textContent || ''; }
+ } catch (e) {}
+ try { hasStart = typeof el.selectionStart === 'number'; } catch (e) {}
+ return JSON.stringify({
+ success: true,
+ field: hasStart && value.length >= 0,
+ len: value.length
+ });
+ } catch (err) {
+ return JSON.stringify({ success: false });
+ }
+ })()`
+}
+
+/** True selection-bearing field state, or 'unknown' when it is not readable
+ * (focus elsewhere, or a control with no value/selection API). */
+type FieldState =
+ | { ok: false }
+ | { ok: true; field: false }
+ | { ok: true; field: true; len: number }
+
+async function readField(run: PreviewScriptRunner): Promise<FieldState> {
+ const trip = await runJson(run, buildFieldStateScript())
+
+ if (trip.kind !== 'answered' || !trip.result.success) {
+ return { ok: false }
+ }
+
+ const r = trip.result as unknown as { field: boolean; len: number }
+
+ return r.field ? { ok: true, field: true, len: r.len } : { ok: true, field: false }
+}
+
+/** Replace the focused field's whole value with `text`. Returns an error string
+ * if the field could not be cleared, so the caller can FAIL rather than let
+ * typing append to stale content. */
+async function replaceExisting(
+ run: PreviewScriptRunner,
+ input: PreviewInputHandle,
+ text: string,
+ signal?: AbortSignal
+): Promise<string | null> {
+ // (a) Settle after the focus click: let the controlled input's re-render
+ // finish mounting/rebuilding its node before we try to select that node.
+ await waitMs(TYPE_RENDER_SETTLE_MS)
+
+ for (let backspaced = 0; backspaced <= TYPE_CLEAR_ATTEMPTS; backspaced++) {
+ await selectAll(input)
+
+ const state = await readField(run)
+
+ // Can't confirm the field (or it isn't a selection-bearing text control):
+ // trust select-all the way the pre-verification driver did and type.
+ if (!state.ok || !state.field) {
+ break
+ }
+
+ // selectAll worked — nothing is left to type over.
+ if (state.len === 0) {
+ break
+ }
+
+ // selectAll is confirmed NOT working (its selection was lost to a re-render
+ // that reset/replaced the node, or never landed). Give up only after every
+ // deterministic clear has also failed.
+ if (backspaced === TYPE_CLEAR_ATTEMPTS) {
+ return TYPE_FAILED_CLEAR
+ }
+
+ // (b) Clear without relying on a selection: End parks the caret at the
+ // tail, then one Backspace per remaining character.
+ await clearCharsBack(input, state.len)
+ }
+
+ await typeText(input, text, signal)
+ return null
+}
+
+/** Set a focused field's value directly through its own DOM setter — no
+ * keystrokes. This is the fallback for inputs a money/number/date mask makes
+ * hostile to real typing: the mask keeps re-applying its own formatting, so
+ * select-all and even End+Backspace never produce an empty field. Assigning
+ * through the native prototype setter (as the scripted engine does) commits
+ * the value in a way controlled React inputs accept, then dispatches input +
+ * change so the page records it. */
+function buildDirectSetScript(text: string): string {
+ return `(function () {
+ try {
+ var el = document.activeElement;
+ if (!el) { return JSON.stringify({ success: false, error: 'no focused field' }); }
+ var setVal = null;
+ if (el.tagName === 'TEXTAREA') { setVal = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set; }
+ else if (el.tagName === 'INPUT') { setVal = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set; }
+ if (setVal) { setVal.call(el, ${JSON.stringify(text)}); }
+ else if ('value' in el) { el.value = ${JSON.stringify(text)}; }
+ else if (el.isContentEditable) { el.textContent = ${JSON.stringify(text)}; }
+ else { return JSON.stringify({ success: false, error: 'not a text field' }); }
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ el.dispatchEvent(new Event('change', { bubbles: true }));
+ return JSON.stringify({ success: true });
+ } catch (err) {
+ return JSON.stringify({ success: false, error: String(err) });
+ }
+ })()`
+}
+
+/** Type into the focused field, and if real keystrokes could not clear a
+ * masked/hostile input (money, date, number masks that keep re-formatting),
+ * fall back to setting the value directly through the DOM. Returns null on
+ * success or a clear error. */
+async function setFocusedField(
+ run: PreviewScriptRunner,
+ input: PreviewInputHandle,
+ text: string,
+ signal?: AbortSignal
+): Promise<string | null> {
+ const clearError = await replaceExisting(run, input, text, signal)
+
+ // Real keystrokes cleared it and typed fine — no fallback needed.
+ if (!clearError) {
+ return null
+ }
+
+ // Real keystrokes could not empty the field (a mask keeps refilling it).
+ // Fall back to a direct DOM value-set, which bypasses the mask.
+ const trip = await runJson(run, buildDirectSetScript(text))
+
+ if (trip.kind !== 'answered') {
+ return clearError
+ }
+
+ return trip.result.success ? null : clearError
+}
+
/** The outcome of one round trip into the page. `silent` is its own case on
* purpose: a page that stops answering mid-action is navigating, whereas one
* that answers with nothing is broken, and the agent needs to hear the
@@ -451,15 +617,17 @@ async function driveAction(
return stoppedType(signal, 0, text.length)
}
- // Select-all inside the now-focused field, so typing replaces what is there
- // the way it would for a person. NOT a triple-click: that is a pointer
- // gesture and selects the paragraph under the cursor whenever the target
- // turns out not to be a field.
- await selectAll(input)
- const typed = await typeText(input, text, signal)
-
- if (signal?.aborted) {
- return stoppedType(signal, typed, text.length)
+ // Select-and-replace the field's existing value. This is the one spot that
+ // survives a controlled React input re-rendering on focus/click: settle
+ // first, verify the select actually cleared the field, and if the page
+ // threw the selection away we empty it with End+Backspace instead of
+ // typing over — never append to stale content. If real keystrokes cannot
+ // clear a masked field at all (money/date/number masks keep refilling it),
+ // fall back to setting the value directly through the DOM.
+ const setError = await setFocusedField(run, input, text, signal)
+
+ if (setError) {
+ return { error: setError, success: false }
}
if (action.submit) {
diff --git a/apps/desktop/src/app/chat/right-rail/preview-drive.ts b/apps/desktop/src/app/chat/right-rail/preview-drive.ts
index 993d2689a02..10f2d403101 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-drive.ts
+++ b/apps/desktop/src/app/chat/right-rail/preview-drive.ts
@@ -16,6 +16,8 @@
import type { PreviewInputHandle } from './preview-input'
+import { isMacPlatform } from '@/lib/platform'
+
export interface DrivePoint {
x: number
y: number
@@ -121,21 +123,50 @@ export async function pressKey(input: PreviewInputHandle, key: string): Promise<
* click is a POINTER gesture, so it selects whatever paragraph sits under the
* cursor whenever the target turns out not to be a field, and the agent was
* leaving pages with their body text highlighted. There is no `char` phase —
- * a chord is not text entry, and sending one types a literal 'a'. */
+ * a chord is not text entry, and sending one types a literal 'a'.
+ *
+ * The chord is the OS's select-all: Cmd+A on macOS, Ctrl+A everywhere else.
+ * Sending both modifiers at once is not a chord any platform acts on, so the
+ * select silently did nothing and typing APPENDED to the field's existing
+ * value — visible corruption (e.g. a 9.99 price became 19999.99). */
export async function selectAll(input: PreviewInputHandle): Promise<void> {
- const chord = ['control', 'meta']
+ const chord = isMacPlatform() ? ['meta'] : ['control']
input.send({ keyCode: 'a', modifiers: chord, type: 'keyDown' })
input.send({ keyCode: 'a', modifiers: chord, type: 'keyUp' })
await wait(KEY_MS)
}
+/** Press a control key (End, Backspace, …) with NO `char` phase. A `char`
+ * phase would type the key's literal meaning for editable content, which a
+ * deletion or caret move must never do. */
+export async function pressControlKey(input: PreviewInputHandle, key: string): Promise<void> {
+ input.send({ keyCode: key, type: 'keyDown' })
+ input.send({ keyCode: key, type: 'keyUp' })
+ await wait(KEY_MS)
+}
+
+/** Empty the focused field deterministically: park the caret at the tail, then
+ * Backspace `count` characters. Independent of any active selection, so it
+ * still works when a re-render has just thrown a whole-field selection away —
+ * End collapses any selection to the caret, and each Backspace is a real,
+ * trusted key the page (React included) applies to the DOM as it stands.
+ * `count` is the field's value length in UTF-16 code units. */
+export async function clearCharsBack(input: PreviewInputHandle, count: number): Promise<void> {
+ await pressControlKey(input, 'End')
+
+ for (let i = 0; i < count; i++) {
+ await pressControlKey(input, 'Backspace')
+ }
+}
+
/** Type `text` a character at a time into whatever currently has focus.
*
* Checks `signal` between characters. A timeout or interrupt aborts the
* signal while this loop is still queued; without the check those keystrokes
* keep landing after the tool has already given up. The character in flight
- * has already been sent — the rest are not. */
+ * has already been sent — the rest are not. Returns how many characters
+ * were actually sent before an abort. */
export async function typeText(input: PreviewInputHandle, text: string, signal?: AbortSignal): Promise<number> {
let typed = 0