Skip to content

Fix paste burst detection logic and timing thresholds - #3371

Closed
adsqx wants to merge 6 commits into
openai:mainfrom
adsqx:fix/paste-burst-logic
Closed

adsqx wants to merge 6 commits into
openai:mainfrom
adsqx:fix/paste-burst-logic

Conversation

@adsqx

@adsqx adsqx commented Sep 9, 2025 •

Copy link
Copy Markdown

Improves paste burst detection logic (16ms interval, guard delay) and reduces test flakiness; enhances whitespace/length heuristics.

Inter-char threshold: 16 ms (from 8 ms) to reduce flakes on slower machines while still masking during paste bursts.
Flush delay: +8 ms above threshold for stable post-burst flush (jitter margin).
Retro-grab: start buffering after ≥2 rapid chars, preventing the 3rd char from leaking; small bursts insert text, large bursts get a placeholder.

- Increased character interval to 16ms to reduce flakiness
- Added guard delay for reliable test timing
- Improved detection of paste-like bursts with whitespace or long strings

@nornagon-openai nornagon-openai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm worried that this will introduce lag during regular typing, as we delay displaying characters until we decide that the input isn't part of a paste burst.

@adsqx

adsqx commented Sep 10, 2025 •

Copy link
Copy Markdown
Author

@nornagon-openai
This was a change introduced solely to avoid test errors when I implemented reactive loading of MCP. Most likely, some issue occurred due to the program starting up too quickly, so the timeout had to be increased.

I submitted the PR based on @bolinfest request/recommendation — not entirely sure which word fits better here. If there are any doubts, I’m not attached to pushing a pointless PR :)

I personally use Codex and would love to see it working as smoothly as possible. If this is just about gaining “credit,” I’m totally fine with closing it.

Hopefully, the issue with program not found and requested timeout in the context of MCP loading can be resolved.

Maybe someday there will be an opportunity to submit something meaningful :)

@adsqx

adsqx commented Sep 12, 2025

Copy link
Copy Markdown
Author

I'm worried that this will introduce lag during regular typing, as we delay displaying characters until we decide that the input isn't part of a paste burst.

In practice — no.
16 ms is ~62 characters/s (1000/16). Typical fast human typing speed is about 10–20 chars/s, which translates to ~50–100 ms between consecutive characters. Statistically, humans don’t produce 3 consecutive characters with intervals ≤16 ms, so the “paste-burst” threshold is safe relative to normal typing.

Blink duration: usually ~100–150 ms.

Typical sources of false positives (non-human or system-level):

  1. Event queue flush after a “freeze” — handling many keydowns at once results in artificially small measured intervals.

  2. IME/autocorrect/snippets — committing an entire word or batch of characters “at once.”

  3. Macros / auto-repeat / bots / e2e tests — generate events spaced just a few to a dozen ms apart.

  4. Link lag (Bluetooth/USB) + burst delivery — transport jitter causes events to arrive bunched together.

Input/rendering latency (roughly):

Keyboard → OS: wired often ~1–10 ms, Bluetooth typically ~7–30 ms.

Event loop / scheduler: from a few to several dozen ms depending on system load.

Rendering at 60 Hz: one frame ≈ 16.7 ms; blocking one or two frames can “compress” timestamps of consecutive keystrokes.

Conclusion:
A 16 ms threshold targets paste/automation dynamics rather than human typing speeds; a 120 ms window ≈ one blink effectively protects UX against accidental submissions during bursts.

@dylan-hurd-oai dylan-hurd-oai left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AdsQnn I'm happy to do some experimenting with tweaking this interval, but we need to address FlushResult, since chat_composer.ts depends on this type and this change won't compile in its current form.

Sharing screen recordings of typing/pasting on windows, as well as linux and/or mac platform will help speed up review here.

Paste(String),
Typed(char),
None,
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why remove this?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I described it in full below, but I did it quite a while ago, so I don’t remember all the details.
It was also about 10 versions ago :)

@adsqx

adsqx commented Oct 18, 2025

Copy link
Copy Markdown
Author

