Skip to content

Fast Enter, Enter, Backspace on an empty block deletes the new block, and letters typed meanwhile are lost #1535

Closed

Description

@jariji

Search first

  • I searched and no similar issues were found

What Happened?

Note from human author: This issue is drafted by Claude Opus 5.5. As far as I can tell it's correct, but I personally can't type fast enough to reproduce the issue it's talking about on test.logseq.com; the reproduction below uses scripted key events. The issue was discovered by property testing on a local fork. I have drafts of a few other problems but I'll wait for your permission before posting them since I don't know how you feel about AI-drafted issues.

[Claude content follows.]


On an empty block, I press Enter, Enter, Backspace quickly, before the first Enter's new block appears. Logseq ends with one block instead of two.

On an empty block, I press Enter, type x y and press Backspace quickly. Logseq ends with one empty block instead of an empty block and a block x: the new block and the typed letters are gone.

I reproduced the first case on https://test.logseq.com/ (2.0.2) and both cases on a desktop build of logseq/logseq@a0f4399. Related: #821 (rapid Enter then Tab), which involves the same code path.

Reproduce the Bug

The keys must arrive while the first Enter's insert is still pending. On test.logseq.com that window lasts about 40–60 ms, so two keys inside it are faster than most people type; on a large graph the window lasts longer (see Additional Context). A script that sends real key events over the Chrome DevTools Protocol reproduces the bug every time (see Files).

By hand:

  1. Create a page with one empty block and click into it.
  2. Press Enter, Enter, Backspace as fast as possible.
  3. One block remains.

With the script (tested with the desktop app):

  1. Start Logseq Desktop with --remote-debugging-port=9333 and open a throwaway DB graph.
  2. Run LOGSEQ_CDP_PORT=9333 LOGSEQ_TEST_GRAPH=<graph name> node repro.mjs enter-enter-backspace (Node 22 or later). The script creates a page zz-repro-... with one empty block, opens the editor on it and sends the keys with no pause.
  3. Restart Logseq and run the script with enter-x-y-backspace. A restart is needed because after the first case the block view can crash ("Missing renderer resource entity"), which I will report separately.

Expected Behavior

Keys on an empty block Expected blocks Actual blocks
Enter, Enter, Backspace "", "" ""
Enter, x, y, Backspace "", "x" ""

The same keys typed slowly (1 s apart) give the expected blocks.

Screenshots

No response

Files

repro.mjs
// Reproduces: fast Enter then Backspace on an empty block deletes the new block instead of undoing the last key
// Start the Logseq desktop app with --remote-debugging-port=PORT, open a throwaway DB graph, then:
//   LOGSEQ_CDP_PORT=PORT LOGSEQ_TEST_GRAPH=<graph name> node repro.mjs [case-label]
// Node 22 or later (built-in WebSocket). The script creates pages named zz-repro-... in the
// graph and leaves them there. It types real key events with no pause between them, so the keys
// arrive while the first Enter's insert is still pending in the database worker.
// --- Connection (shared by the reproducers in this directory tree; copied into each script) ---
const port = Number(process.env.LOGSEQ_CDP_PORT);
const testGraph = process.env.LOGSEQ_TEST_GRAPH;
if (!port || !testGraph) {
  console.error('Set LOGSEQ_CDP_PORT (the --remote-debugging-port of Logseq) and LOGSEQ_TEST_GRAPH (the name of the open throwaway graph).');
  process.exit(2);
}
const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = reject; });
let nextId = 0;
const pending = new Map();
const listeners = [];
ws.onmessage = ({ data }) => {
  const msg = JSON.parse(data);
  if (msg.id !== undefined) { pending.get(msg.id)?.(msg); pending.delete(msg.id); }
  else listeners.forEach(f => f(msg));
};
const send = (method, params = {}) => new Promise(resolve => {
  const id = ++nextId; pending.set(id, resolve); ws.send(JSON.stringify({ id, method, params }));
});
const evaluate = async (expression, awaitPromise = false) => {
  const r = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise });
  if (r.result?.exceptionDetails) throw new Error(JSON.stringify(r.result.exceptionDetails).slice(0, 300));
  return r.result?.result?.value;
};
const api = async (method, ...args) => JSON.parse(await evaluate(
  `(async () => JSON.stringify(await logseq.api.${method}(...${JSON.stringify(args)}) ?? null))()`, true));
const sleep = ms => new Promise(r => setTimeout(r, ms));
const graph = await api('get_current_graph');
if (!String(graph?.name ?? '').includes(testGraph) && !String(graph?.url ?? '').includes(testGraph)) {
  console.error(`The open graph (${graph?.name}) is not ${testGraph}; refusing to edit it.`);
  process.exit(2);
}

const KEYS = {
  enter: { key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 },
  backspace: { key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 },
  escape: { key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 },
};
async function press(k) {
  if (KEYS[k]) {
    await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', ...KEYS[k] });
    await send('Input.dispatchKeyEvent', { type: 'keyUp', ...KEYS[k] });
    return;
  }
  const code = `Key${k.toUpperCase()}`, vk = k.toUpperCase().charCodeAt(0);
  await send('Input.dispatchKeyEvent', { type: 'keyDown', key: k, code, text: k, unmodifiedText: k, windowsVirtualKeyCode: vk });
  await send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk });
}

// Creates a page with one block whose text is `seedText`, opens the editor on that block with the
// caret at the end, and resolves to the page name, or to null when the editor does not open.
async function editNewPage(label, seedText) {
  const name = `zz-repro-${label}-${Date.now()}`;
  await api('create_page', name, {}, { redirect: false });
  const seed = await api('append_block_in_page', name, seedText);
  await evaluate(`void logseq.api.push_state('page', {name: ${JSON.stringify(name)}})`);
  await sleep(1200);
  for (let attempt = 0; attempt < 5; attempt++) {
    await evaluate(`void logseq.api.edit_block(${JSON.stringify(seed.uuid)})`);
    await sleep(600);
    if (await evaluate(`document.activeElement?.tagName === 'TEXTAREA'`)) {
      await evaluate(`(() => { const t = document.activeElement; t.setSelectionRange(t.value.length, t.value.length); })()`);
      return name;
    }
  }
  return null;
}

// Sends `keys` with no pause between them, waits for the inserts to land, leaves editing, and
// resolves to the titles of the page's top-level blocks.
async function typeAndRead(name, keys) {
  for (const k of keys) await press(k);
  await sleep(2500);
  await press('escape');
  await sleep(800);
  return (await api('get_page_blocks_tree', name)).map(b => b.title);
}
// --- end of connection code ---

const CASES = [
  { label: 'enter-enter-backspace', seed: '', keys: ['enter', 'enter', 'backspace'], expected: ['', ''] },
  { label: 'enter-x-y-backspace', seed: '', keys: ['enter', 'x', 'y', 'backspace'], expected: ['', 'x'] },
];

let failures = 0;
// A case label as the first argument runs only that case.
const only = process.argv[2];
for (const { label, seed, keys, expected } of CASES.filter(c => !only || c.label === only)) {
  const name = await editNewPage(label, seed);
  if (name === null) {
    console.log(`STOP ${label}: the editor did not open. On affected builds the previous case can break the block view ("Missing renderer resource entity"); restart Logseq and run the next case by its label.`);
    process.exit(3);
  }
  const titles = await typeAndRead(name, keys);
  const ok = JSON.stringify(titles) === JSON.stringify(expected);
  if (!ok) failures++;
  console.log(`${ok ? 'ok  ' : 'FAIL'} seed ${JSON.stringify(seed)}, keys ${keys.join(' ')}: blocks ${JSON.stringify(titles)}${ok ? '' : `, expected ${JSON.stringify(expected)}`}`);
}
ws.close();
process.exit(failures ? 1 : 0);

Browser, Desktop or Mobile Platform Information

Additional Context

Timing. The bug occurs only when keys arrive before the landing callback moves the editor to the new block. The window lasts as long as the insert takes, measured from the Enter keydown to the focus of the new block's editor:

Setup Enter to the new block's editor
test.logseq.com 2.0.2, demo graph, 8 single Enters 38–60 ms (median 46 ms)
desktop a0f4399, synthetic graph of 300,000 blocks, page open, warm cache p50 63 ms, p99 132 ms
the same graph, cold page cache p50 124 ms, p99 272 ms
the same graph, today's journal on the Journals view (built-in queries on) p50 232 ms, p99 4547 ms

Enter, Enter, Backspace needs two keys inside the window, and Enter, x, y, Backspace needs three. A fast typist leaves about 100–150 ms between keys, so the window rarely catches a person on a small graph but catches ordinary typing on a large graph, after a cold start, or on a view with slow queries.

Cause. While an Enter's insert is pending, keydown-backspace-handler (editor.cljs#L3009) calls (backspace-pending-new-block! (zero? (util/get-selection-start (.-target e)))). The editor has not moved yet, so .-target is the textarea of the source block, and on an empty source block its caret is always 0. backspace-pending-new-block! (editor.cljs#L342) then sets :delete? true instead of removing the last typed letter, and the landing callback inserted-block-edit-fn (editor.cljs#L360) deletes the new block.

logseq/logseq@223f755bb6 added the delete-block? argument for a later moment: once the landing callback has moved the editor to the new block, the caret belongs to that block, and a caret at 0 means the user deletes it (e2e test backspace-at-start-removes-pending-block-dom-test).

Suggested fix. Use the caret only after the landing callback has started. Before that, the user types into the provisional row, where the caret stays at the end of the typed text. I have a fix with a regression test on top of logseq/logseq#13782 and can open a PR.

Are you willing to submit a PR? If you know how to fix the bug.

  • I'm willing to submit a PR (Thank you!)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions