Skip to content

refactor(website): split chatSlice into composed store/chat owners - #14665

Merged
iamwhatever merged 1 commit into
mainfrom
refactor/f04-chat-redux-state
Sep 29, 2026
Merged

iamwhatever merged 1 commit into
mainfrom
refactor/f04-chat-redux-state

Conversation

@bolichen97

@bolichen97 bolichen97 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Contributors can change one part of the dashboard's chat state without reading or merging against the whole 7,572-line chatSlice.ts, while the dashboard behaves exactly as before.

website/src/store/chatSlice.ts held every chat reducer, thunk, selector, wire guard and transcript calculation in one file. Its extraReducers builder alone was 1,042 lines. It is one of the most-edited frontend files, so an unrelated fix to the side chat, sub-agent cards or older-history paging lands in the same file, conflicts with every other open chat change, and has to be reviewed against thousands of lines it does not touch.

Why it matters

Every chat-state fix pays for the file's size: longer reviews, frequent rebase conflicts between unrelated PRs, and a real chance of editing the wrong one of several near-identical slot-detail reducers. The WebSocket router, composer, sidebar and ChatPage refactors that follow also build on this store, and they need clear owners to depend on.

Not a goal

  • Changing any behaviour: the state shape, initial state, action type strings, action creators, thunk names and prefixes, selectors, constants, types and storage keys stay the same.
  • Changing any consumer. Every import of store/chatSlice keeps working unchanged, and no consumer file is edited.
  • Splitting the chat slice into several slices, or adding a shared state service.
  • Touching the API client, the WebSocket hook, pages, components, i18n catalogs or baselines, or any backend code.
  • Rewording docs outside the five owned specs. Five other docs only get a file or symbol pointer re-pointed where the move made it false.
  • Fixing pre-existing chat bugs found along the way.

What changed (motivation → approach → change)

Owner under website/src/store/chat/ Responsibility
wire.ts trust boundary: prototype-key guards, slot-detail read and normalization, tool-output clamp
transcript.ts, paging.ts, thinking.ts pure transcript identity, dedup, echo reconciliation, chunk floors; page sizes, coverage and the older-page abort handle; client-only reasoning rows
state.ts ChatState, initial state, the mc-activity-open:<slot> key family
runState.ts, slotCache.ts, messages.ts, queue.ts, composerCards.ts, activity.ts reducer families for run state, per-slot page cache, transcript edits, queued rows, composer cards, activity panel and tool log
subagents.ts, automations.ts, side.ts, workflows.ts, mcpApps.ts reducer families and selectors for sub-agent cards, automations, Side Chat, workflow runs, MCP App payloads
slotSwitch.ts, slotRefresh.ts, lifecycle.ts, slotResidue.ts switchSlot, refreshSlot / warmSlotCache, create / fork / resume / history thunks with their extra reducers, and slot teardown
selectors.ts slot-scoped reads, the composer busy rule, Continue / Resume predicates

The file was too big to change safely, so each responsibility now has one owner and chatSlice.ts (849 lines) is the single createSlice call that composes them. It spreads the reducer families into reducers, calls each owner's add…Cases(builder) in extraReducers, and re-exports every public name. Consumers therefore see the same module, the same action types and the same objects.

