fix(desktop): dismiss stale channel autocomplete before edit submit

Cancel pending channel lookup and close the tray immediately when the live
text no longer has a channel query. Keep valid-query suggestions debounced.
This prevents Enter from inserting the old channel at an obsolete offset
after replacing an edit body.

Freeze the debounce window in the non-empty edit browser regression and
cover immediate invalidation, canceled publication and retained valid-query
debouncing through the production hook.

Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
Signed-off-by: Wes <wesbillman@users.noreply.github.com>
This commit is contained in:
Wes
2026-09-10 11:17:38 -06:00
committed by Carl
parent c09b661867
commit 08a6bf3948
3 changed files with 139 additions and 3 deletions

View File

@@ -0,0 +1,105 @@
import assert from "node:assert/strict";
import { after, afterEach, before, test } from "node:test";
import { JSDOM } from "jsdom";
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
url: "http://localhost",
});
before(() => {
Object.assign(globalThis, {
document: dom.window.document,
HTMLElement: dom.window.HTMLElement,
IS_REACT_ACT_ENVIRONMENT: true,
window: dom.window,
});
});
afterEach(async () => {
const { cleanup } = await import("@testing-library/react");
cleanup();
});
after(() => dom.window.close());
async function renderChannelLinks(t) {
const React = await import("react");
const { act, renderHook } = await import("@testing-library/react");
const { ChannelNavigationProvider } = await import(
"@/shared/context/ChannelNavigationContext.tsx"
);
const { useChannelLinks } = await import("./useChannelLinks.ts");
const channels = ["general", "engineering"].map((name) => ({
id: name,
name,
channelType: "stream",
archivedAt: null,
}));
const { result } = renderHook(useChannelLinks, {
wrapper: ({ children }) =>
React.createElement(ChannelNavigationProvider, { channels }, children),
});
t.mock.timers.enable({ apis: ["setTimeout"] });
return {
result,
update(value, cursor = value.length) {
act(() => result.current.updateChannelQuery(value, cursor));
},
tick(ms) {
act(() => t.mock.timers.tick(ms));
},
};
}
for (const replacement of ["Edited, not deleted", "", "Welcome to #general "]) {
test(`invalidating an open channel query is immediate: ${JSON.stringify(replacement)}`, async (t) => {
const { result, update, tick } = await renderChannelLinks(t);
update("Welcome to #general");
tick(120);
assert.equal(result.current.isChannelOpen, true);
update(replacement);
// Do not advance the debounce clock: the very next Enter must be free
// to submit instead of inserting #general at its obsolete offset.
assert.equal(result.current.isChannelOpen, false);
for (const key of ["Enter", "Tab", "ArrowDown"]) {
const event = { key, preventDefault: () => assert.fail("stole the key") };
assert.deepEqual(result.current.handleChannelKeyDown(event), {
handled: false,
});
}
tick(120);
assert.equal(result.current.isChannelOpen, false);
});
}
test("an invalid update cancels pending publication; later valid queries still debounce", async (t) => {
const { result, update, tick } = await renderChannelLinks(t);
update("#general");
tick(60);
update("plain replacement");
tick(120);
assert.equal(result.current.isChannelOpen, false);
update("#eng");
tick(119);
assert.equal(result.current.isChannelOpen, false);
tick(1);
assert.equal(result.current.isChannelOpen, true);
assert.deepEqual(
result.current.channelSuggestions.map((s) => s.name),
["engineering"],
);
let prevented = false;
assert.deepEqual(
result.current.handleChannelKeyDown({
key: "Enter",
preventDefault: () => {
prevented = true;
},
}),
{ handled: true, suggestion: result.current.channelSuggestions[0] },
);
assert.equal(prevented, true);
});

View File

@@ -116,12 +116,27 @@ export function useChannelLinks() {
const updateChannelQuery = React.useCallback(
(value: string, cursorPosition: number) => {
// Store latest values so the debounced callback always uses fresh data
latestValueRef.current = value;
latestCursorRef.current = cursorPosition;
if (debounceTimerRef.current !== null) {
clearTimeout(debounceTimerRef.current);
debounceTimerRef.current = null;
}
// Debounce suggestions, not invalidation: after replacing a #channel
// with ordinary text, Enter must submit rather than accept its stale
// suggestion and overwrite the replacement using the old offset.
if (
!detectPrefixQuery(
"#",
value,
cursorPosition,
knownNamesLowerRef.current,
)
) {
setChannelQuery(null);
return;
}
debounceTimerRef.current = setTimeout(() => {

View File

@@ -41,16 +41,17 @@ async function submitEmptyEdit(
await page.keyboard.press("Enter");
}
test.beforeEach(async ({ page }) => {
async function openGeneralChannel(page: import("@playwright/test").Page) {
await installMockBridge(page);
await page.goto("/");
await page.getByTestId("channel-general").click();
await expect(page.getByTestId("chat-title")).toHaveText("general");
});
}
test("clearing an edit to empty prompts to delete, then deletes on confirm", async ({
page,
}) => {
await openGeneralChannel(page);
const row = page.locator(`[data-message-id="${OWN_MESSAGE_ID}"]`);
await expect(row).toBeVisible({ timeout: 10_000 });
@@ -72,6 +73,7 @@ test("clearing an edit to empty prompts to delete, then deletes on confirm", asy
});
test("cancelling the empty-edit delete keeps the message", async ({ page }) => {
await openGeneralChannel(page);
const row = page.locator(`[data-message-id="${OWN_MESSAGE_ID}"]`);
await expect(row).toBeVisible({ timeout: 10_000 });
@@ -93,6 +95,8 @@ test("cancelling the empty-edit delete keeps the message", async ({ page }) => {
});
test("a non-empty edit still edits and never deletes", async ({ page }) => {
await page.clock.install();
await openGeneralChannel(page);
const row = page.locator(`[data-message-id="${OWN_MESSAGE_ID}"]`);
await expect(row).toBeVisible({ timeout: 10_000 });
@@ -104,9 +108,21 @@ test("a non-empty edit still edits and never deletes", async ({ page }) => {
const editedContent = `Edited, not deleted ${Date.now()}`;
await input.click();
await expect(input).toBeFocused();
// Let edit hydration's #general suggestion open, then hold the debounce
// clock while replacing the entire body and immediately submitting.
await expect(
page
.getByTestId("message-composer")
.getByRole("button", { name: "#general stream", exact: true }),
).toBeVisible();
await page.keyboard.press("ControlOrMeta+A");
await page.clock.pauseAt(
new Date(await page.evaluate(() => Date.now() + 1_000)),
);
await page.keyboard.type(editedContent);
await page.keyboard.press("Enter");
await page.clock.resume();
// No delete confirmation, edit mode exits, the row survives with new text.
await expect(page.getByRole("alertdialog")).toHaveCount(0);