Skip to content

The agent that grows with you

fix(desktop): stop the edit composer's timers from outliving it

Jack Lau37a8c10ab125
diff --git a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
index d9bf458c80c..a61409b3aeb 100644
--- a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx
@@ -118,6 +118,24 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
const slash = useSlashCompletions({ gateway })
const emoji = useEmojiCompletions()
+ // Timers this composer schedules must not outlive it. Every callback below
+ // touches component state, a ref or the composer core, and this is the one
+ // composer that routinely unmounts mid-flight: confirming an edit tears it
+ // down while the 200ms submit latch is still pending, so the latch resumes
+ // against an unmounted tree. Two of the callbacks already carry defensive
+ // try/catch for the racing-teardown case; clearing the timers removes the
+ // race instead of surviving it.
+ const pendingTimeoutsRef = useRef<Set<number>>(new Set())
+
+ const scheduleTimeout = useCallback((run: () => void, delayMs: number): void => {
+ const id = window.setTimeout(() => {
+ pendingTimeoutsRef.current.delete(id)
+ run()
+ }, delayMs)
+
+ pendingTimeoutsRef.current.add(id)
+ }, [])
+
// This is the one composer that routinely unmounts, so it is where the focus
// bus leaks: confirming or cancelling an edit tears the composer down while
// `'edit'` is still the active target. Release it alongside the thread-scroll
@@ -126,6 +144,12 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
() => () => {
notifyThreadEditClose()
releaseActiveComposer('edit')
+
+ for (const id of pendingTimeoutsRef.current) {
+ window.clearTimeout(id)
+ }
+
+ pendingTimeoutsRef.current.clear()
},
[]
)
@@ -341,7 +365,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
draftRef.current = composerPlainText(editor)
aui.composer().setText(draftRef.current)
requestEditFocus()
- starter ? window.setTimeout(refreshTrigger, 0) : closeTrigger()
+ starter ? scheduleTimeout(refreshTrigger, 0) : closeTrigger()
}
// In place first, spanning Chromium's split text nodes (see
@@ -360,7 +384,16 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
finish()
},
- [aui, closeTrigger, recordUndoPoint, refreshTrigger, rememberInitialDraft, requestEditFocus, trigger]
+ [
+ aui,
+ closeTrigger,
+ recordUndoPoint,
+ refreshTrigger,
+ rememberInitialDraft,
+ requestEditFocus,
+ scheduleTimeout,
+ trigger
+ ]
)
const insertRefStrings = useCallback(
@@ -526,11 +559,11 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
rememberInitialDraft()
const nextDraft = syncDraftFromEditor(editor)
- window.setTimeout(refreshTrigger, 0)
+ scheduleTimeout(refreshTrigger, 0)
return nextDraft
},
- [refreshTrigger, rememberInitialDraft, syncDraftFromEditor]
+ [refreshTrigger, rememberInitialDraft, scheduleTimeout, syncDraftFromEditor]
)
const handleInput = (event: FormEvent<HTMLDivElement>) => {
@@ -602,7 +635,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
// Clear latch after cooldown to allow re-submission. This prevents rapid
// double-Enter but doesn't require tracking when onEdit settles (which may
// be synchronous or async, and whose promise we don't have access to).
- window.setTimeout(() => {
+ scheduleTimeout(() => {
setSubmitting(false)
}, 200)
} catch {
@@ -618,7 +651,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
return
}
- window.setTimeout(() => {
+ scheduleTimeout(() => {
const root = rootRef.current
const active = document.activeElement
@@ -653,7 +686,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
}
}, 80)
},
- [aui, closeTrigger, submitting, syncDraftFromEditor]
+ [aui, closeTrigger, scheduleTimeout, submitting, syncDraftFromEditor]
)
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
@@ -810,7 +843,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sess
data-placeholder={copy.editMessage}
data-slot={RICH_INPUT_SLOT}
onBeforeInput={handleBeforeInput}
- onBlur={() => window.setTimeout(closeTrigger, 80)}
+ onBlur={() => scheduleTimeout(closeTrigger, 80)}
onCompositionEnd={event => {
composingRef.current = false
flushEditorToDraft(event.currentTarget)
diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx
index bd441fdb445..5befc0515d8 100644
--- a/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx
@@ -233,6 +233,63 @@ describe('Enter submission and latch behavior', () => {
})
})
+ // Confirming an edit unmounts the composer while its 200ms submit latch is
+ // still pending. Left running, the callback resumes on an unmounted tree and
+ // calls setSubmitting, which React turns into work against a torn-down
+ // renderer. Under vitest that surfaces after the test file finishes, as
+ // "ReferenceError: window is not defined" out of resolveUpdatePriority, an
+ // unhandled error that fails a run in which every test passed. The delay is
+ // matched explicitly so unrelated library timers cannot make this pass.
+ it('clears the submit latch timer when confirming the edit unmounts the composer', async () => {
+ const LATCH_MS = 200
+ // jsdom under node hands back a Timeout object rather than a numeric id,
+ // so these are compared by identity rather than by value.
+ const scheduled: unknown[] = []
+ const cleared: unknown[] = []
+ const realSetTimeout = window.setTimeout.bind(window)
+ const realClearTimeout = window.clearTimeout.bind(window)
+
+ vi.spyOn(window, 'setTimeout').mockImplementation(((
+ handler: TimerHandler,
+ timeout?: number,
+ ...args: unknown[]
+ ) => {
+ const id = realSetTimeout(handler, timeout, ...args)
+
+ if (timeout === LATCH_MS) {
+ scheduled.push(id)
+ }
+
+ return id
+ }) as typeof window.setTimeout)
+
+ vi.spyOn(window, 'clearTimeout').mockImplementation(((id?: number) => {
+ cleared.push(id)
+ realClearTimeout(id)
+ }) as typeof window.clearTimeout)
+
+ const onEdit = vi.fn(async () => {})
+ const view = render(<IncrementalHarness onEdit={onEdit} />)
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit message' }))
+
+ const editor = await screen.findByRole('textbox', { name: 'Edit message' })
+
+ editor.textContent = 'an edit whose composer goes away before the latch expires'
+ fireEvent.input(editor)
+ fireEvent.keyDown(editor, { key: 'Enter' })
+
+ await waitFor(() => {
+ expect(onEdit).toHaveBeenCalledTimes(1)
+ })
+
+ expect(scheduled).toHaveLength(1)
+
+ view.unmount()
+
+ expect(cleared).toContain(scheduled[0])
+ })
+
it('inserts a newline on Shift+Enter without submitting', async () => {
const onEdit = vi.fn(async () => {})
render(<IncrementalHarness onEdit={onEdit} />)