Skip to content

fix: only enable agent creation by default for team agents - #5

Merged
0xHericles merged 1 commit into
mainfrom
fix/disable-agent-create
Apr 4, 2025
Merged

0xHericles merged 1 commit into
mainfrom
fix/disable-agent-create

Conversation

@0xHericles

Copy link
Copy Markdown
Contributor

No description provided.

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

lgtm!

@0xHericles
0xHericles merged commit 91fd5bf into main Apr 4, 2025
tlgimenes added a commit that referenced this pull request May 19, 2026
- readCachedTaskBranch / readCachedLastThread now read from the manager
  singleton via getManager() instead of the legacy KEYS.threadsPrefix
  React Query cache (which is no longer populated by any writer).
- Call sites in useNavigateToAgentThread, usePanelActions,
  useChatMainPanelState, and agents-section pass (orgSlug, locator)
  instead of (queryClient, locator).
- useTaskMetadata subscribes to manager.threads via useSyncExternalStore;
  prefers localHit's metadata over the suspense-query fallback so a
  stale-null cache entry can't pin metadata for a freshly-created task.
- Drop dead KEYS.threadsPrefix entry now that no helper uses it.
- Test for readCachedLastThread rewritten to seed the manager directly.

Closes review findings #2 (cached readers return null in practice) and
\#5 (useTaskMetadata race after manager.create).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
tlgimenes added a commit that referenced this pull request May 20, 2026
- readCachedTaskBranch / readCachedLastThread now read from the manager
  singleton via getManager() instead of the legacy KEYS.threadsPrefix
  React Query cache (which is no longer populated by any writer).
- Call sites in useNavigateToAgentThread, usePanelActions,
  useChatMainPanelState, and agents-section pass (orgSlug, locator)
  instead of (queryClient, locator).
- useTaskMetadata subscribes to manager.threads via useSyncExternalStore;
  prefers localHit's metadata over the suspense-query fallback so a
  stale-null cache entry can't pin metadata for a freshly-created task.
- Drop dead KEYS.threadsPrefix entry now that no helper uses it.
- Test for readCachedLastThread rewritten to seed the manager directly.

Closes review findings #2 (cached readers return null in practice) and
\#5 (useTaskMetadata race after manager.create).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
tlgimenes added a commit that referenced this pull request May 20, 2026
…re (#3401)

* feat(decopilot): emit snapshot event on /stream connect

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]>

* feat(events): emit thread snapshot on SSE connect when subscribed

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]>

* fix(events): normalize thread snapshot + document probe-type limitation

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]>

* fix(events): emit error frame on snapshot failure

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]>

* refactor(chat): extract Store<T> primitive to store/

* feat(chat): ThreadManagerStore skeleton + /watch snapshot ingest

* feat(chat): apply thread.* CloudEvents to ThreadManagerStore

* feat(chat): optimistic create/rename/hide/setStatus/setBranch on store

* feat(chat): reconnect rebase preserves pending optimistic rows

* feat(chat): active-thread slot with setActive/closeActive

* feat(chat): module-scoped registry for ThreadManagerStore

* refactor(chat): ThreadConnection consumes /stream snapshot event

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]>

* refactor(chat): move ThreadConnection into store/

* fix(chat): prevent test hang from zero-delay reconnect loop

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]>

* feat(chat): React hooks for ThreadManagerStore

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]>

* feat(chat): mount ThreadManagerProvider alongside ThreadEventsBridge

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

* refactor(chat): migrate tasks panel to ThreadManagerStore hooks

* refactor(chat): migrate chat-context to ThreadManagerStore hooks

* refactor(chat): migrate create-thread call sites to ThreadManagerStore

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

* refactor(chat): use-ensure-task reads/creates via ThreadManagerStore

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]>

* refactor(chat): delete legacy thread-store / events / actions / cache-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]>

* chore(chat): remove dead KEYS.threads entry

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]>

* fix(chat): wrap entire org-shell with ThreadManagerProvider

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]>