@dylan-hurd-oai
This was not just the removal of an enum, but a change in the underlying model.
Instead of returning FlushResult::{Paste, Typed, None}, the function flush_if_due() now returns Option.

Purpose of the change: simplification and encapsulation of logic.
All state handling (pending_first_char, burst_window, Enter suppression) is now contained within PasteBurst, so higher-level code no longer needs to distinguish between event types.

Advantages:

Simpler API – the caller only checks whether there is text to insert.

Better encapsulation – detection details remain internal to the class.

More stable behavior and testing – fewer edge cases.

Eliminates UI flicker during fast paste sequences.

Disadvantages:

Loss of semantic distinction between Typed and Paste (may affect telemetry or undo tracking).

Minor allocation cost due to to_string() for single characters.

Assessment: the change is good – it simplifies the code, improves UX, and enhances testability.
The enum was only needed internally; after refactoring, it became unnecessary.

Exactly like in belief propagation — each node operates locally, passing upward its resulting estimation rather than raw observations.
This reduces computational redundancy, simplifies the flow of information, and increases system coherence. :)

FlushResult, since chat_composer.ts depends on this type

You're right — that's why I'm a fan of something like belief propagation and a modular approach.
If a project’s entire dependency chain flows upward from a single module, even a small change can require refactoring half of the codebase.

I just dropped it in because it came to mind when I saw it.

#2968
The fix was actually part of a larger PR, and I added this at @bolinfest request :)
And from what I remember, you mentioned that you had already tested this case on your side.

No worries — I just mentioned it because I believe the remaining PRs listed below will eventually need to be implemented as well.

I think it’s not worth trying to fix this by force — it’s better to rewrite it from scratch for the current version.

I’ll close this PR shortly, so all good :)
Just added it for informational purposes.

@codex Am I right about this, or am I mistaken? It might need some refinement, but I mean the general concept.