Three constructs stay in chatSlice.ts because a read-only check reads them from that file. The live chat_message frame reducer applies QUESTION_RETIRING_ROLES and the chunk-gap marker, which a backend test and the i18n ledger read. deleteSlot holds the one dispatch(switchSlot( site the call-site oracle counts there. loadOlderMessages carries the slot capture chatPins.test.tsx reads. requestStop stays too, because it dispatches this slice's own actions. The switch-notice action became a createAction with the same chat/setSwitchSlotGone type so slotSwitch.ts does not import the facade. The MCP App key separator became a named constant, so the i18n ledger for store/chatSlice.ts goes from 4 to 1 and new files add none.

The session, history, mcp-apps, side and subagent specs now name these owners. side.md also fixes one sentence that was already false about the unchanged sseSideQueue reducer: a redelivered push id is ignored, never rewritten, and front head-inserts. history.md adds a chat-store owner table beside the virtualizer table. The #13683 availableAgents section and every backend section are unchanged.

Four unowned docs had a pointer the move made false, and each is re-pointed with no other wording change: learn-cron-dashboard.md (seedContextUsage), followup-suggestions-trust-model.md (follow-up reducers), and two RFCs whose stale chatSlice.ts:NNN line cites become symbol cites.

Backwards compatibility

Compatible: chatSlice.ts keeps its full export surface, action types, thunk prefixes, initial state and default reducer. chatSlice.publicSurface.test.ts pins all of them by name, and the 37 existing chatSlice tests, the 12 direct reducer/selector oracles and every other consumer pass unmodified.

Tests

  • website/src/store/chatSlice.publicSurface.test.ts: the exact runtime export list; chat/<name> types for every action creator; every thunk's prefix and lifecycle types; constant values; the initial state in key order; reference identity for an unrelated action; the persisted mc-activity-open:<slot> seed and write; shared empty references; and zero recomputations of the six memoized aggregates across an unrelated change (red when an input is widened to state.chat).
  • website/src/store/chatSlice.unsafeKeys.test.ts: __proto__, constructor and prototype sent through every keyed reducer family never reach Object.prototype, and never leave an own entry or a swapped prototype anywhere in the state tree. Sub-agent ids are sent on both the active and a background slot. Removing the id guard in sseSubagentPending was checked to turn it red.
  • website/src/store/chatSlice.ownership.test.ts: no owner imports the facade; the owners' runtime imports have no cycle; nothing in src, integration or capture outside src/store imports an owner (so vi.mock('../store/chatSlice') still replaces everything); reducer families own disjoint action names that add up to the exported action creators; the switch-notice pair slotSwitch.ts wires outside that map still sets and clears switchSlotGone; every re-export is the owner's own binding. A planted cycle and facade import were checked to turn it red.
  • The TypeScript type of all 166 chatSlice exports was compared between main and this head with the compiler API: identical, except that sseChatMessage's payload now prints as the structurally identical ChatFrame alias.
  • Unchanged and green: all 442 store and chat test files, including every file that imports chatSlice (7,160 tests), including switchSlotCallsiteClassification.test.ts, chatPins.test.tsx, ChatSliceCoverage*.test.tsx and test/test_slot_needs_input_status.py.

Manual verification

N/A — unit coverage sufficient: this is a pure Redux module with no rendered output. The related sets ran locally: 352 frontend test files (10,706 tests), plus the backend files that cite chatSlice or the changed specs (784 tests). Every new module is at least 94% line-covered. local-gate.py --base e4dd6161b --dry-run selects 864 backend and 346 frontend files; the backend set is CI's to run in full.

Screenshots / video

Why no screenshot: the diff moves Redux state code between modules behind an unchanged facade and changes no component, style or string, so nothing renders differently.

Related Issues

no linked issue: structural refactor of the chat store, part of the frontend decomposition campaign.

Code comments outside this claim still say a symbol lives in chatSlice.ts. The names resolve through the facade, and the owned specs record the true owners. They are left for the owning lanes:

Comment Symbol Now defined in
src/kiro_crew/dashboard/state.py:1082 the inject-kind table website/src/store/chat/selectors.ts
test/test_dashboard_chat.py:2743, :2867 switchSlot.fulfilled replace, SKIP_ROLES chat/slotSwitch.ts, chat/wire.ts
website/src/utils/pinnedPrompt.ts:93 isTurnBoundaryUser, the lastUserIdx walk chat/thinking.ts, chat/selectors.ts
website/src/pages/chat/ChatPageMessageContent.tsx:162, website/src/test/ChatPage.dockSearchClose.test.tsx:362 isRedeliveredMessage chat/transcript.ts
website/src/app-sdk/protocol/options.ts:77, website/src/test/deriveFollowUpOptions.test.ts:277 mergePreservedClientTs chat/transcript.ts
website/src/utils/structuralEqual.ts:8 sameMessage chat/transcript.ts
website/src/test/sessionSummaryTab.test.tsx:76, website/capture/chatpane-loader.tsx:26 SlotState chat/state.ts
website/scripts/capture-autocompact-slider.mjs:69, capture-panel-section-header.mjs:161, capture-pierre-files-tab.mjs:428 fetchSlotDetail, activity-open persistence chat/wire.ts, chat/state.ts

Follow-up after merge: the docs/feature-map/README.md "Default memory mode" row still lists store/chatSlice.ts. That name still resolves through the createSlot export, but the memory-mode default now lives in store/chat/lifecycle.ts. The re-point is left to a docs-sync PR because this diff has to stay under the review lanes' 1 MB diff cap, and that row's long lines cost about 13 KB of diff.

Integration follow-up: .github/docs-lint-baseline.txt line 425 (line-ref … chatSlice.ts:668-671) no longer fires, because that RFC cite is now a symbol cite. docs-lint reports it as an advisory prune; this PR leaves the baseline alone.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@bolichen97
bolichen97 requested a review from a team September 28, 2026 08:40
@bolichen97
bolichen97 requested a review from a team as a code owner September 28, 2026 08:40
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Sep 28, 2026
@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — ✅ PASS

Design-level review of f9bdba8fb16426ef92ef2a2056b914823eb7cc3b — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: PASS

Nothing to check.

[DESIGN-REVIEWED] f9bdba8

Description read

[DESCRIPTION-READ] 4df9866aa0205815c02bcf514acbd7610a042ff3cd3c4449d72878fda3ea1edc

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Fable 5) — ✅ PASS

UX-level review of f9bdba8fb16426ef92ef2a2056b914823eb7cc3b — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

UX-Verdict: PASS

Nothing to check.

[UX-REVIEWED] f9bdba8

Description read

[DESCRIPTION-READ] 62cc109bdc8913537b3c36e1c69b33b8221fae440821fc9e099fcd1f976b98d7

That sha256 names everything this verdict read: the PR description, plus the 3 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5) — ✅ PASS

Premise-level review of f9bdba8fb16426ef92ef2a2056b914823eb7cc3b — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: PASS

Behaviour-identity rests wholly on the new pin tests and CI's full suite — a 7,500-line move is unreviewable by eye, so confirm the 442 chat/store test files ran green on this head.

What this change ships

Inventory (9 items) — 9 justified

Intent: contributors can edit one part of the dashboard's chat state without merging against the 7,572-line chatSlice.ts, with identical runtime behaviour — a structural ADDITION (refactor), harm measured by the file itself.

  1. chatSlice.ts contents moved into 21 owner modules under store/chat/, facade re-exports every name — justified
  2. New chatSlice.publicSurface.test.ts pins exports, action types, initial state — justified
  3. New chatSlice.unsafeKeys.test.ts pins prototype-key guards across keyed reducer families — justified
  4. New chatSlice.ownership.test.ts pins one-way facade dependency and disjoint action ownership — justified
  5. Switch-notice action rebuilt as createAction keeping type chat/setSwitchSlotGone — justified
  6. MCP App key separator became a named constant — justified
  7. side.md redelivery sentence corrected — justified (verified on base: sseSideQueue already had if (at >= 0) return and front head-insert, so the old "updates in place" pin was false)
  8. Five owning specs name the new owners — justified (AGENTS.md same-commit rule)
  9. Four unowned docs' stale chatSlice.ts pointers re-pointed — justified

No undeclared riders found: no consumer files edited, no new persisted keys (mc-activity-open: pre-exists), ChatFrame stays unexported, module-level queue-edit state is a pure move. Not product shape; no RFC required.

[FIRST-PRINCIPLES-REVIEWED] f9bdba8

Description read

[DESCRIPTION-READ] 82d5846b26f40cf0e107c136c1a36d1fbd631d9d6524e00587111a91a7817983

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings

GPT 5.6 completed its review of f9bdba8fb16426ef92ef2a2056b914823eb7cc3b and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] f9bdba8

False positive or not applicable? A repository writer can comment:
/ai-review override gpt f9bdba8fb16426ef92ef2a2056b914823eb7cc3b: <one-sentence reason>

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 28, 2026
@bolichen97
bolichen97 enabled auto-merge (squash) September 28, 2026 15:40
@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Sep 28, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author

/ai-review override fable f4cc64a: Opus discovery exhausted its 180-turn budget twice at this head on the ~922 KB behaviour-preserving move diff with no verdict and no finding; GPT, Design, First Principles, UX, Security Scope and CodeQL all passed on this head.

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded

@bolichen97 marked the fable AI finding as false positive, not applicable, or explicitly accepted for f4cc64aca171353a3726ecc9d02c3a64c773e2bd.

Opus discovery exhausted its 180-turn budget twice at this head on the ~922 KB behaviour-preserving move diff with no verdict and no finding; GPT, Design, First Principles, UX, Security Scope and CodeQL all passed on this head.

This decision applies only to this commit. A new push requires a new judgment.

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5 Review — ✅ no blocking findings

Reviewed f9bdba8fb16426ef92ef2a2056b914823eb7cc3b — this comment is updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] f9bdba8

Verdict parsed from the review's SHA-scoped output markers for commit f9bdba8fb16426ef92ef2a2056b914823eb7cc3b.

False positive or not applicable? A repository writer can comment:
/ai-review override fable f9bdba8fb16426ef92ef2a2056b914823eb7cc3b: <one-sentence reason>

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: action required A blocking check or review needs attention labels Sep 28, 2026
@bolichen97
bolichen97 force-pushed the refactor/f04-chat-redux-state branch from f4cc64a to a413c27 Compare September 29, 2026 01:19
@bolichen97

Copy link
Copy Markdown
Contributor Author

Rebased: main moved website/src/store/chatSlice.ts in #14699 (e8959f4, "keep an unconfirmed send pending instead of offering Resume"), which conflicted with this split. The rest of the rebase merged cleanly (f4cc64aca -> a413c275a, onto main 7610731). #14699's change is ported into the owners that now hold that logic, with no other change.

Where each #14699 hunk landed

#14699 hunk in chatSlice.ts (main) Now in
@@ -192 reconcileOptimisticEcho: echo clears meta.deliveryUnconfirmed website/src/store/chat/transcript.ts:167-169
@@ -4470 selectTurnInterrupted: trailing meta.optimistic user row is not interrupted website/src/store/chat/selectors.ts:260-273
@@ -4487 new selectTrailingSendUnconfirmed (+ its doc block), right after selectTurnInterrupted website/src/store/chat/selectors.ts:291-331
@@ -4872 confirmOptimisticSend: receipt clears meta.deliveryUnconfirmed website/src/store/chat/messages.ts:176-178
@@ -4887 new reducer markSendUnconfirmed (+ doc), right after confirmOptimisticSend website/src/store/chat/messages.ts:194-221 (in messageReducers, composed into the one createSlice, so the action type is chat/markSendUnconfirmed)
@@ -7549 export list gains markSendUnconfirmed website/src/store/chatSlice.ts:812; selectTrailingSendUnconfirmed re-exported at :842

Proof it is the same change

  • Line check: 89 of the 90 non-blank lines fix(chat): keep an unconfirmed send pending instead of offering Resume #14699 added to chatSlice.ts appear verbatim (whitespace-trimmed) in the new tree. The one exception is the reducer signature, which carries state: ChatState like every reducer declared outside createSlice: markSendUnconfirmed(state: ChatState, action: PayloadAction<{ slot: string; sendId: string }>).
  • Types: the TypeScript compiler API compared all 166 exports of main's chatSlice.ts with this head's facade and found them identical. markSendUnconfirmed is ActionCreatorWithPayload<{ slot: string; sendId: string }, "chat/markSendUnconfirmed"> on both sides. The only textual difference is the one that existed before this rebase: sseChatMessage's payload prints as the structurally identical ChatFrame alias.
  • fix(chat): keep an unconfirmed send pending instead of offering Resume #14699's own tests pass unmodified (git diff --quiet origin/main on each): src/test/ChatPage.sendResponseLate.test.tsx, src/test/UserMessage.test.tsx, src/test/chatSlice.continuable.test.ts, src/test/chatSlice.test.ts.
  • The only test edits in this PR's own files add the two new names to chatSlice.publicSurface.test.ts (export list) and chatSlice.ownership.test.ts (selectors re-export table).

Re-gated at a413c275a: tsc, eslint src --max-warnings 0, jscpd (0 clones), 257 chatSlice-importing test files (5,103 tests), the 350-file frontend related set (10,671 tests), i18n:check, build plus the bundle-size (810 chunks) and chunk-cycle gates, docs-lint, feature-map gate, test/test_slot_needs_input_status.py. The other main commits touching this PR's specs (#11717 session.md, #14588 history.md, #14661 and #14722 subagent.md, feature-map rows) auto-merged. They are backend or unrelated text, and none of them cites a chatSlice owner.

range-diff excerpt, code files only (git range-diff 35fac2012..f4cc64aca 761073102..a413c275a)
    @@ website/src/store/chat/messages.ts (new)
     +        if (m.role !== 'user' || m.meta?.sendId !== sendId) continue
     +        const meta = { ...(m.meta || {}) }
     +        delete meta.optimistic
    ++        // A receipt that arrives after all is the confirmation the deadline
    ++        // mark said was missing.
    ++        delete meta.deliveryUnconfirmed
     +        // Stamp the server-minted row id the receipt carried back. The bubble
     +        // was appended client-side with only a `sendId` (no server identity),
     +        // so either the user echo or this receipt can supply its identity.
    @@ website/src/store/chat/messages.ts (new)
     +    }
     +    if (!confirm(state.messages)) confirm(state.slotMessages[safeKey(slot)])
     +  },
    ++  /** Record that a send's own receipt never came: the transport deadline
    ++   *  fired (`response-late`) and no correlated echo has confirmed the row, so
    ++   *  the bubble stays `optimistic` and only a late echo can still clear it.
    ++   *  Stamps `meta.deliveryUnconfirmed` on that bubble; the row's pending line
    ++   *  is drawn from THIS mark, never from `optimistic` alone, because the flag
    ++   *  also survives a `refused` or `transport-error` send (whose error row and
    ++   *  restored composer already say what happened) and a `queued` receipt
    ++   *  (whose card owns the text), so a line keyed on it would claim a wait on
    ++   *  rows nobody is waiting for. Client-minted like `optimistic`, never sent,
    ++   *  and cleared by the same two doors (`confirmOptimisticSend`, the echo
    ++   *  reconcile). Scans BOTH arrays as `confirmOptimisticSend` does; a row an
    ++   *  echo already confirmed is left alone. */
    ++  markSendUnconfirmed(state: ChatState, action: PayloadAction<{ slot: string; sendId: string }>) {
    ++    const { slot, sendId } = action.payload
    ++    if (isUnsafeKey(slot)) return
    ++    const mark = (msgs: ChatMessage[] | undefined): boolean => {
    ++      if (!msgs) return false
    ++      const floor = Math.max(0, msgs.length - RECONCILE_WINDOW)
    ++      for (let i = msgs.length - 1; i >= floor; i--) {
    ++        const m = msgs[i]
    ++        if (m.role !== 'user' || m.meta?.sendId !== sendId) continue
    ++        if (m.meta?.optimistic) m.meta = { ...m.meta, deliveryUnconfirmed: true }
    ++        return true
    ++      }
    ++      return false
    ++    }
    ++    if (!mark(state.messages)) mark(state.slotMessages[safeKey(slot)])
    ++  },
     +  /** Resolve an optimistic steer bubble against the steer POST's own receipt.
     +   *
     +   *  `meta.steer` draws the "Steered into the running turn" badge, so it is an
    @@ website/src/store/chat/selectors.ts (new)
     +        continue
     +      }
     +      if (m.role !== 'user') return sawTrailingError
    ++      // A user row still carrying `meta.optimistic` is the composer's own
    ++      // bubble, minted at send time and cleared only by the send's receipt
    ++      // (`confirmOptimisticSend`) or a correlated echo. Until then nothing
    ++      // proves the server ever received the text -- a POST that hit the
    ++      // transport deadline before leaving the browser draws exactly this row --
    ++      // so no turn was opened and none was interrupted. Reading it as one
    ++      // offers a Resume whose bare continue runs against a transcript that
    ++      // never held the message, and the agent answers the request before it.
    ++      // An error row behind it is the send's own failure, not a reply that
    ++      // died, so it does not revive the verdict. This branch is invisible to
    ++      // the `is_turn_interrupted` mirror by construction: the flag is minted
    ++      // client-side and never sent, so no transcript the server can produce
    ++      // carries a row for it to read, and the two cannot disagree.
    ++      if (m.meta?.optimistic) return false
     +      // A `/compact` answered by its compaction notice is a FINISHED turn --
     +      // unless an error row trails the notice, the same evidence the
     +      // plain-assistant branch honors. First-whitespace-token match using
    @@ website/src/store/chat/selectors.ts (new)
     +  // tool rows here. A trailing error row is still the evidence the assistant
     +  // branch honors, so it decides the same way.
     +  return sawTrailingError
    ++}
    ++
    ++/**
    ++ * True while the newest send in the active transcript is a plain-send bubble
    ++ * whose receipt never came (`meta.deliveryUnconfirmed`, stamped by
    ++ * `markSendUnconfirmed` on `response-late`).
    ++ *
    ++ * Gates the footer's plain running indicator. The send did start a local turn,
    ++ * so `slotRunning` is true and "Thinking…" would draw directly under a bubble
    ++ * that says "Delivery pending…" over a notice that says the delivery is not
    ++ * confirmed -- the UI claiming the agent is working on a message nothing proves
    ++ * it received. Keyed on the deadline MARK, never on `optimistic` alone: the
    ++ * flag is also true for the ordinary in-flight second before a receipt, and
    ++ * hiding the indicator there would make every send flicker.
    ++ *
    ++ * Reads the same tail `selectTurnInterrupted` reads, with the same skips and
    ++ * the same terminators, so the two never disagree about which row is newest:
    ++ * the WARN notice under the bubble and the roles in `CONTINUE_SCAN_SKIP` are
    ++ * looked through; a Stop card, a dispatching inject row or a nudge row ends the
    ++ * walk (each means the agent is, or was, visibly at work on something else, and
    ++ * the indicator is theirs); the first user or assistant row decides. The
    ++ * error/compaction bookkeeping that selector carries has no bearing on a
    ++ * boolean about the bubble, so this walk does not repeat it.
    ++ *
    ++ * Client-local by construction, like the mark: nothing the server sends can
    ++ * carry it, and both confirmation doors (`confirmOptimisticSend`, the echo
    ++ * reconcile) clear it, so the indicator returns on its own.
    ++ */
    ++export const selectTrailingSendUnconfirmed = (state: RootState): boolean => {
    ++  const msgs = state.chat.messages
    ++  for (let i = msgs.length - 1; i >= 0; i--) {
    ++    const m = msgs[i]
    ++    if (isStopEvent(m)) return false
    ++    if (m.role === 'inject' && m.content && TURN_INJECT_KINDS.has((m.meta as { injectKind?: unknown } | undefined)?.injectKind)) return false
    ++    if (m.role === 'nudge' && m.content) return false
    ++    if (CONTINUE_SCAN_SKIP.has(m.role)) continue
    ++    if ((m.role === 'user' || m.role === 'assistant') && m.content) {
    ++      if (m.role === 'assistant' && isSystemNoticeKind((m.meta as { kind?: string } | undefined)?.kind)) continue
    ++      return m.role === 'user' && !!m.meta?.deliveryUnconfirmed
    ++    }
    ++  }
    ++  return false
     +}
     
      ## website/src/store/chat/side.ts (new) ##
    @@ website/src/store/chat/transcript.ts (new)
     +      if (ts) m.ts = ts
     +      m.meta = { ...(m.meta || {}), ...meta }
     +      delete (m.meta as Record<string, unknown>).optimistic
    ++      // The echo is the delivery proof a late receipt never gave; the deadline
    ++      // mark `markSendUnconfirmed` stamped falls with the flag.
    ++      delete (m.meta as Record<string, unknown>).deliveryUnconfirmed
     +      if (!meta.steer) delete (m.meta as Record<string, unknown>).steer
     +      return true
     +    }
    @@ website/src/store/chatSlice.ownership.test.ts (new)
     +  ['side', side, ['queueEditBroadcastAt']],
     +  ['selectors', selectors, [
     +    'selectActiveSlotProject', 'selectComposerBusy', 'selectContinuable', 'selectSendConfirmed', 'selectSlotMessages',
    -+    'selectSlotPendingApproval', 'selectSlotRunEpoch', 'selectSlotStreamState', 'selectSlotToolLog', 'selectTurnInterrupted',
    ++    'selectSlotPendingApproval', 'selectSlotRunEpoch', 'selectSlotStreamState', 'selectSlotToolLog', 'selectTrailingSendUnconfirmed',
    ++    'selectTurnInterrupted',
     +  ]],
     +  ['slotSwitch', slotSwitch, ['clearSwitchSlotGone', 'switchSlot', 'switchSlotNoticeCopy']],
     +  ['slotRefresh', slotRefresh, ['refreshSlot', 'warmSlotCache']],
    @@ website/src/store/chatSlice.publicSurface.test.ts (new)
     +  'clearSlotReveal', 'clearSlotState', 'clearSubagentsForSnapshot', 'clearSwitchSlotGone',
     +  'clearTerminalSubagents', 'clearUndeletableHistory', 'clearUnresumableResume',
     +  'clearWorkflowRun', 'confirmOptimisticSend', 'dismissFollowupItem', 'editQueuedMessage',
    -+  'endLocalTurn', 'finalizeAssistant', 'hydrateSlotMessages', 'markSubagentApproving',
    ++  'endLocalTurn', 'finalizeAssistant', 'hydrateSlotMessages', 'markSendUnconfirmed', 'markSubagentApproving',
     +  'openActivityPanel', 'openActivityToTab', 'openActivityToTool', 'reconcileWorkflowRuns',
     +  'removeAutomation', 'removeByApprovalId', 'removeQueuedMessage', 'removeThinking',
     +  'reorderQueuedMessages', 'replaceMessages', 'requestFolderReveal', 'requestSlotReveal',
    @@ website/src/store/chatSlice.publicSurface.test.ts (new)
     +  'selectSidebarSubagentCounts', 'selectSidebarWorkflowActive', 'selectSidebarWorkflowActiveKeys',
     +  'selectSlotMessages', 'selectSlotPendingApproval', 'selectSlotPendingSpawnApprovals',
     +  'selectSlotRunEpoch', 'selectSlotStreamState', 'selectSlotSubagents',
    -+  'selectSlotSubagentsActive', 'selectSlotToolLog', 'selectSubagentActivityCount',
    ++  'selectSlotSubagentsActive', 'selectSlotToolLog', 'selectSubagentActivityCount', 'selectTrailingSendUnconfirmed',
     +  'selectTurnInterrupted', 'shouldResolveAskOnSend', 'slotCoverageShortfall',
     +  'slotSwitchFetchLimit', 'snapshotChunkGen', 'snapshotChunkSeq', 'switchSlotNoticeCopy',
     +  'transcriptTsMs',
    @@ website/src/store/chatSlice.ts
     -      if (ts) m.ts = ts
     -      m.meta = { ...(m.meta || {}), ...meta }
     -      delete (m.meta as Record<string, unknown>).optimistic
    +-      // The echo is the delivery proof a late receipt never gave; the deadline
    +-      // mark `markSendUnconfirmed` stamped falls with the flag.
    +-      delete (m.meta as Record<string, unknown>).deliveryUnconfirmed
     -      if (!meta.steer) delete (m.meta as Record<string, unknown>).steer
     -      return true
     -    }
    @@ website/src/store/chatSlice.ts: export const requestStop = createAsyncThunk<Stop
     -        continue
     -      }
     -      if (m.role !== 'user') return sawTrailingError
    +-      // A user row still carrying `meta.optimistic` is the composer's own
    +-      // bubble, minted at send time and cleared only by the send's receipt
    +-      // (`confirmOptimisticSend`) or a correlated echo. Until then nothing
    +-      // proves the server ever received the text -- a POST that hit the
    +-      // transport deadline before leaving the browser draws exactly this row --
    +-      // so no turn was opened and none was interrupted. Reading it as one
    +-      // offers a Resume whose bare continue runs against a transcript that
    +-      // never held the message, and the agent answers the request before it.
    +-      // An error row behind it is the send's own failure, not a reply that
    +-      // died, so it does not revive the verdict. This branch is invisible to
    +-      // the `is_turn_interrupted` mirror by construction: the flag is minted
    +-      // client-side and never sent, so no transcript the server can produce
    +-      // carries a row for it to read, and the two cannot disagree.
    +-      if (m.meta?.optimistic) return false
     -      // A `/compact` answered by its compaction notice is a FINISHED turn --
     -      // unless an error row trails the notice, the same evidence the
     -      // plain-assistant branch honors. First-whitespace-token match using
    @@ website/src/store/chatSlice.ts: export const requestStop = createAsyncThunk<Stop
     -  return sawTrailingError
     -}
     -
    +-/**
    +- * True while the newest send in the active transcript is a plain-send bubble
    +- * whose receipt never came (`meta.deliveryUnconfirmed`, stamped by
    +- * `markSendUnconfirmed` on `response-late`).
    +- *
    +- * Gates the footer's plain running indicator. The send did start a local turn,
    +- * so `slotRunning` is true and "Thinking…" would draw directly under a bubble
    +- * that says "Delivery pending…" over a notice that says the delivery is not
    +- * confirmed -- the UI claiming the agent is working on a message nothing proves
    +- * it received. Keyed on the deadline MARK, never on `optimistic` alone: the
    +- * flag is also true for the ordinary in-flight second before a receipt, and
    +- * hiding the indicator there would make every send flicker.
    +- *
    +- * Reads the same tail `selectTurnInterrupted` reads, with the same skips and
    +- * the same terminators, so the two never disagree about which row is newest:
    +- * the WARN notice under the bubble and the roles in `CONTINUE_SCAN_SKIP` are
    +- * looked through; a Stop card, a dispatching inject row or a nudge row ends the
    +- * walk (each means the agent is, or was, visibly at work on something else, and
    +- * the indicator is theirs); the first user or assistant row decides. The
    +- * error/compaction bookkeeping that selector carries has no bearing on a
    +- * boolean about the bubble, so this walk does not repeat it.
    +- *
    +- * Client-local by construction, like the mark: nothing the server sends can
    +- * carry it, and both confirmation doors (`confirmOptimisticSend`, the echo
    +- * reconcile) clear it, so the indicator returns on its own.
    +- */
    +-export const selectTrailingSendUnconfirmed = (state: RootState): boolean => {
    +-  const msgs = state.chat.messages
    +-  for (let i = msgs.length - 1; i >= 0; i--) {
    +-    const m = msgs[i]
    +-    if (isStopEvent(m)) return false
    +-    if (m.role === 'inject' && m.content && TURN_INJECT_KINDS.has((m.meta as { injectKind?: unknown } | undefined)?.injectKind)) return false
    +-    if (m.role === 'nudge' && m.content) return false
    +-    if (CONTINUE_SCAN_SKIP.has(m.role)) continue
    +-    if ((m.role === 'user' || m.role === 'assistant') && m.content) {
    +-      if (m.role === 'assistant' && isSystemNoticeKind((m.meta as { kind?: string } | undefined)?.kind)) continue
    +-      return m.role === 'user' && !!m.meta?.deliveryUnconfirmed
    +-    }
    +-  }
    +-  return false
    +-}
    +-
     -/** Monotonic tick, so an observation can be ordered against a request already in flight.
     - *  A bare boolean cannot: it could have been set by an earlier, unrelated edit. */
     -let queueEditBroadcastSeq = 0
    @@ website/src/store/chatSlice.ts: export const requestStop = createAsyncThunk<Stop
     -          if (m.role !== 'user' || m.meta?.sendId !== sendId) continue
     -          const meta = { ...(m.meta || {}) }
     -          delete meta.optimistic
    +-          // A receipt that arrives after all is the confirmation the deadline
    +-          // mark said was missing.
    +-          delete meta.deliveryUnconfirmed
     -          // Stamp the server-minted row id the receipt carried back. The bubble
     -          // was appended client-side with only a `sendId` (no server identity),
     -          // so either the user echo or this receipt can supply its identity.
    @@ website/src/store/chatSlice.ts: export const requestStop = createAsyncThunk<Stop
     -      }
     -      if (!confirm(state.messages)) confirm(state.slotMessages[safeKey(slot)])
     -    },
    +-    /** Record that a send's own receipt never came: the transport deadline
    +-     *  fired (`response-late`) and no correlated echo has confirmed the row, so
    +-     *  the bubble stays `optimistic` and only a late echo can still clear it.
    +-     *  Stamps `meta.deliveryUnconfirmed` on that bubble; the row's pending line
    +-     *  is drawn from THIS mark, never from `optimistic` alone, because the flag
    +-     *  also survives a `refused` or `transport-error` send (whose error row and
    +-     *  restored composer already say what happened) and a `queued` receipt
    +-     *  (whose card owns the text), so a line keyed on it would claim a wait on
    +-     *  rows nobody is waiting for. Client-minted like `optimistic`, never sent,
    +-     *  and cleared by the same two doors (`confirmOptimisticSend`, the echo
    +-     *  reconcile). Scans BOTH arrays as `confirmOptimisticSend` does; a row an
    +-     *  echo already confirmed is left alone. */
    +-    markSendUnconfirmed(state, action: PayloadAction<{ slot: string; sendId: string }>) {
    +-      const { slot, sendId } = action.payload
    +-      if (isUnsafeKey(slot)) return
    +-      const mark = (msgs: ChatMessage[] | undefined): boolean => {
    +-        if (!msgs) return false
    +-        const floor = Math.max(0, msgs.length - RECONCILE_WINDOW)
    +-        for (let i = msgs.length - 1; i >= floor; i--) {
    +-          const m = msgs[i]
    +-          if (m.role !== 'user' || m.meta?.sendId !== sendId) continue
    +-          if (m.meta?.optimistic) m.meta = { ...m.meta, deliveryUnconfirmed: true }
    +-          return true
    +-        }
    +-        return false
    +-      }
    +-      if (!mark(state.messages)) mark(state.slotMessages[safeKey(slot)])
    +-    },
     -    /** Resolve an optimistic steer bubble against the steer POST's own receipt.
     -     *
     -     *  `meta.steer` draws the "Steered into the running turn" badge, so it is an
    @@ website/src/store/chatSlice.ts: const chatSlice = createSlice({
      export const {
     -  setActiveSlot, clearSlotState, setPendingInput, setAgentSwitchNotice, clearSwitchSlotGone, clearUnresumableResume, clearUndeletableHistory, setQuestionCard, clearQuestionCard, setQuestionDraft, resolveQuestionCard, setFollowupCard, clearFollowupCard, dismissFollowupItem, setFolderSuggestion, clearFolderSuggestion, ageFolderSuggestion, appendMessage, appendSlotMessage, updateStreamingMessage, finalizeAssistant,
     +  setActiveSlot, clearSlotState, setPendingInput, setAgentSwitchNotice, clearUnresumableResume, clearUndeletableHistory, setQuestionCard, clearQuestionCard, setQuestionDraft, resolveQuestionCard, setFollowupCard, clearFollowupCard, dismissFollowupItem, setFolderSuggestion, clearFolderSuggestion, ageFolderSuggestion, appendMessage, appendSlotMessage, updateStreamingMessage, finalizeAssistant,
    -   removeThinking, confirmOptimisticSend, resolveOptimisticSteer, removeByApprovalId, resolveByApprovalId, clearPendingPermissions, setSlotRunning, setSlotStopping, settleStopNotRunning, startLocalTurn, endLocalTurn, syncSlotRunningFromServer, setSlotState, setSlotStatusDetail, setStopPressedAt, clearMessages, clearSlotCache, truncateAfterIndex, replaceMessages, hydrateSlotMessages, sseChatMessage, sseChatMessageUpdate, sseChatMessagePatchByTs, sseThinkingChunk, removeQueuedMessage, appendQueuedMessage, cancelQueuedMessage, editQueuedMessage, reorderQueuedMessages,
    +   removeThinking, confirmOptimisticSend, markSendUnconfirmed, resolveOptimisticSteer, removeByApprovalId, resolveByApprovalId, clearPendingPermissions, setSlotRunning, setSlotStopping, settleStopNotRunning, startLocalTurn, endLocalTurn, syncSlotRunningFromServer, setSlotState, setSlotStatusDetail, setStopPressedAt, clearMessages, clearSlotCache, truncateAfterIndex, replaceMessages, hydrateSlotMessages, sseChatMessage, sseChatMessageUpdate, sseChatMessagePatchByTs, sseThinkingChunk, removeQueuedMessage, appendQueuedMessage, cancelQueuedMessage, editQueuedMessage, reorderQueuedMessages,
        sseContextUsage, setVoicePlaying, setVoiceAudio,
        toggleActivity, openActivityToTab, openActivityPanel, openActivityToTool, clearFocusToolCallId, requestSlotReveal, clearSlotReveal, requestFolderReveal, clearSubagentsForSnapshot, sseSubagentPending, markSubagentApproving, sseSubagentSpawn, sseSubagentTool, sseSubagentStalled, sseSubagentRetrying, sseSubagentDone, sseSubagentQueued,
     @@ website/src/store/chatSlice.ts: export const {
    @@ website/src/store/chatSlice.ts: export const {
     +export { queueEditBroadcastAt } from './chat/side'
     +export {
     +  selectActiveSlotProject, selectComposerBusy, selectContinuable, selectSendConfirmed, selectSlotMessages,
    -+  selectSlotPendingApproval, selectSlotRunEpoch, selectSlotStreamState, selectSlotToolLog, selectTurnInterrupted,
    ++  selectSlotPendingApproval, selectSlotRunEpoch, selectSlotStreamState, selectSlotToolLog, selectTrailingSendUnconfirmed,
    ++  selectTurnInterrupted,
     +} from './chat/selectors'
     +export { clearSwitchSlotGone, switchSlot, switchSlotNoticeCopy, type SwitchSlotArg } from './chat/slotSwitch'
     +export { refreshSlot, warmSlotCache } from './chat/slotRefresh'

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: passed Eligible automated validation passed for the current revision merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: checking Automated validation is still running labels Sep 29, 2026
@bolichen97
bolichen97 force-pushed the refactor/f04-chat-redux-state branch from a413c27 to 3a47f14 Compare September 29, 2026 02:12
@bolichen97

Copy link
Copy Markdown
Contributor Author

Docs-only amend (a413c275a -> 3a47f140f): the Design and UX lanes failed closed on a413c275a in their diff prefetch step with diff exceeds 1 MB; failing closed (split the PR). The PR diff was 1,001,973 bytes against a 1,000,000 cap, pushed over by the #14699 port, which counts once as a deletion from the facade and once as an addition to the owners.

This amend reverts one pointer swap only: the docs/feature-map/README.md "Default memory mode" row goes back to main's text (store/chatSlice.ts). That row's lines run to thousands of characters, so the one-line swap cost about 13 KB of diff. The name still resolves through the facade's createSlot export, and the re-point to store/chat/lifecycle.ts is logged for a docs-sync PR after merge. No code changed: git diff a413c275a 3a47f140f touches only that file. The diff is now 989,015 bytes, and the same when simulated as a merge onto main 2e09b1030.

The frozen "Not a goal" bullet still says "Five other docs"; with this revert it is four (learn-cron-dashboard.md, followup-suggestions-trust-model.md and the two RFCs).

Verdicts on a413c275a before the amend: Opus 5 "No findings" (published). GPT 5.6 produced "No findings" but could not publish it (failed comment read; withheld-verdict artifact 11008385890). All CI checks passed.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 29, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: passed Eligible automated validation passed for the current revision merge conflict Branch has merge conflicts with its base — author must resolve before merge labels Sep 29, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author

One exact-job rerun on 9e13b5066: Backend Tests (Windows) (4) (job 109277138717, CI run 36528485744) failed a single node, with 16,729 others passing:

test/test_diag_procs.py::test_a_read_refused_as_too_soon_does_not_restart_the_window - AssertionError: 0.8s apart is under the floor

This PR changes only website/ and docs/ files, and no Python. That test times reads against a 1 s wall-clock floor. The same node passes 3/3 locally at this head. I am rerunning only that job, once.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=8abffc040039 side.md sseSideQueue sentence correction was undeclared

fixed (description only, no code change): the PR body's "What changed" now declares it. side.md also corrects one sentence that was already false about the unchanged sseSideQueue reducer: a redelivered push id is ignored, never rewritten, and front head-inserts.
The reducer is byte-identical to base, as the review notes. The sentence sits in the side.md section this PR had to re-own (### store/chat/side.ts — Side State), so it was rewritten to match the code, not to change behaviour.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 29, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author

Infra rerun on 9e13b5066, no code change: editing the description (to declare the side.md sentence fix) started a second GPT 5.6 Review run, 36532063687. Its Resolve human override step died on gh: API rate limit exceeded for installation before any verdict was published (request ids 1C40:354B37:F3EE5B:32A4CA8:6ABB5D13 and 1C41:118B5D:FF71F4:34EB604:6ABB5D14, 06:39:15Z). Its post step then found this head's slot already holding the earlier run's verdict (run 36528485441, "No findings"). After waiting 20+ minutes for the installation budget, I reran it once with --failed.

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: action required A blocking check or review needs attention labels Sep 29, 2026
chatSlice.ts had grown to 7,572 lines holding every chat reducer, thunk,
selector, wire guard and transcript calculation, with a 1,042-line
extraReducers builder. Changes to one responsibility meant reading and
merging against all of them.

The slice now composes cohesive owners under website/src/store/chat/:
the wire trust boundary, pure transcript and paging calculations, the
state shape, reducer families (run state, slot cache, messages, queue,
composer cards, activity, sub-agents, automations, side chat, workflows,
MCP apps), the switch/refresh/lifecycle thunks with their extra
reducers, slot teardown, and selector families. chatSlice.ts stays the
single createSlice wiring point and the facade every consumer imports:
action type strings, action creators, thunk prefixes, selectors,
constants, types, initial state and the default reducer export are
unchanged. The constructs source-text oracles read from chatSlice.ts
stay there.

New characterization tests pin the public surface and initial state,
prototype-key guards across every reducer family and every depth of
the state tree, and the ownership shape (no owner imports the facade,
acyclic owner imports, facade-only access from outside src/store,
disjoint reducer families, re-export identity). The session, history,
mcp-apps, side and subagent specs record the new owners, and four
other docs have the file or symbol pointers the move made false
re-pointed.
@bolichen97
bolichen97 force-pushed the refactor/f04-chat-redux-state branch from 9e13b50 to f9bdba8 Compare September 29, 2026 08:20
@bolichen97

Copy link
Copy Markdown
Contributor Author

@buluoray Rebased again: new head f9bdba8fb16426ef92ef2a2056b914823eb7cc3b, one commit on main 244afb1d7. #14906 had also added a paragraph to history.md at the same spot, so both edits touched it. main's follow paragraph is kept verbatim, and this PR's chat-store owner block now sits after it. No code changed: the #14834 deleteSlot port and the #14913 sseSubagentDone port are unchanged from the head you were asked to re-review, and both are still identical to main. Re-gated at this head: 442 store and chat test files (7,160 tests), tsc, eslint, docs-lint; diff 989,637 bytes.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: passed Eligible automated validation passed for the current revision and removed readiness: passed Eligible automated validation passed for the current revision merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: checking Automated validation is still running labels Sep 29, 2026
@iamwhatever
iamwhatever merged commit 4ae6a88 into main Sep 29, 2026
97 checks passed
@iamwhatever
iamwhatever deleted the refactor/f04-chat-redux-state branch September 29, 2026 15:30
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Sep 29, 2026
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.

3 participants