Skip to content

refactor(Chat): internal-authoritative composer input state - #4074

Open
AKnassa wants to merge 5 commits into
meta:mainfrom
AKnassa:ak-2473-composer-state
Open

AKnassa wants to merge 5 commits into
meta:mainfrom
AKnassa:ak-2473-composer-state

Conversation

@AKnassa

@AKnassa AKnassa commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

What this does

Reworks how the chat composer input keeps track of what's typed, following the architecture laid out in #2473: the editable area itself is now the single source of truth, and the value prop becomes a commit/override channel.

Why

The old "skip exactly one echo" bookkeeping had a real hole: if the app committed an earlier value slightly late (easy under async state), the composer treated it as an external change and silently deleted the user's newest keystrokes. The new model fixes that class of bug and gives app code a clean programmatic way to set the draft.

What changed

  • A small ledger of not-yet-acknowledged edits replaces the one-shot echo marker; a late echo is recognized and skipped, a genuine override still applies cleanly.
  • New setValue on the existing handle: writes the text and reports exactly one change — the same change pipeline as typing. It also re-evaluates the trigger menu the way typing does (a menu left open over replaced content closes, instead of aiming a later item pick at a stale trigger position in the new text), and it places the caret at the end only when the input has focus — writing a range into an unfocused editable would yank the document selection (and in Blink, focus itself) away from wherever the user is typing. Call focus() before setValue to continue typing at the end.
  • Submit-clear goes through the same pipeline (identical observable behavior, plus proper token cleanup).
  • Public props unchanged; every pre-existing test passes unmodified. 5 new tests pin the late-echo bug, the setValue contract, setValue's own late-echo protection (mutation-verified: the prior suite still passed with the ledger bypassed in setValue), the unfocused-selection guard, and the stale-menu close.

How to see it

pnpm exec vitest run packages/core/src/Chat — 142/142 pass. Full core suite green (6775/6775).

Fixes #2473 (part of Q3 Chat tracker #3635)

The contentEditable DOM and its Selection become the single source of
truth for ChatComposerInput; the controlled value prop is a
commit/override channel. The one-shot pendingEchoValueRef echo marker
is replaced by a bounded pending-emissions ledger, so a parent's late
commit of an earlier emission no longer wipes newer keystrokes. New
handle method setValue writes the DOM, places the caret, and reports
through the same emitChange pipeline as typing — exactly one onChange,
echo-free. Prop surface unchanged; the pre-existing suite passes
unchanged.

Implements meta#2473 (part of Q3 Chat tracker meta#3635)

Claude-Session: https://claude.ai/code/session_01P9qSoGWZPPp9pUNNRUSwkM
@vercel

vercel Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
astryx Ready Ready Preview Sep 26, 2026 4:31am UTC

Request Review

@github-actions github-actions Bot added community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge labels Jul 19, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 19, 2026
@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR

🧪 Sandbox Preview

View Sandbox for this PR

No new or modified components detected.

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.9KB 1.2KB

Accessibility Audit

Status: 3 accessibility violation(s) found — 3 serious.

ChatComposer - 1 issue(s)
  • 🟠 serious: Ensure the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds
    • Rule: color-contrast · Affects 1/19 stories · Learn more
    • WCAG: 1.4.3 (Level AA)
ChatComposerInput - 1 issue(s)
  • 🟠 serious: Ensure the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds
    • Rule: color-contrast · Affects 1/16 stories · Learn more
    • WCAG: 1.4.3 (Level AA)
ChatToolCalls - 1 issue(s)
  • 🟠 serious: Ensure the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds
    • Rule: color-contrast · Affects 10/11 stories · Learn more
    • WCAG: 1.4.3 (Level AA)

Visual Regression

1 of 420 shot(s) changed. View the report

A change here is a question, not a failure: check whether the after is the
picture you intended. Record that review on the PR. Baseline maintenance is an
explicit dispatch of CI; this report never rewrites the baseline or adds a release gate.

component story theme mode pixels
SideNav Resizable in AppShell probe dark 3,208
SideNav — Resizable in AppShell — probe dark
BeforeAfterDiff
Before visual regression frame After visual regression frame Pixel difference frame

Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

…y caret (meta#2473)

Self-review hardening of the new setValue handle method:

- Re-evaluate the trigger menu after a programmatic replacement, the
  same way typing does. A menu left open across setValue kept a stale
  trigger position into destroyed content, so a later item pick would
  splice the wrong range of the new text.
- Place the caret only when the input owns focus (mirrors the sync
  effect's wasFocused guard). Writing a range into an unfocused
  editable yanks the document selection — and in Blink, focus itself —
  away from wherever the user is typing; call focus() first to
  continue typing at the end.
- Pin setValue's late-echo protection: every prior test passed with
  the pending-emissions ledger bypassed in setValue (the echo assert
  was satisfied vacuously by the DOM-already-equal branch). The new
  test fails against that mutant and passes against the real pipeline.
- Docs: add the missing expandToken to the handleRef lists (en/zh/
  dense) and state the focus qualifier + menu re-evaluation in the
  JSDoc, doc.mjs, and changeset.

@cixzhang cixzhang 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.

Thanks — the late-echo hole is real and this reads it right. One thing before it lands.

Matching the echo anywhere in the ledger swallows a genuine override that equals an un-acknowledged emission. When the parent doesn't commit every onChange — which the new value doc blesses — the ledger holds every keystroke, so value='' after the user emptied the box once reads as an echo and the composer keeps its text: switching threads carries a half-typed message into the new one. main clears it.

Matching only the oldest un-acknowledged entry fixes it and keeps all 142 Chat tests green:

if (echoIndex === 0) {
  ledger.splice(0, 1);
  return;
}

Also refactor and a patch changeset both promise nothing consumer-visible changed, but value means something different now for everyone already passing it.

Does matching only the oldest entry still cover the async commit you had in mind?

If you'd rather talk it through with someone, we're in Discord.

[Reviewed by Robohands]

// own echoes.
const ledger = pendingEmissionsRef.current;
const echoIndex = ledger.indexOf(controlledValue);
if (echoIndex !== -1) {

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.

Matches anywhere in the ledger. Probably wants echoIndex === 0 — only the oldest un-acknowledged emission can be an echo.

@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch

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.

This changes what value means for existing consumers. Might want minor.

@cixzhang

Copy link
Copy Markdown
Contributor

Checking in on composer state: echo matching still needs to consume only the oldest pending emission so a genuine parent override is not swallowed. Would you like to continue, have us carry it, or close this for now?

@astracat-bot astracat-bot 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.

Thanks — the internal-authoritative direction and the late-echo fix are the right shape, and the new tests pin the main typing, selection, and menu behaviour well.

One correction is needed before this lands:

  • The pending-emissions ledger currently matches an incoming value anywhere in the list. When a parent does not commit every onChange, a genuine override that equals a non-oldest pending emission is swallowed as an echo — clearing the draft on a thread switch can leave the previous message visible in the new conversation. Please consume only the oldest pending emission and add a regression test for that colliding-override case.
  • The changeset says patch, but this adds the public setValue handle method and changes what value means for existing consumers. Please bump it to minor.

[Automated review]

Resolved conflicts:
- packages/core/src/Chat/ChatComposerInput.tsx: kept the PR's
  handleRef.setValue alongside upstream's `focus: focusEditable`
  (meta#6419/meta#6398 keep an existing in-editor selection on focus); dropped the
  PR's local placeCaretAtEnd helper in favour of upstream's import from
  ./chatComposerSelection; handleKeyDown deps keep upstream's
  onKeyDownProp (meta#4280) and drop onChange, since submit-clear now reports
  through emitChange. The pending-emissions ledger auto-merged over
  upstream's one-shot pendingEchoValueRef, next to meta#6419's
  emitChangeVersionRef.
- packages/core/src/Chat/ChatComposerInput.test.tsx: took upstream's
  imports (waitFor, act, userEvent); the PR's controlled-value and
  trigger-menu tests auto-merged.
- packages/core/src/Chat/ChatComposerInput.doc.mjs: kept the PR's
  handleRef/value prose in upstream's prettier-wrapped layout, and recast
  the English/dense em dashes as punctuation per meta#4394.

Known fallout, fixed in the follow-up review commit (astracat F2): the
required `setValue` member breaks upstream's five-member handle literal in
useChatPasteAsToken.test.ts (TS2741 under the core typecheck).
…meta#2473)

Addresses the astracat-bot review (and cixzhang's Aug 24 review) of
18ee69f.

F1 - ledger swallowed genuine overrides. The sync effect matched an
incoming `value` anywhere in the pending-emissions ledger, so with a
parent that doesn't commit every onChange, a thread switch to value=''
after the user emptied and retyped a draft was treated as an echo and
the half-typed text stayed. The effect now consumes only the OLDEST
pending emission, and resets the ledger when the incoming value already
equals the DOM. Without the reset, oldest-only matching leaves a stale
head after a coalesced commit (only the latest emission lands) and a
later override back to that head is swallowed.
  red:   'applies a genuine override equal to a non-oldest pending
         emission' -> AssertionError: expected 'half' to be ''
         (at the merged PR code); with oldest-only matching but no reset,
         'a coalesced commit does not leave a stale ledger head that
         swallows a later override' -> expected 'ab' to be 'a'
  green: ChatComposerInput.test.tsx 88/88, including the existing
         in-order late-echo test.
The known residual (an override equal to the oldest un-echoed emission
is still read as an echo) is documented at the effect.

F2 - required setValue broke the exported handle type.
ChatComposerInputHandle is the input type of useChatPasteAsToken and
useChatDictation, so consumers build these objects; a new required
member is a type break shipped as a patch. setValue is now optional on
the type (the handle ChatComposerInput returns always provides it), a
compile-only test pins that a handle with only the five original
members type-checks, and the changeset is [feat] + patch with an honest
line about the optional member instead of "Prop surface unchanged".
useChatPasteAsToken.test.ts is left unedited.
  red:   core tsc -> TS2741 "Property 'setValue' is missing" at
         ChatComposerInput.test.tsx and useChatPasteAsToken.test.ts:28
  green: core tsc exit 0; check-changesets valid.
)

Follow-up to d3db49a. F1 narrowed echo recognition to the oldest
pending emission, but the public prop docs still promised the old,
absolute behavior ("echoes of onChange are ignored", and onChange as
purely observational even alongside `value`).

F1 (docs) - value/onChange now describe what the sync effect does:
- `value` JSDoc and the en/zh/dense doc.mjs `value` entries: in-order
  echoes of onChange, even late ones, are skipped; any other value
  that differs from the editor content, including a coalesced or
  debounced commit, is applied as an override. A parent that passes
  `value` without committing every onChange may have an override
  equal to its oldest uncommitted emission read as an echo; force it
  with `key` or `handleRef.setValue`.
- `onChange` JSDoc drops "the parent does not need to commit the
  value back"; it and the doc.mjs onChange entries now say to commit
  each emission when passing `value`, pointing at `value`.
- File header, setValue JSDoc and the changeset say "in-order echo".
  The changeset gains one sentence stating the same limits.
- en/dense prose has no em dashes (meta#4394).

Two tests pin the documented behavior:
- 'applies a coalesced commit that differs from the editor content
  as an override' (value='' -> 'a','ab','abc' -> value='ab' => 'ab').
  With the pre-F1 indexOf matching restored it fails:
  expected 'abc' to be 'ab'.
- 'lets setValue force an override equal to the oldest uncommitted
  emission': value='' is skipped as the documented residual, then
  handleRef.setValue('') clears the box.
Docs-only change otherwise; no runtime code touched. Both tests pass
at d3db49a as expected for a docs finding.

F2 unchanged (setValue optional, [feat] + patch). F3 still waits on
cixzhang (breaking or not).

Checks: 7 Chat suites 154/154; core tsc exit 0; eslint and prettier
clean; check-changesets, check-sync, check-knowledge pass;
docPropLiterals + doc-loads 144/144.
@AKnassa

AKnassa commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

@cixzhang sorry for the slow reply. I'd like to keep going with this. I've pushed 1b49a0e, with main merged in. That merge meant re-applying the ledger and setValue on top of the upstream changes to ChatComposerInput, keeping the shared placeCaretAtEnd import.

  • Echo matching (d3db49a): the sync effect now only consumes the oldest pending emission, as you suggested. I added one thing on top. When an incoming value already equals the editor content, the ledger is cleared. Without that, a coalesced commit (only the latest emission lands) leaves a stale oldest entry, and a later override equal to that entry gets swallowed. Both cases have regression tests.
  • setValue on the handle (d3db49a): setValue is now optional on ChatComposerInputHandle. The handle ChatComposerInput returns always has it. Consumers build this type for useChatPasteAsToken and useChatDictation, so a required member would have broken them at the type level. The changeset is [feat] + patch because check:changesets only accepts minor with [breaking]. It no longer says "Prop surface unchanged".
  • Docs (1b49a0e): the value/onChange docs and the changeset now describe the actual behavior. There are two new tests for it.

On your question: yes, it covers the case I had in mind, where every emission is committed late but in order. Coalesced or debounced commits that differ from the editor content are applied as overrides. One known gap: if a parent doesn't commit every onChange, an override equal to its oldest uncommitted emission is still read as an echo. That's documented, and key or handleRef.setValue forces the override.

Open: do you consider the value change breaking? If so, I'll switch the changeset to [breaking] + minor. I still need to retitle the PR to feat(Chat).

@astracat-bot astracat-bot 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.

Approval is waiting on an engineering-owner decision: the current component:ChatComposerInput record does not list setValue among its imperative-editing operations, and skipping an explicit value equal to the oldest uncommitted onChange emission contradicts its rule that an external value is reflected. An engineering owner needs to decide whether to adopt both, and if so whether the skipped override is a [breaking] minor change under AST-017 FR1. They record the decision by commenting /approve-spec <full head SHA> on this pull request (the author may do so if they are an engineering owner), and the component record is then updated to match. Two fixes are needed whatever the decision:

  • The ledger also records an emission equal to the value the parent already committed, such as a leading space in an empty composer (which emits '') or setValue with the current text. The next late in-order commit then still deletes newer typing. Compare each emission with the last ledger entry or, when the ledger is empty, the last synced value, and add a regression test.
  • The title, description and changeset promise more than the code delivers. Retitle to feat(Chat), qualify "a genuine override still applies cleanly" and "identical observable behavior", and keep the late-commit sentence in the changeset only once the ledger is fixed.

[Automated review]

@cixzhang
cixzhang dismissed their stale review November 18, 2026 21:22

(Posted by Cindy's agent.) Dismissed as stale on the owner's decision: this review is on an outdated head. Please re-review the current head if concerns remain.

This branch was successfully deployed

1 active deployment
Preview — 1b49a0e6 Deployed Sep 26, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot. community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(Chat): XDSChatComposerInput — internal-authoritative state model (Lexical-inspired)

2 participants