Thanks for the constructive discussion, and good luck with the ongoing work on Codex!

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 100 to +115
/// now emit that char as normal typed input.
///
/// Returns None if the timeout has not elapsed or there is nothing to flush.
pub fn flush_if_due(&mut self, now: Instant) -> FlushResult {
pub fn flush_if_due(&mut self, now: Instant) -> Option<String> {
let timed_out = self
.last_plain_char_time
.is_some_and(|t| now.duration_since(t) > PASTE_BURST_CHAR_INTERVAL);
if timed_out && self.is_active_internal() {
self.active = false;
let out = std::mem::take(&mut self.buffer);
FlushResult::Paste(out)
Some(out)
} else if timed_out {
// If we were saving a single fast char and no burst followed,
// flush it as normal typed input.
if let Some((ch, _at)) = self.pending_first_char.take() {
FlushResult::Typed(ch)
Some(ch.to_string())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P0 Badge Adjust chat compositor to Option-based flush result

Replacing flush_if_due’s return type with Option<String> and dropping the FlushResult enum requires all call sites to change, but chat_composer still imports FlushResult and matches on its variants. The project will no longer compile because the enum no longer exists and the call now expects an Option<String>. Update the caller (e.g., handle_paste_burst_flush) to handle the new API or keep the enum.

Useful? React with 👍 / 👎.

@adsqx adsqx Oct 18, 2025 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, that part was already clear — what I actually wanted to know is whether it’s better, overall, to stick with the current PasteBurst implementation using Option, or to bring back the FlushResult version

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

To use Codex here, create an environment for this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔧 Potential improvements

1️⃣ is_active() semantics

Current:

pub fn is_active(&self) -> bool {
    self.is_active_internal() || self.pending_first_char.is_some()
}

Issue: pending_first_char ≠ active paste — it's only "maybe".
Proposal:

  • is_active() → only when we’re actually buffering
  • has_pending_state() → when we’re awaiting a decision

2️⃣ Duplicated time-window logic

Repeated pattern:
self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
Extract helper:

fn extend_suppress_window(&mut self, now: Instant) {
    self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
}


3️⃣ decide_begin_buffer does too much

It currently:

  • decides whether to start buffering
  • mutates state (begin_with_retro_grabbed)
  • returns what to remove from the UI

Split responsibilities:

Pure decision:

fn should_retro_grab(&self, grabbed: &str, retro_chars: usize) -> bool {
    // heuristic logic
}

State mutation only:

pub fn begin_with_retro_grabbed(&mut self, grabbed: String, now: Instant) {
    // ...
}

4️⃣ Magic number in heuristic

Current:
|| grabbed.chars().count() >= 16
Why 16? Extract a named constant with context:
const PASTE_HEURISTIC_MIN_LENGTH: usize = 16; // Typical threshold for URLs/paths

@dylan-hurd-oai

Copy link
Copy Markdown
Contributor

All state handling (pending_first_char, burst_window, Enter suppression) is now contained within PasteBurst, so higher-level code no longer needs to distinguish between event types.

This is a reasonable argument to me - can you rebase the PR and update chat_composer.rs accordingly?

@adsqx

adsqx commented Oct 20, 2025

Copy link
Copy Markdown
Author

@dylan-hurd-oai Ok, I can take this on. However, I’d need about 24–48 hours, because I’d like to test it properly. At the moment, for example, paste doesn’t work for me at all on Ubuntu. I’ll try to get it done as quickly as possible. Let me know if that works for you.

@adsqx

adsqx commented Oct 21, 2025 •

Copy link
Copy Markdown
Author

2025-10-21T00:42:17.364881Z DEBUG ChatComposer::handle_paste_image_path attempt preview=11;rgb:1818/1818/1818
Zrzut ekranu z 2025-10-20 02-32-57

I’m facing a strange situation — in the regular terminal, short text pastes work fine, but long ones don’t. In contrast, in VS Code’s terminal, it’s the opposite: long pastes work, but short ones don’t. I’m trying to track down the cause and log it properly. I’ve also noticed that the input occasionally gets random entries like rgb:1818/1818/1818 appearing repeatedly. I mean that they don’t get pasted at all.

Zrzut ekranu z 2025-10-21 02-48-14

Okay, I’m getting closer — I can see that when I press Ctrl+V, it tries to paste an image even though I’ve copied text. Clearly, when I pasted something starting with rgb/1818..., it sent immediately, so it’s not a timing issue — something breaks there, and most likely that specific sequence triggers it.
Zrzut ekranu z 2025-10-21 03-30-37

And at that moment, when I pasted again right after the rgb, the message was sent immediately.
Additionally, you can see that I pasted it only once, but it got duplicated and misaligned.

That means the rgb/1818 part appears on its own, even when I’m not pasting anything — and if I paste something long right after it shows up, the message gets sent instantly.

So I believe that the logic handling image pasting might be causing some kind of disruption in how this works. But I’ll keep trying to pinpoint it further.

Alright, I figured it out — the RGB value comes from the terminal’s color output. Something might be wrong with how that’s handled.
It’s just that something in the background seems to be pasting by itself.

Zrzut ekranu z 2025-10-21 03-55-01

I’ve disabled image insertion, so it’s probably not that.
The problem clearly started after one of the updates — everything was working perfectly before that.

Problem solved.

Problem: requery_default_colors() in tui.rs

What was happening:

  1. On every FocusGained event (when clicking on the terminal), the code sent an OSC query to the terminal:
    \x1b]10;?\x07\x1b]11;?\x07
    (asking for the foreground/background colors)
  2. The terminal responded with:
    \x1b]10;rgb:1818/1818/1818\x07
  3. This response leaked into the input stream and appeared as rgb/1818/... in your input field!

Solution:
Disable crate::terminal_palette::requery_default_colors() in tui.rs:381

Location:
codex-rs/tui/src/tui.rs:377–382 — inside the FocusGained event handler

That’s it. The rest of the code (PasteBurst, bracketed paste) was perfectly fine.

I doubt the cause was PasteBurst, since bracketed paste already handles most terminals anyway. I tested it with PasteBurst disabled, and the issue is fixed — nothing gets sent automatically anymore, even when pasting very long text.

I also have the impression that the / in rgb is causing some kind of conflict — the logs show it’s trying to load something as an image, resulting in an “Err: no such file or directory.”

All the issues with missing pastes, duplication (like in the screenshot), and unintended message sending have completely disappeared :) Even after I fully disconnected the system PasteBurst.