* perf(chat): one COLLECTION_THREADS_CREATE per new thread (was 2-3)

Pre-refactor "new thread" click fired CREATE + GET (and sometimes a
duplicate CREATE). Trace:

1. The home composer (`useHomeSubmit` in input.tsx) navigated to the
   thread URL WITHOUT creating the row. `useEnsureTask` then fired
   CREATE in a useEffect — and React 19 Strict Mode's intentional
   double-mount duplicated it (the dedup guard against
   ensureCreate.isPending doesn't survive Strict Mode's hook re-init).
2. `use-main-panel-tabs.ts:useTaskMetadata` ran its own
   useSuspenseQuery(COLLECTION_THREADS_GET) against KEYS.ensureTask,
   firing a GET because the cache wasn't pre-populated under the new
   store-based read path.

Three fixes:

- `useHomeSubmit` now calls `manager.create()` before navigating, so
  the row is in `manager.threads` when the thread route mounts.
  `useEnsureTask` resolves localHit on first render and never fires.
- `useEnsureTask` now uses a single idempotent CREATE for its slow
  path (archived/cold-load case), since `COLLECTION_THREADS_CREATE` is
  server-side idempotent (`threads.ts:230-251` SELECT-returns the
  existing row on conflict).
- `useTaskMetadata` reads from `manager.threads` first; falls back to
  the one-shot GET only when the snapshot doesn't carry the thread
  (archived threads not in the open-list snapshot).

Net result on the "new thread + send" flow: 1 CREATE, 0 GETs (down
from 1 CREATE + 1 GET in the happy case, and 2 CREATEs + 1 GET when
Strict Mode duplicated).

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

* fix(chat): live thread status + title updates were never reaching the store

Two bugs surfaced when watching the tasks panel during streaming:

1. Wrong SSE event-type namespace. The server-side factories in
   @decocms/mesh-sdk emit `decopilot.thread.status` (and friends) — NO
   `com.deco.` prefix on the wire. ThreadManagerStore was subscribing
   with `?types=com.deco.decopilot.thread.*` and looking for events
   under that same prefix in handleFrame, so every live status event
   was filtered out by the hub before it ever reached the manager. The
   thread row stayed pinned to whatever status it had at snapshot time
   ("Done" if completed, stuck if mid-run). Also flipped the server-
   side snapshot probe (`THREAD_SNAPSHOT_PROBE_TYPE`) so it still
   matches the new client wildcard.

2. Title updates have no `/events` path. The auto-titler emits a
   `data-thread-title` chunk on the per-thread `/stream` SSE, not as
   an org-wide CloudEvent. Task 17 dropped the legacy onData → patch
   wiring assuming the manager would pick it up via `/events` — but
   `decopilot.thread.title` doesn't exist as an event type. Restored
   the patch via a new `manager.patchThread(patch)` local-only mutator
   and an `onData` handler in chat-context's ThreadObserver.

Manager + server tests updated to match the new event prefix.

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

* fix(chat): user-ask Submit button is now Next until every item is answered

The user-ask form rendered "Submit" immediately on mount, only disabling
it until all items were answered. With multiple questions that's the
wrong affordance — there's no way to advance to question 2 without
hunting for the pagination dots.

PaginatedFormSubmitButton now labels itself "Next" while any item is
unanswered and "Submit" once every item has an answer. The "Next" form
advances to the next unanswered item; "Submit" flushes the batch. Both
routes flow through `submitOrAdvance` from useMultiPartDecisionForm,
which already had the right pivot logic — the button was just not
exposing it.

Approval form (`approval.tsx`) is unchanged: it has no explicit Submit
button — each Deny/Accept click dispatches `submitOrAdvance` directly,
so answering the last pending approval commits the batch immediately.

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

* fix(tasks-panel): refresh relative timestamps on a 30s heartbeat

`formatTimeAgo(new Date(task.updated_at))` runs on every render — but
with referentially-stable `task` props the React compiler memoizes the
row, so the displayed string froze once the data settled. Result: "3m
ago" stayed "3m ago" until something else forced a re-render (a status
event, a new thread, etc), then jumped to "12m ago" all at once.

Introduces `useClockTick(intervalMs = 30_000)`, a tiny
useSyncExternalStore-backed singleton heartbeat. TaskRow subscribes,
which forces a re-render every 30 seconds — independent of whether the
underlying task object changed. Singleton timer per interval: subscribers
share one setInterval, started on the first mount and torn down when the
last unmounts, so no leaked timer after the panel unmounts.

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

* fix(tasks-panel): bump heartbeat from 30s to 60s

60s matches the resolution of formatTimeAgo's "Xm ago" output — finer
ticks just wake the panel for no visible change.

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

* chore(chat): remove dead exports flagged by knip

CI knip pass surfaced 7 unused exports + 1 unused file left behind by
the chat data-layer refactor:

  - apps/mesh/src/web/components/chat/task/helpers.ts — last importer
    was the deleted thread-actions.ts.
  - hooks.tsx: useThreadStatus / useActiveThread / useThreadMessages /
    useThreadConnStatus / useFinishReason — built as the "complete"
    public hook surface but never consumed (chat-context still goes
    through getOrOpenStream + useStore directly).
  - thread-connection.ts: getActiveConn — last caller was the deleted
    ThreadEventsBridge.
  - task/types.ts: TASK_CONSTANTS — legacy pagination/staletime
    constants from the React-Query era, no consumers after the store
    migration.

hooks.test.ts trimmed to the one block that still exercises a live
hook (useThreads).

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

* fix(chat): coerce TextInput value to "" to stop uncontrolled→controlled warning

The user-ask form's TextInput spreads `{...field}` from react-hook-form's
Controller. When new question parts arrive mid-stream the form's
defaultValues recomputes with new keys, but react-hook-form doesn't auto-
reset; for the new path `field.value` is briefly `undefined` until the
next render. React warns when an input flips from uncontrolled
(`value={undefined}`) to controlled (`value="..."`).

Coerce to `""` on read so the input stays controlled from the first
render. Same pattern ChoiceInput's draft `<input>` already uses
(`value={isCustomActive ? draftValue : ""}`).

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

* refactor(api): rename GET /api/:org/events → /watch

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

* docs: update SSE consumer comments to reference /watch

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

* docs(use-ensure-task): update /events references to /watch

* feat(sdk): enrich DecopilotThreadStatusEvent with title/branch/created_at/updated_at

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

* feat(run-reactor): pass thread row metadata through thread.status events

Extends all four createDecopilotThreadStatusEvent call sites in run-reactor.ts
to include title, branch, created_at, and updated_at from the loaded thread row,
enabling the client to hydrate its store without a separate fetch.

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

* feat(decopilot): emit thread.status after auto-titler commits

After the auto-titler writes the new title to the DB, broadcast a
decopilot.thread.status SSE event via sseHub so other tabs / sessions
not subscribed to the per-thread /stream see the updated title.

- Adds optional `sseHub` to `DispatchRunDeps` (and `ThreadGateRuntime.deps`)
- Builds `onTitleUpdated` callback in `prepareRun` that loads the thread
  row (best-effort) and calls `sseHub.emit` with `createDecopilotThreadStatusEvent`
- Adds `onTitleUpdated?` to `HarnessProcessLocal` and `RunDecopilotStreamExtras`
- `decopilot/index.ts` forwards `pl.onTitleUpdated` to `runDecopilotStream`
- `run-stream.ts` awaits `onTitleUpdated?.(title)` inside the titleOp `.then`
  (best-effort: errors are caught and logged without breaking the run)
- Wires `sseHub` into `setThreadGateRuntime` and the orphan-recovery
  `dispatchRunAndWait` call in `app.ts`
- Adds 4 unit tests covering: happy path with full row enrichment,
  storage failure fallback, correct org-id routing, and optionality of
  the field

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

* refactor(decopilot): extract onTitleUpdated builder so tests exercise it directly

Move the inline onTitleUpdated closure from prepareRun() into an exported
buildOnTitleUpdated() in on-title-updated.ts, then import it in both
dispatch-run.ts (production) and on-title-updated.test.ts (tests) so
the tests exercise the real code path instead of a local copy.

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

* feat(chat-store): synthesize enriched rows from thread.status events

Extract title, branch, created_at, and updated_at from thread.status
event payloads so synthetic rows avoid "New chat" zombie titles and carry
accurate timestamps when the server emits a fully-enriched event.

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

* feat(chat-store): paginate threads via COLLECTION_THREADS_LIST + buffer boot events

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

* refactor(watch): remove thread snapshot frame from connect

Clients now use COLLECTION_THREADS_LIST for initial state; the snapshot
frame on /watch connect is dead code. Drops THREAD_SNAPSHOT_PROBE_TYPE,
shouldEmitThreadSnapshot, normalizeThreadForResponse usage, and the
matchesAnyPattern import from app.ts. Updates watch.test.ts to assert
the connected frame is emitted and no snapshot is sent.

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

* refactor(chat-store): drop snapshot frame handling — MCP page-0 owns initial load

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

* feat(tasks-panel): restore infinite scroll via fetchNextPage

Expands useThreads() to surface hasMore, isFetchingMore, and
fetchNextPage from the manager store, and wires those props into
TasksSection's existing useInfiniteScroll sentinel.

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

* refactor(chat-context): expose activeTask directly; drop dead tasks-array surface

Replace filterThreads({ virtualMcpId }) array with a direct allThreads.find(id)
lookup, expose activeTask on ChatTaskContextValue, and remove the tasks array
that was never enumerated by any consumer.

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

* refactor(thread-filter): drop unused virtualMcpId dimension

* fix(chat-context-panel): consume activeTask instead of tasks-array find

Missed consumer in Task 10's chat-context refactor.

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

* fix(chat-store): resync on /watch reconnect; isolate threadsStatus from watch errors

- C2: Remove all threadsStatus writes from runWatchLoop — threadsStatus
  now reflects only the MCP page-0 load result; transient /watch HTTP
  failures backoff silently without regressing the UI to an error banner.
- C1: Track firstConnect in runWatchLoop; on every subsequent successful
  reconnect re-arm eventBuffer and re-fire loadInitialPage so events
  missed during the disconnect window are recovered via a fresh page-0.
- I3: Add fetchNextPage concurrency no-op test.
- Step 8: Add reconnect resync integration test.

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

* fix(chat-store): fetchThread for off-page direct-links; emit row status in titler

Add manager.fetchThread() that checks local list first then falls back to
COLLECTION_THREADS_GET, preventing spurious CREATE calls on deep links to
threads past page 0 or archived threads. Update useEnsureTask to use
fetch-then-create flow. Fix buildOnTitleUpdated to emit row?.status rather
than hardcoded in_progress so completed threads don't regress on the client.

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

* refactor(chat): migrate cached readers to ThreadManagerStore

- readCachedTaskBranch / readCachedLastThread now read from the manager
  singleton via getManager() instead of the legacy KEYS.threadsPrefix
  React Query cache (which is no longer populated by any writer).
- Call sites in useNavigateToAgentThread, usePanelActions,
  useChatMainPanelState, and agents-section pass (orgSlug, locator)
  instead of (queryClient, locator).
- useTaskMetadata subscribes to manager.threads via useSyncExternalStore;
  prefers localHit's metadata over the suspense-query fallback so a
  stale-null cache entry can't pin metadata for a freshly-created task.
- Drop dead KEYS.threadsPrefix entry now that no helper uses it.
- Test for readCachedLastThread rewritten to seed the manager directly.

Closes review findings #2 (cached readers return null in practice) and
\#5 (useTaskMetadata race after manager.create).

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

* chore(sse-hub): unexport matchesAnyPattern — only caller is in-file

Caller in app.ts (shouldEmitThreadSnapshot) was removed with the snapshot
frame in commit 8572782. Knip flagged the export as dead; revert to
file-local visibility.

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

* style(sse-hub): collapse matchesAnyPattern signature per Biome line-width

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

* fix(tasks-panel): lift active-row scrollIntoView out of TaskRow

The per-row effect ran on every row mount and was effectively coupled to
the list's identity. fetchNextPage's append re-rendered (and in some
cases re-mounted) the active row, re-firing scrollIntoView and yanking
the user's scroll position back to the active task — fighting them mid-scroll.

Move the autofocus + scrollIntoView to TasksSection, keyed on
activeTaskId only. The active row is located via [data-task-id=...]
inside the scroll container. Effect fires exactly once per selection
change; list growth no longer triggers it.

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

* fix(tasks-panel): scrollIntoView block: nearest (was start)

"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]>

* feat(decopilot): /stream is now a pure live tail (drop message snapshot)

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.

* refactor(decopilot): drop vestigial messages fixture from /stream test factory

makeStreamApp no longer takes a messages array — the handler no longer
calls listMessages, so the mock just records call count and returns empty.

* feat(chat-store): add mergeAndSort helper for paginated message merging

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

* fix(chat-store): mergeAndSort treats numeric epoch-0 created_at as valid

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]>

* feat(chat-store): thread MCP client through ThreadConnection constructor

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]>

* fix(chat-store): silence TS6133 on unused _client + forward client through 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.

* feat(chat-store): client-owned initial-page load + chunk buffering

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]>

* fix(chat-store): forward orderBy to COLLECTION_THREAD_MESSAGES_LIST + 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]>

* refactor(chat-store): drop dead 'event: snapshot' handling

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.

* docs(chat-store): update messages field doc — seeded from MCP, not snapshot

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

* feat(chat-store): refetch latest page on every SSE reconnect

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.

* feat(chat-store): fetchOlderMessages for infinite scroll-up

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.

* feat(chat): expose hasMoreOlder/isFetchingOlder/fetchOlderMessages via useChatStream

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

* feat(chat-ui): infinite scroll-up via top sentinel + scroll-anchor delta

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.

* style(chat-ui): use h-px utility for top sentinel (was inline style)

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

* refactor(chat): stabilize fetchOlderMessages ref + unexport unused type

- 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]>

* refactor(chat-store): hoist extractToolErrorMessage to shared mcp-utils

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]>

* test(thread): COLLECTION_THREAD_MESSAGES_LIST orderBy → sort translation

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]>

* fix(chat-store): order messages by top-level created_at, not metadata

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]>

* feat(chat): suspend the chat panel during initial-page MCP fetch

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]>

* fix(lint): suppress ban-ref-current-assignment on slash-mention bridge

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]>

* refactor(chat-watch): share /watch via decopilot SSE pool

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]>

* fix(chat): bottom-anchor scroll on completed-thread open

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]>

* fix(ensure-task): wait for fetchThread before firing CREATE

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]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
guitavano added a commit that referenced this pull request Jul 31, 2026
…tokens, dedup enqueue

P1:
- #4 double-enqueue race: per-(task,reviewer,cycle) claim table
  (INSERT ... ON CONFLICT DO NOTHING) gates each reviewer so a
  concurrent/duplicate trigger enqueues a reviewer at most once per cycle.
- #5 reviewer identity forgery: each claim mints a reviewToken bound to the
  reviewer; TASK_BOARD_REVIEW_DECISION marks a decision `verified` only when
  the token resolves to a claim whose reviewer matches. Auto-merge gate
  requires every enabled reviewer's latest verdict to be a VERIFIED approve,
  so one agent can't forge the two-reviewer sign-off.

P2:
- #6 tests: shared review-cycle reducer + verifiedOnly anti-forgery gate,
  checks-status parsing/preview-host, reviewer re-review cycle.
- #7 duplication: extract enqueueAgentRunForTask (thread create + link +
  persist-before-dispatch + enqueue) shared by the Super Agent and reviewer
  enqueues; reuse StudioContextFactory instead of a local copy.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
guitavano added a commit that referenced this pull request Jul 31, 2026
…roduction (#5520)

* feat(task-board): QA Agent + Code Reviewer review flow with ship-to-production

Add two per-org automated reviewers that run on a task's PR once the Super
Agent finishes, gated by org flags, plus a manual "ship to production" merge.

- Reviewers: QA Agent (verifies the task solved the problem) and Code Reviewer
  (reviews the code with the repo's stack review skills). Enabled per-org via
  `qa_agent_enabled` / `code_reviewer_enabled` flags; both run as linked threads
  shown live on the card, delegated by the Super Agent.
- Trigger is headless: fires from the projector's run-terminal hook when a
  Super Agent run finishes (no UI required); the modal's poll is a safety net.
- Decision via `TASK_BOARD_REVIEW_DECISION` (request_changes hands back to the
  Super Agent with feedback + `gh pr checkout` to update the same PR; approve
  records the sign-off). Auto-merge (`auto_merge` flag) merges once every enabled
  reviewer approves; a manual "Ship to production" button + merge tool otherwise.
- Merge is gated on CI: never ships on failing/pending checks (client + server).
- PR card: live state, an expandable checks footer (Status API + Checks API,
  with each failing check's output markdown), and the deco deploy preview link
  (lifted from the deploy bot's PR comment). Concurrent GitHub reads + a
  loading skeleton.
- Dev: dispatch defaults the sandbox target to the env-configured provider so
  background runs work under `--local-sandbox-provider`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(task-board): review-cycle re-review + preview-host injection + org-scoped merge conn

Address blockers/important findings from the branch review:
- Re-review never re-ran the reviewers: the thread-finish backstop advanced a
  task to In Review without recording a `status_changed` activity, so the
  reviewer cycle boundary (`lastInReviewAt`) went stale after a request_changes
  fix pushed to the same PR. Record the transition so reviewers re-run.
- Preview-host match was an unanchored substring on attacker-writable PR-comment
  URLs (phishing button + a URL the autonomous QA agent opens). Replace with a
  strict hostname check (`isDecoPreviewHost`).
- `resolveGithubConnection` resolved a linked connectionId without an org filter
  on a PR-merge (write) path — org-scope the lookup.
- Add unit tests: `isDecoPreviewHost` (incl. the decoy), `reviewerHandledThisCycle`
  (incl. the re-review prior-cycle case).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(task-board): harden review flow — anti-race claims, anti-forgery tokens, dedup enqueue

P1:
- #4 double-enqueue race: per-(task,reviewer,cycle) claim table
  (INSERT ... ON CONFLICT DO NOTHING) gates each reviewer so a
  concurrent/duplicate trigger enqueues a reviewer at most once per cycle.
- #5 reviewer identity forgery: each claim mints a reviewToken bound to the
  reviewer; TASK_BOARD_REVIEW_DECISION marks a decision `verified` only when
  the token resolves to a claim whose reviewer matches. Auto-merge gate
  requires every enabled reviewer's latest verdict to be a VERIFIED approve,
  so one agent can't forge the two-reviewer sign-off.

P2:
- #6 tests: shared review-cycle reducer + verifiedOnly anti-forgery gate,
  checks-status parsing/preview-host, reviewer re-review cycle.
- #7 duplication: extract enqueueAgentRunForTask (thread create + link +
  persist-before-dispatch + enqueue) shared by the Super Agent and reviewer
  enqueues; reuse StudioContextFactory instead of a local copy.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(task-board): add TASK_BOARD_REVIEW_DECISION to Task Manager tools integration assertion

The studio-pack integration test pinned the Task Manager's selected_tools
without TASK_BOARD_REVIEW_DECISION, which the review flow added to the
manager. Align the expected list with the source (task-manager.ts) and the
unit test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
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.

2 participants