Skip to content

refactor(chat): replace RQ-backed thread caches with ThreadManagerStore - #3401

Merged
tlgimenes merged 77 commits into
mainfrom
tlgimenes/chat-thread-store
May 20, 2026
Merged

tlgimenes merged 77 commits into
mainfrom
tlgimenes/chat-thread-store

Conversation

@tlgimenes

@tlgimenes tlgimenes commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

What is this contribution about?

Replaces the React-Query-backed thread/message caches in the chat module with a single class-based store (ThreadManagerStore) fed by SSE snapshot-on-connect from /api/:org/events and /api/:org/decopilot/threads/:id/stream. Drops the cache-patching ThreadEventsBridge, the scope-key cache fan-out, and the GET-before-CREATE dance on thread navigation — the server's idempotent COLLECTION_THREADS_CREATE is now the only thread tool call on a "new thread + send" flow (down from 1 CREATE + 1 GET, sometimes duplicated under React Strict Mode). Also fixes the user-ask form's "Submit" button to be a "Next" button until every item is answered, and refreshes the tasks-panel relative timestamps on a 60s heartbeat so "3m ago" no longer freezes when the panel's data is referentially stable.

Screenshots/Demonstration

Smoke-tested in-browser at http://semarang-v2.localhost/gimenes-local: new-thread create, send/receive, snapshot rebuild on revisit, hover-archive, status transitions in the panel, multi-turn streaming, title auto-update — all clean, no console errors.

How to Test

  1. Pull this branch, run `bun run dev`.
  2. Open `http://.localhost/`. Send a message from the home composer — verify network shows exactly one `COLLECTION_THREADS_CREATE` and the SSE feeds `/api//events` and `/.../stream` open without firing `COLLECTION_THREADS_LIST` or `COLLECTION_THREAD_MESSAGES_LIST`.
  3. Verify the tasks panel row's status transitions `in_progress` → `completed`/`requires_action` live during a turn, the auto-titler's title appears once it streams, archive-from-hover works, and relative timestamps tick forward without needing a list mutation.

Migration Notes

No DB migrations. Existing `COLLECTION_THREADS_LIST` / `COLLECTION_THREAD_MESSAGES_LIST` tools remain for API consumers; chat module just stops calling them.

Review Checklist

  • PR title is clear and descriptive
  • Changes are tested and working
  • Documentation is updated (if needed)
  • No breaking changes

Summary by cubic

Replaced React Query chat caches with a unified ThreadManagerStore that loads threads via COLLECTION_THREADS_LIST, tails /api/:org/watch for live updates (shared EventSource per org), and seeds per‑thread messages from COLLECTION_THREAD_MESSAGES_LIST with reconnect refetch and infinite scroll. /api/:org/decopilot/threads/:id/stream remains a pure live tail; titles/statuses stay in sync across tabs and “new thread + send” is a single COLLECTION_THREADS_CREATE.

  • New Features

    • Shared decopilot SSE pool for /api/:org/watch (decopilotSSE) with per-subscriber onReconnect; ThreadManagerStore subscribes through it to avoid duplicate connections and to resync after drops.
  • Bug Fixes

    • Chat opens completed threads anchored to the bottom (no off-screen assistant reply); streaming/submitted threads keep the sticky top pin.
    • Avoided spurious COLLECTION_THREADS_CREATE on deep-linked threads by waiting for fetchThread to finish in useEnsureTask.

Written for commit 89b94fc. Summary will update on new commits. Review in cubic

@github-actions

Copy link
Copy Markdown
Contributor

🧪 Benchmark

Should we run the Virtual MCP strategy benchmark for this PR?

React with 👍 to run the benchmark.

Reaction Action
👍 Run quick benchmark (10 & 128 tools)

Benchmark will run on the next push after you react.

@github-actions

github-actions Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Release Options

Suggested: Patch (2.336.7) — based on refactor: prefix

React with an emoji to override the release type:

Reaction Type Next Version
👍 Prerelease 2.336.7-alpha.1
🎉 Patch 2.336.7
❤️ Minor 2.337.0
🚀 Major 3.0.0

Current version: 2.336.6

Note: If multiple reactions exist, the smallest bump wins. If no reactions, the suggested bump is used (default: patch).

@cubic-dev-ai cubic-dev-ai 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.

10 issues found across 42 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/mesh/src/web/layouts/tasks-panel/index.tsx">

<violation number="1" location="apps/mesh/src/web/layouts/tasks-panel/index.tsx:51">
P2: Handle the promise returned by `hide(task.id)` to avoid unhandled rejections when archiving fails.</violation>
</file>

<file name="apps/mesh/src/web/components/chat/highlight/user-ask-question.tsx">

<violation number="1" location="apps/mesh/src/web/components/chat/highlight/user-ask-question.tsx:401">
P2: Pressing Enter in the form triggers `decisionForm.submit()`, which silently does nothing when not every question is answered. This creates a behavioral inconsistency: the button (now `submitOrAdvance`) advances to the next question, but Enter does nothing. Change both `<form onSubmit>` handlers to `decisionForm.submitOrAdvance()` to match the new button behavior.</violation>
</file>

<file name="apps/mesh/src/api/routes/decopilot/routes.ts">

<violation number="1" location="apps/mesh/src/api/routes/decopilot/routes.ts:94">
P2: Cancellation is attempted on a locked ReadableStream, so downstream cancel may not stop the upstream stream.</violation>
</file>

<file name="apps/mesh/src/web/components/chat/store/thread-manager-store.ts">

<violation number="1" location="apps/mesh/src/web/components/chat/store/thread-manager-store.ts:206">
P2: Reconnect backoff adds abort listeners without cleanup on timeout, causing listener accumulation over repeated retries.</violation>
</file>

<file name="apps/mesh/src/web/hooks/use-ensure-task.ts">

<violation number="1" location="apps/mesh/src/web/hooks/use-ensure-task.ts:71">
P1: Guard mutation-derived `data` by the current `id`; otherwise a previous successful create can be returned for a different task id.</violation>
</file>

Tip: cubic can generate docs of your entire codebase and keep them up to date. Try it here.

Re-trigger cubic

Comment thread apps/mesh/src/api/app.ts Resolved
Comment on lines +71 to 74
if (ensureCreate.data) return { status: "ready", task: ensureCreate.data };
if (ensureCreate.isError) {
return { status: "error", error: ensureCreate.error };
}

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.

P1: Guard mutation-derived data by the current id; otherwise a previous successful create can be returned for a different task id.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mesh/src/web/hooks/use-ensure-task.ts, line 71:

<comment>Guard mutation-derived `data` by the current `id`; otherwise a previous successful create can be returned for a different task id.</comment>

<file context>
@@ -35,95 +35,45 @@ type State =
-    return { status: "creating" };
-  }
+  if (localHit) return { status: "ready", task: localHit };
+  if (ensureCreate.data) return { status: "ready", task: ensureCreate.data };
   if (ensureCreate.isError) {
     return { status: "error", error: ensureCreate.error };
</file context>
Suggested change
if (ensureCreate.data) return { status: "ready", task: ensureCreate.data };
if (ensureCreate.isError) {
return { status: "error", error: ensureCreate.error };
}
if (ensureCreate.variables === id && ensureCreate.data) {
return { status: "ready", task: ensureCreate.data };
}
if (ensureCreate.variables === id && ensureCreate.isError) {
return { status: "error", error: ensureCreate.error };
}

const handleArchive = (task: Task) => {
const wasActive = task.id === activeTaskId;
hideThread(task.id);
hide(task.id);

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.

P2: Handle the promise returned by hide(task.id) to avoid unhandled rejections when archiving fails.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mesh/src/web/layouts/tasks-panel/index.tsx, line 51:

<comment>Handle the promise returned by `hide(task.id)` to avoid unhandled rejections when archiving fails.</comment>

<file context>
@@ -47,7 +48,7 @@ function TasksPanelContent() {
   const handleArchive = (task: Task) => {
     const wasActive = task.id === activeTaskId;
-    hideThread(task.id);
+    hide(task.id);
 
     if (!wasActive) return;
</file context>

isAllAnswered={decisionForm.isAllAnswered}
onSubmit={decisionForm.submit}
isCurrentAnswered={decisionForm.isCurrentAnswered}
onAdvanceOrSubmit={decisionForm.submitOrAdvance}

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.

P2: Pressing Enter in the form triggers decisionForm.submit(), which silently does nothing when not every question is answered. This creates a behavioral inconsistency: the button (now submitOrAdvance) advances to the next question, but Enter does nothing. Change both <form onSubmit> handlers to decisionForm.submitOrAdvance() to match the new button behavior.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mesh/src/web/components/chat/highlight/user-ask-question.tsx, line 401:

<comment>Pressing Enter in the form triggers `decisionForm.submit()`, which silently does nothing when not every question is answered. This creates a behavioral inconsistency: the button (now `submitOrAdvance`) advances to the next question, but Enter does nothing. Change both `<form onSubmit>` handlers to `decisionForm.submitOrAdvance()` to match the new button behavior.</comment>

<file context>
@@ -397,7 +397,8 @@ function UserAskPrompt({ parts, isStreaming, onSubmit }: UserAskPromptProps) {
         isAllAnswered={decisionForm.isAllAnswered}
-        onSubmit={decisionForm.submit}
+        isCurrentAnswered={decisionForm.isCurrentAnswered}
+        onAdvanceOrSubmit={decisionForm.submitOrAdvance}
       />
     </>
</file context>

Comment thread apps/mesh/src/api/events-watch.test.ts Resolved
@tlgimenes
tlgimenes force-pushed the tlgimenes/chat-thread-store branch from c177253 to 2373c12 Compare May 19, 2026 18:44

@cubic-dev-ai cubic-dev-ai 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.

3 issues found across 41 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/mesh/src/web/layouts/tasks-panel/index.tsx">

<violation number="1" location="apps/mesh/src/web/layouts/tasks-panel/index.tsx:51">
P2: Handle the promise returned by `hide(task.id)` to avoid unhandled rejections when archiving fails.</violation>
</file>

<file name="apps/mesh/src/web/components/chat/highlight/user-ask-question.tsx">

<violation number="1" location="apps/mesh/src/web/components/chat/highlight/user-ask-question.tsx:401">
P2: Pressing Enter in the form triggers `decisionForm.submit()`, which silently does nothing when not every question is answered. This creates a behavioral inconsistency: the button (now `submitOrAdvance`) advances to the next question, but Enter does nothing. Change both `<form onSubmit>` handlers to `decisionForm.submitOrAdvance()` to match the new button behavior.</violation>
</file>

<file name="apps/mesh/src/web/components/chat/store/thread-manager-store.ts">

<violation number="1" location="apps/mesh/src/web/components/chat/store/thread-manager-store.ts:206">
P2: Reconnect backoff adds abort listeners without cleanup on timeout, causing listener accumulation over repeated retries.</violation>

<violation number="2" location="apps/mesh/src/web/components/chat/store/thread-manager-store.ts:291">
P2: When initial thread-list fetch fails, event buffering is never drained, so live `/watch` thread events stop updating the store until a reconnect.</violation>
</file>

<file name="apps/mesh/src/web/hooks/use-ensure-task.ts">

<violation number="1" location="apps/mesh/src/web/hooks/use-ensure-task.ts:71">
P1: Guard mutation-derived `data` by the current `id`; otherwise a previous successful create can be returned for a different task id.</violation>
</file>

<file name="apps/mesh/src/api/routes/decopilot/run-reactor.ts">

<violation number="1" location="apps/mesh/src/api/routes/decopilot/run-reactor.ts:75">
P2: `updatedAt` is emitted from a stale pre-update thread snapshot in terminal status handling. Emit metadata from a post-update read (or DB-returned updated row) so clients receive the correct timestamp.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

title: thread?.title,
branch: thread?.branch ?? null,
createdAt: thread?.created_at,
updatedAt: thread?.updated_at,

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.

P2: updatedAt is emitted from a stale pre-update thread snapshot in terminal status handling. Emit metadata from a post-update read (or DB-returned updated row) so clients receive the correct timestamp.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mesh/src/api/routes/decopilot/run-reactor.ts, line 75:

<comment>`updatedAt` is emitted from a stale pre-update thread snapshot in terminal status handling. Emit metadata from a post-update read (or DB-returned updated row) so clients receive the correct timestamp.</comment>

<file context>
@@ -69,6 +69,10 @@ async function handleTerminalStatus(
+      title: thread?.title,
+      branch: thread?.branch ?? null,
+      createdAt: thread?.created_at,
+      updatedAt: thread?.updated_at,
     }),
   );
</file context>

@cubic-dev-ai cubic-dev-ai 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.

2 issues found across 76 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/mesh/src/web/layouts/tasks-panel/index.tsx">

<violation number="1" location="apps/mesh/src/web/layouts/tasks-panel/index.tsx:51">
P2: Handle the promise returned by `hide(task.id)` to avoid unhandled rejections when archiving fails.</violation>
</file>

<file name="apps/mesh/src/web/components/chat/highlight/user-ask-question.tsx">

<violation number="1" location="apps/mesh/src/web/components/chat/highlight/user-ask-question.tsx:401">
P2: Pressing Enter in the form triggers `decisionForm.submit()`, which silently does nothing when not every question is answered. This creates a behavioral inconsistency: the button (now `submitOrAdvance`) advances to the next question, but Enter does nothing. Change both `<form onSubmit>` handlers to `decisionForm.submitOrAdvance()` to match the new button behavior.</violation>
</file>

<file name="apps/mesh/src/web/hooks/use-ensure-task.ts">

<violation number="1" location="apps/mesh/src/web/hooks/use-ensure-task.ts:71">
P1: Guard mutation-derived `data` by the current `id`; otherwise a previous successful create can be returned for a different task id.</violation>
</file>

<file name="apps/mesh/src/api/routes/decopilot/run-reactor.ts">

<violation number="1" location="apps/mesh/src/api/routes/decopilot/run-reactor.ts:75">
P2: `updatedAt` is emitted from a stale pre-update thread snapshot in terminal status handling. Emit metadata from a post-update read (or DB-returned updated row) so clients receive the correct timestamp.</violation>

<violation number="2" location="apps/mesh/src/api/routes/decopilot/run-reactor.ts:75">
P2: Terminal status events can publish a stale `updatedAt` timestamp because it is read before the DB update.</violation>
</file>

<file name="apps/mesh/src/harnesses/decopilot/run-stream.ts">

<violation number="1" location="apps/mesh/src/harnesses/decopilot/run-stream.ts:428">
P2: `onTitleUpdated` is called even if `threads.update` fails, so other tabs can receive a title update that was not actually committed.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

// Notify subscribers outside the per-thread /stream (other tabs,
// panels). Best-effort: a publish failure must not break the run.
try {
await onTitleUpdated?.(title);

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.

P2: onTitleUpdated is called even if threads.update fails, so other tabs can receive a title update that was not actually committed.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mesh/src/harnesses/decopilot/run-stream.ts, line 428:

<comment>`onTitleUpdated` is called even if `threads.update` fails, so other tabs can receive a title update that was not actually committed.</comment>

<file context>
@@ -409,6 +422,17 @@ export async function* runDecopilotStream(
+        // Notify subscribers outside the per-thread /stream (other tabs,
+        // panels). Best-effort: a publish failure must not break the run.
+        try {
+          await onTitleUpdated?.(title);
+        } catch (err) {
+          console.error(
</file context>

title: thread?.title,
branch: thread?.branch ?? null,
createdAt: thread?.created_at,
updatedAt: thread?.updated_at,

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.

P2: Terminal status events can publish a stale updatedAt timestamp because it is read before the DB update.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mesh/src/api/routes/decopilot/run-reactor.ts, line 75:

<comment>Terminal status events can publish a stale `updatedAt` timestamp because it is read before the DB update.</comment>

<file context>
@@ -69,6 +69,10 @@ async function handleTerminalStatus(
+      title: thread?.title,
+      branch: thread?.branch ?? null,
+      createdAt: thread?.created_at,
+      updatedAt: thread?.updated_at,
     }),
   );
</file context>

@tlgimenes
tlgimenes force-pushed the tlgimenes/chat-thread-store branch from c6965d2 to 8eff412 Compare May 20, 2026 18:37
tlgimenes and others added 23 commits May 20, 2026 15:38
The GET /api/:org/decopilot/threads/:threadId/stream endpoint now emits a
single `event: snapshot` SSE frame carrying `{ messages: [...] }` before it
starts tailing the per-thread JetStream subject. The payload is sourced
through `ctx.storage.threads.listMessages` — the same path that backs
`COLLECTION_THREAD_MESSAGES_LIST` — so the snapshot is consistent with the
tool's view of the thread.

This lets reconnecting clients rebuild thread state deterministically on
every (re)connect without a separate snapshot round-trip. The snapshot frame
is prepended at the byte layer (the AI SDK's JsonToSseTransformStream only
emits anonymous `data:` events), with cancel propagation forwarded to the
underlying tail stream.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The GET /api/:org/events SSE handler now emits a single `event: snapshot`
frame carrying `{ threads: [...] }` after the existing `connected` event and
before the listener is registered with `sseHub`. The payload is sourced
through `ctx.storage.threads.list` — the same path that backs
`COLLECTION_THREADS_LIST` — so reconnecting clients can rebuild the open
thread list deterministically without a separate REST round-trip.

The snapshot is gated by the listener's `?types=...` filter using the SSE
hub's own `matchesAnyPattern` matcher (now exported), so it fires exactly
when the listener would also receive live `com.deco.decopilot.thread.*`
events — no drift between snapshot coverage and live delivery.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The SSE `/api/:org/events` snapshot was emitting raw `Thread` rows from
storage, while `COLLECTION_THREADS_LIST` runs every row through
`normalizeThreadForResponse`. That meant a stale `in_progress` thread
showed as `status: "in_progress"` in the snapshot but `status: "expired"`
through the existing tool path — a divergence that would surface as soon
as the upcoming client store consumed both.

The snapshot now runs rows through the same normalizer (coerces
`hidden: null` → `false`; surfaces stale in_progress threads as the
virtual `"expired"` status). A new test seeds a row with `updated_at`
≥ 31min in the past and asserts the snapshot reports `"expired"`.

Also adds a JSDoc note on `THREAD_SNAPSHOT_PROBE_TYPE` documenting that
listeners subscribing to a single specific thread event type by exact
name (no wildcard) receive live events but not the initial snapshot, and
that the supported pattern is `com.deco.decopilot.thread.*`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
If `ctx.storage.threads.list` throws while building the SSE snapshot, the
response headers have already been flushed (the `connected` event was
written first), so Hono's `streamSSE` silently terminates the stream with
no error frame the client can detect. Wrap the snapshot read in a narrow
try/catch and emit `event: error` (mirroring the "Too many connections"
shape) then return to close the stream so the client's reconnect loop
retries — running with no snapshot would leave the UI inconsistent.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bootstrap() no longer POSTs to COLLECTION_THREAD_MESSAGES_LIST for the
initial snapshot. SSE opens immediately; the server's first `event:
snapshot` frame seeds `messages` and flips status loading→ready. On
reconnect, the snapshot frame replaces messages unless a local submit
is in flight (mirrors the prior refresh() guard).

The SSE body is now parsed as raw SSE frames (manual newline splitter)
instead of being piped through parseJsonEventStream. Snapshot frames
are routed separately; all other frames are validated against
uiMessageChunkSchema and folded into the assistant message as before.

refresh() stays as a no-op stub until thread-events.tsx is deleted in
Phase 6 (Task 20). Removed fetchSnapshot() and parseSseSingleResponse()
entirely.

Tests:
- Rewrote "thread-boot" to assert the snapshot arrives via SSE.
- Rewrote "thread-boot-err" to assert an HTTP 500 on /stream
  transitions to error.
- Dropped "refresh re-fetches snapshot" and "refresh guard during
  submit" — the refactor removes the code path they exercised; SSE
  reconnect now re-emits the snapshot, and the in-flight-submit guard
  is covered by the snapshot handling in handleStreamFrame.
- Updated the fetch-mock helpers to emit an empty snapshot frame on
  the default /stream response so other tests still transition out of
  loading.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The Task 10 refactor of ThreadConnection.runSseLoop used delay=0 on
clean stream end (graceful tail). In production this is fine; in tests
where mocked fetch returns a closed stream, the loop spins so fast that
afterEach can't fire to dispose the conn, causing 100%+ CPU and OOM.

Two changes:
- Add a 50ms minimum delay on clean reconnect. Imperceptible in
  production, breathing room for the test runner.
- Add proper afterEach cleanup in thread-manager-store.test.ts that
  disposes both registries (conn + manager) after every test.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds the React hook layer for ThreadManagerStore so call sites can read
from the manager via context + useSyncExternalStore:

  - ThreadManagerProvider constructs/reuses the manager via
    getOrOpenManager(orgSlug, locator, { client }). Because the registry
    keys on `${orgSlug}::${locator}`, repeated provider renders return
    the same instance — no useEffect needed.
  - useThreadManager / useThreads / useThreadStatus expose the manager's
    top-level Store<T> slots.
  - useActiveThread / useThreadMessages / useThreadConnStatus /
    useFinishReason wrap the active conn's stores, falling back to
    module-scoped stable noopSubscribe + default-getters when no conn is
    active (so useSyncExternalStore's identity-stability rules hold).
  - useThreadActions returns bound mutators (create/rename/hide/
    setStatus/setBranch/setActive/closeActive); the React compiler keeps
    the returned object stable.

Store-level tests cover the underlying state the hooks read from
(threads snapshot, active flip on setActive, messages reflecting the
conn's /stream snapshot). renderHook coverage is deferred — the repo
doesn't ship @testing-library/react and the hooks are one-line wrappers
over the manager's Stores. Deeper coverage lands at the migration call
sites in Phase 5.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Swap the four remaining .create.mutateAsync({ data: ... }) callers over
to the new useThreadActions hook from store/hooks. The new create takes
the inner ThreadCreateData shape directly and returns Promise<Task>.
Consult ThreadManagerStore.threads first via useSyncExternalStore; skip
the MCP GET when the org snapshot already knows the thread. On 404,
delegate creation to manager.create — the store owns list insertion, so
the legacy threadsPrefix cache priming and THREADS collection
invalidation drop out.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…-ops

The new ThreadManagerStore + hooks (store/) own the chat data layer end to
end after Phase 5. Removes the parallel task/* modules: thread-store.ts
(useThreads), thread-events.tsx (SSE→cache bridge), thread-actions.ts
(mutations), cache-operations.ts, and the matching test files. Also drops
the temporary ThreadConnection.refresh() no-op kept alive only for the
bridge, removes the <ThreadEventsBridge /> mount in OrgShellLayout, and
trims task/index.ts to expose only filter helpers + Task/ChatMessage
types — folding Task 22's doc update into the same commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The legacy ThreadEventsBridge was the only caller of KEYS.threads. After
deleting it the entry has zero references; drop it. KEYS.threadsPrefix
stays — it's still used by read-cached-last-thread / read-cached-task-branch
to peek at any thread-scoped cache entry without knowing the scope key.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The provider must be above <StudioSidebar /> because agents-section
calls useThreadActions to create threads. Previously placed it inside
SidebarInset → StudioSidebar threw "missing ThreadManagerProvider"
on mount. Hoisting it above SidebarProvider also covers the panel
state provider which calls useThreads internally.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
tlgimenes and others added 20 commits May 20, 2026 15:38
"start" anchored the active row to the top of the container on every
selection change, even when the row was already comfortably in view —
yanking the scroll position around. "nearest" only scrolls if the row
isn't visible, picking the minimal delta to bring it on-screen.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Removes prependSnapshotFrame and the per-connect listMessages call.
The client will own initial-page load via COLLECTION_THREAD_MESSAGES_LIST
in a subsequent commit on this branch.
…t factory

makeStreamApp no longer takes a messages array — the handler no longer
calls listMessages, so the mock just records call count and returns empty.
Falsy check \`!md?.created_at\` would silently sort a message with
created_at: 0 to the end (POSITIVE_INFINITY) — incorrect since 0 is
a valid Unix epoch timestamp. Switch to == null. Also adds tests
for both-empty input, numeric timestamps, and duplicate-id last-wins.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Plumbing-only commit — client field is set but not yet read. Subsequent
commits use it for initial-page load, reconnect refetch, and fetch-older.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…rough setActive

- Rename private client → _client so TypeScript's noUnusedLocals exempts
  the intentionally-unread field. Will be renamed back when T5 first
  uses it.
- ThreadManagerStore.setActive now forwards this.client to
  getOrOpenStream, preventing a latent null-client regression when
  setActive wins the registry slot before the provider's call.
ThreadConnection now boots by calling COLLECTION_THREAD_MESSAGES_LIST
(latest page, size 5, sort desc) in parallel with the SSE connect.
UIMessageChunks arriving before the page resolves are queued in
chunkBuffer and drained through handleChunk after the page lands.

Includes the pagination state (hasMoreOlder/isFetchingOlder Stores,
serverFetchedCount/pageSize private fields) staged in the prior
working tree.

Removes reliance on the server snapshot frame for initial state.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… guard dispose race

- Client now passes orderBy: [{ field: ["created_at"], direction: "desc" }]
  to the MCP tool. Previously sent sort: "desc" which Zod silently
  stripped (not in CollectionListInputSchema), causing the initial page
  to return the oldest 5 messages instead of the newest 5.
- COLLECTION_THREAD_MESSAGES_LIST handler translates the first orderBy
  direction to storage.listMessages' sort param.
- loadInitialPage's success path now checks this.abort.signal.aborted
  before mutating state, preventing post-dispose state writes.
- Null-client branch flips status to ready before draining the buffer
  to avoid a loading → ready → streaming → ready flicker.
- Buffer test asserts the MCP call's argument shape so future regressions
  in this shape are caught.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The server no longer emits the frame; any stray legacy frame is now
silently ignored. Class docstring updated to describe the new boot
path (MCP page + chunk buffering) and reconnect refetch model.
Replaces the prior server-snapshot reconnect rebase. Merge is
upsert-by-id + sort by created_at, so optimistic local rows and
in-flight streaming rows survive the merge.
Page size 5, offset-cursored via serverFetchedCount, guarded against
concurrent calls via isFetchingOlder. Overlap with rows already in
'messages' is absorbed by mergeAndSort's upsert-by-id.
When the top 1px sentinel enters the viewport, fire fetchOlderMessages
and re-anchor scrollTop by the height delta so the user's reading
position is preserved through the prepend.
- fetchOlderMessages context value is now conn.fetchOlderMessages.bind(conn)
  instead of a fresh closure per render. The previous shape caused
  useTopSentinel's effect to re-run on every streaming chunk (since
  ChatStreamProvider re-renders on each chunk), churning the
  IntersectionObserver subscribe/unsubscribe pair many times per second.
- ThreadConnectionOptions is module-internal now (was exported but no
  external caller imports it — knip would flag).
- Reconnect-refetch test comment clarified: streamSlot.close() is a
  clean exit, so CLEAN_RECONNECT_DELAY_MS (50ms) is the actual reconnect
  delay; the 1100ms wait is intentional padding for test scheduling.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Both stores called identical 10-line copies of the helper. Future
divergence (e.g. a richer MCP error shape) would silently inconsistify
the two. New module lives next to its callers; only this helper for now.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Covers the contract introduced when the chat client started passing
orderBy to drive cold-boot pagination:
 • no orderBy → asc (legacy default preserved)
 • orderBy: [] → asc
 • orderBy created_at desc → newest first
 • desc + limit 2 → top 2 newest + hasMore + totalCount (cold-boot shape)
 • unsupported field name → direction respected, column fixed to created_at

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Persisted ThreadMessage rows carry created_at at the top level. Some
assistant rows additionally stamp metadata.created_at at run-start time,
which is EARLIER than the user message they answer — pulling the
timestamp from metadata sorted the assistant before its user, and
useMessagePairs discarded the assistant as an orphan, producing a
"No response was generated" empty-state for every reopened thread.

Fix: readTimestamp reads m.created_at via a defensive cast (UIMessage
doesn't declare the field) and ignores metadata.created_at entirely.
Updated all test fixtures to use top-level created_at; added a
regression test asserting metadata.created_at is ignored.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@tlgimenes
tlgimenes force-pushed the tlgimenes/chat-thread-store branch from 8eff412 to b0a6415 Compare May 20, 2026 18:41
ThreadConnection exposes a `ready` Promise that resolves once
loadInitialPage settles (success, error, or null-client). ActiveTaskProvider
calls React.use(conn.ready) before subscribing to messages/status — this
suspends the subtree so the existing <Suspense fallback={<Chat.Skeleton />}>
boundary in side-panel-chat.tsx catches it, replacing the previous
"empty list until MCP returns" first paint.

The Promise resolves rather than rejects on error so the error state is
shown inline (via status) instead of cascading to an ErrorBoundary.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@cubic-dev-ai

cubic-dev-ai Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

You're iterating quickly on this pull request. To help protect your rate limits, cubic has paused automatic reviews on new pushes for now—when you're ready for another review, comment @cubic-dev-ai review.

tlgimenes and others added 5 commits May 20, 2026 16:07
mention-slash.tsx:157 has the same render-time .current-assignment
pattern as chat-context.tsx (latest-closure forwarder, avoids useEffect
which is banned project-wide). Matches the existing TODO-marked
suppression in chat-context.tsx.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Resolved one conflict in apps/mesh/src/web/components/chat/tiptap/mention-slash.tsx.
Main refactored the slash-mention edit-chip bridge to inline the
callback directly on `mentionStorage.onEditChip`, eliminating the
requestEditRef + render-time .current assignment that needed the
oxlint-disable suppression added in 415cde2. Took main's version
verbatim — the suppression is no longer needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ThreadManagerStore opened its own fetch-based /watch loop in addition
to the EventSource pool used by useDecopilotEvents, so each org held
two parallel /watch connections. Lift the pool into a dedicated module
and have the store subscribe through it; extend SSESubscription with a
per-subscriber onReconnect hook so the store can still resync on drop.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The last-pair ref callback always called scrollIntoView({block:"start"})
on mount, which on a completed thread parks the user message at the top
of the viewport and leaves the assistant response off-screen below.
Branch on status: streaming/submitted keeps the sticky-at-top pin;
otherwise scrollTop is set to scrollHeight via a [data-chat-scroller]
marker on the chat scroller. Guarded by a didInitialScroll ref so the
unstable callback doesn't refire on every commit during streaming.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Distinguish "fetch in flight" from "fetch returned not found" so a direct
link to a thread outside the loaded snapshot no longer races a spurious
COLLECTION_THREADS_CREATE alongside the GET.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@tlgimenes
tlgimenes merged commit 8ebd903 into main May 20, 2026
16 checks passed
@tlgimenes
tlgimenes deleted the tlgimenes/chat-thread-store branch May 20, 2026 21:11
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.

1 participant