On Windows, it’s possible that the output didn’t reach the input field directly — something might have filtered it — but it definitely entered the paste queue and disrupted the cycle, because there’s no way it didn’t. This would also explain the timing differences observed between the system terminal and VS Code. Most likely, that’s the real cause.

Ah, and I tested various timing values for the paste burst, but it never fixed the problem.

We could work on fixing this further — so what’s the next step?
Should we proceed independently with the PasteBurst and ChatComposer parts?
Are you planning to handle this fix on your own, or should I include it in the same PR?

@dylan-hurd-oai

dylan-hurd-oai commented Oct 23, 2025 •

Copy link
Copy Markdown
Contributor

@AdsQnn if the problem is requery_default_colors() in tui.rs, are you planning on putting up a new PR with that fix? Or are you still planning on rebasing and fixing this PR? The current code does not compile.

@adsqx

adsqx commented Oct 23, 2025 •

Copy link
Copy Markdown
Author

@dylan-hurd-oai I’d prefer an entirely new one. I’m just asking whether you’d rather handle it yourselves or should I upload it. Should I include only that part, or also slightly increase the Paste Burst just in case and upload that too?

I’ve shared the whole process so it’s clear what everything comes from — I’m not guessing :) I’m certain the issue lies right there. I just wrote here to confirm whether you’re okay with this, so there’s no misunderstanding before I create a separate PR.

In the attached thread, the author mentions that they also had the same kind of input leak on Windows.

I mean that I don’t want to impose anything, so I’m asking before I do anything :)

@dylan-hurd-oai

Copy link
Copy Markdown
Contributor

@AdsQnn new PR is fine! Tag me on it. Please ensure:

  • it is rebased against a recent commit on main
  • the code compiles
  • you have a clear repro case that no longer occurs with your change

@adsqx

adsqx commented Oct 25, 2025 •

Copy link
Copy Markdown
Author

There’s an issue with “paste burst” that I’m trying to solve. Normally, everything is handled by bracketed paste, and that part works fine. But in order to properly test paste-burst, I’m testing it with bracketed paste disabled.

The problem is that the terminal sends long pasted text in chunks of 1, 2, or 4 KB (1024 or 2048 characters). So when I paste, for example, 4000 characters, this happens:

First I get: [paste 2048 chars]

Then nothing happens until I press any key, and only then I receive something like [paste ~1000 chars], and so on…

In other words, the first chunk arrives immediately, but the next chunks stay buffered and are only flushed when a new input event occurs (e.g., pressing a key).

So for paste-burst to behave as intended, I need to solve this packet-splitting / buffering issue. Something seems to be delaying or holding back the remaining chunks. This is a separate problem from bracketed paste itself — because bracketed paste would intercept everything anyway. But if I want paste-burst to work correctly on its own, I need to deal with this packetization behavior.

With paste-burst, the kernel may push, for example, 4 chunks of 1024 bytes into the PTY buffer. The application only receives a single POLLIN, performs one read(), and consumes just the first 1024-byte chunk. The remaining data stays in the buffer because no further input event is generated. Only pressing any key triggers another POLLIN, and only then can the next chunks be read.

That’s why after each POLLIN, you need to read in a loop until EAGAIN, to drain all chunks immediately.

So in most cases, bracketed paste will work anyway, and the rgb/1818 issue is still a real one.

Even though paste burst is used very rarely in practice and most terminals support bracketed paste, I just want it to work the way it should.

@etraut-openai

Copy link
Copy Markdown
Contributor

It looks like this PR is no longer relevant, so closing.

@github-actions github-actions Bot locked and limited conversation to collaborators Oct 30, 2025
@openai openai unlocked this conversation Oct 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants