Repository navigation
chore: add agents - #2
Merged
Merged
Conversation
4 tasks
Merged
viktormarinho
added a commit
that referenced
this pull request
Mar 27, 2026
1. JsonFileStorage.load(): only treat ENOENT as empty state, rethrow parse errors and permission failures instead of silently swallowing 2. trigger-callback: reject empty type strings with z.string().min(1) KV stringify issue (#2) is not valid — Kysely+PG requires JSON.stringify for jsonb column inserts, matching the codebase convention. Co-Authored-By: Claude Opus 4.6 <[email protected]>
viktormarinho
added a commit
that referenced
this pull request
Mar 27, 2026
…time SDK (#2844) * feat(automations): add event trigger support with callback system and runtime SDK Add end-to-end event-based trigger support for automations: - UI: event trigger form with connection selector, event type picker, and params - Backend: callback token system (SHA-256 hashed) for secure MCP-to-Mesh delivery - API: POST /api/trigger-callback endpoint for external MCPs to fire automations - Binding: callbackUrl/callbackToken fields on TRIGGER_CONFIGURE schema - Runtime: createTriggers() SDK helper so MCPs can implement triggers declaratively Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: address review issues in trigger callback system - Extract enum values from z.enum() params in createTriggers paramsSchema - Don't delete connection-level callback credentials on single trigger disable - Use Hono bodyLimit middleware instead of client-controlled content-length check - Atomic upsert (onConflict) for token rotation instead of DELETE+INSERT - Validate callbackUrl as URL, reject empty callbackToken in binding schema - Register migration 052 in migrations/index.ts - Bump test delays to 50ms to avoid flaky fire-and-forget assertions Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: make token lifecycle atomic with TRIGGER_CONFIGURE and log non-2xx callbacks 1. configure-trigger: generate token pair without persisting, call TRIGGER_CONFIGURE, then persist hash only on success. On disable, delete token only after MCP confirms. Prevents zombie tokens on failure in either direction. 2. trigger-callback-tokens: split createOrRotateToken into generateTokenPair() + persistTokenHash() for two-phase creation. 3. runtime notify(): check response.ok and log non-2xx status codes instead of silently swallowing them. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(ui): isolate event trigger loading states from SettingsTab - Wrap EventTriggerForm in Suspense boundary so useConnections({ binding: "TRIGGER" }) doesn't suspend the entire automation detail page - Show inline loading spinner inside the event type select instead of disabling the whole select - Move useConnections out of TriggerCard into SettingsTab and pass connectionName as a prop to avoid per-card suspense Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: persist token hash on TRIGGER_CONFIGURE timeout Timeout is ambiguous — the MCP may still accept the token after Promise.race gives up. Persist the hash on timeout so future callbacks can authenticate. On definitive (non-timeout) rejection, skip persistence since the MCP never received the token and the old one (if any) remains valid. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(runtime): clean up callback credentials when last trigger is disabled Track active trigger types per connection. When a trigger is disabled, remove it from the set. When the set is empty (no more active triggers), delete the callback credentials so notify() stops sending callbacks. This prevents wasteful POSTs to Mesh after all triggers for a connection are disabled, and avoids noisy 401 errors in logs. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(runtime): add TriggerStorage interface for persisting trigger state Add optional `storage` parameter to `createTriggers()` so MCPs can persist callback credentials and active trigger types across restarts. API is backwards compatible — array form still works: createTriggers([...]) // in-memory only createTriggers({ definitions, storage }) // with persistence TriggerStorage interface has get/set/delete keyed by connectionId. On notify(), the SDK checks in-memory cache first, then falls back to async storage load. State is persisted on every enable/disable and cleaned up from storage when the last trigger is disabled. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: add org-scoped KV store with StudioKV and JsonFileStorage Mesh side: - Migration 059: kv table (org_id + key composite PK, JSONB value) - KyselyKVStorage: get/set/delete with atomic upsert - HTTP routes: GET/PUT/DELETE /api/kv/:key (auth via API key, org from session) Runtime side: - StudioKV: TriggerStorage backed by Mesh's KV API (for production MCPs) - JsonFileStorage: TriggerStorage backed by a local JSON file (for dev) - Exported from @decocms/runtime/trigger-storage Usage: import { StudioKV } from "@decocms/runtime/trigger-storage"; const triggers = createTriggers({ definitions: [...], storage: new StudioKV({ url: process.env.MESH_URL, apiKey: process.env.MESH_API_KEY, }), }); Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor: use Zod schema for trigger-callback body validation Replace manual typeof checks with TriggerCallbackBodySchema.safeParse() per CLAUDE.md convention: "Use Zod for runtime validation." Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(runtime): load persisted state before disable to clear stale credentials After a restart, disable() found nothing in memory and skipped storage cleanup. Now loads from storage first, so disabling a trigger after restart properly clears persisted credentials. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: don't fail trigger creation if token persistence throws after MCP confirms Once TRIGGER_CONFIGURE succeeds, the MCP is listening. If the subsequent DB write (persistTokenHash/deleteByConnection) throws, log the error but still return success so the caller creates the trigger record. Prevents orphaned triggers on the MCP with no matching record in Mesh. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: JsonFileStorage error handling and empty type validation 1. JsonFileStorage.load(): only treat ENOENT as empty state, rethrow parse errors and permission failures instead of silently swallowing 2. trigger-callback: reject empty type strings with z.string().min(1) KV stringify issue (#2) is not valid — Kysely+PG requires JSON.stringify for jsonb column inserts, matching the codebase convention. Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
viktormarinho
added a commit
that referenced
this pull request
May 7, 2026
Address review on PR #3307: #1 — The previous override only patched `credentialId` and `thinking.id`, leaving stale `capabilities` / `limits` / `provider` / `title` from the saved snapshot. Downstream code (`ensureModelCompatibility`, the max-output-tokens cap, telemetry, prompt headers) consumes those fields, so a tier whose live slot pointed to a different model would get gated against the wrong capability set. Replace the patch with a typed `TierOverride` produced by `resolveTierOverride`, which fetches the full `ModelInfo` via `ctx.aiProviders.listModels` and translates it into the `thinking` shape — same translation as the chat path's `toMetadataModelInfo`. Falls back to a slot-only override (with stored title) if the provider call throws, so a flaky provider doesn't block the run. #2 — Saving any edit on a Simple-Mode-enabled legacy automation (e.g. just renaming it) used to silently write `tier: "smart"` because `tierToPersist` fell back to the dropdown's display fallback. After that, the run path would override the user's original snapshot model with the org's live "smart" slot. Only auto-pin when `slotMatchedTier` is truthy — i.e. the saved credential/model actually correspond to a configured slot. Legacy automations with no slot match stay unpinned on incidental saves; the user has to explicitly pick a tier via the dropdown to opt in. Tests: split build-stream-request tests into "tier override" (verifies full thinking replacement) and add a new resolve-tier-override.test.ts that exercises ModelInfo translation, the disabled / unset / no-tier short-circuits, and the listModels-throws fallback. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
viktormarinho
added a commit
that referenced
this pull request
May 7, 2026
* feat(automations): resolve simple-mode tier at run time
Stop baking the resolved model into the automation row. When the user
saves with Simple Mode enabled, persist a `tier` intent ("fast" /
"smart" / "thinking") inside `automation.models`; `buildStreamRequest`
then looks up the live tier slot from `organization_settings.simple_mode`
and uses that instead of the stored credentialId / thinking.id snapshot.
Effects:
- Dormant automations now pick up org Simple Mode changes the next time
they fire — no UI visit needed to reconcile.
- The detail page derives the dropdown label from `models.tier` first
(truthful even after a slot reconfig), falling back to slot-match for
legacy automations.
- The form clears `tier` whenever the user explicitly picks via the
ModelSelector fallback, so an explicit override beats the tier intent.
- Legacy automations (no tier persisted) keep using the stored snapshot
until next save, at which point Simple Mode is enabled they get pinned
to the matched / default tier.
Tests cover the four resolution paths (override, simple-mode disabled,
tier slot unset, no tier on legacy row).
This builds on the UI work merged in #3305 — that PR aligned the model
selector with the chat input but kept baking the resolved model into the
row, so dormant automations stayed stale until someone opened them.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* fix(automations): refresh full thinking metadata + safer auto-pin
Address review on PR #3307:
#1 — The previous override only patched `credentialId` and `thinking.id`,
leaving stale `capabilities` / `limits` / `provider` / `title` from the
saved snapshot. Downstream code (`ensureModelCompatibility`, the
max-output-tokens cap, telemetry, prompt headers) consumes those fields,
so a tier whose live slot pointed to a different model would get gated
against the wrong capability set. Replace the patch with a typed
`TierOverride` produced by `resolveTierOverride`, which fetches the full
`ModelInfo` via `ctx.aiProviders.listModels` and translates it into the
`thinking` shape — same translation as the chat path's
`toMetadataModelInfo`. Falls back to a slot-only override (with stored
title) if the provider call throws, so a flaky provider doesn't block
the run.
#2 — Saving any edit on a Simple-Mode-enabled legacy automation (e.g.
just renaming it) used to silently write `tier: "smart"` because
`tierToPersist` fell back to the dropdown's display fallback. After
that, the run path would override the user's original snapshot model
with the org's live "smart" slot. Only auto-pin when `slotMatchedTier`
is truthy — i.e. the saved credential/model actually correspond to a
configured slot. Legacy automations with no slot match stay unpinned
on incidental saves; the user has to explicitly pick a tier via the
dropdown to opt in.
Tests: split build-stream-request tests into "tier override" (verifies
full thinking replacement) and add a new resolve-tier-override.test.ts
that exercises ModelInfo translation, the disabled / unset / no-tier
short-circuits, and the listModels-throws fallback.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* docs(automations): clarify tier snapshot fallback role
Co-Authored-By: Claude Opus 4.7 <[email protected]>
* fix(settings): persist Simple Mode toggle on first enable
The autosave gated on `formState.isDirty`, but RHF's dirty flag was
cleared before the 250ms debounce fired:
- `handleToggle` calls `form.reset(...)` to seed default tier slots,
which rebases the dirty baseline (even with keepDirty: true, fields
that weren't already dirty stay clean).
- `useForm({ values: simpleMode })` re-syncs whenever the React Query
cache emits a new object reference, which `useSimpleMode`'s select
does on every render.
By the time the timer fired, `isDirty` was false and `save` bailed,
so the mutation never ran and the row was never inserted. First-time
toggle-on on a fresh org silently no-op'd.
Drop the isDirty gate. Each `schedule()` call is the explicit save
intent — only user actions call it, and nothing inside `save`
re-schedules, so there's no feedback loop.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This was referenced May 14, 2026
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]>
tlgimenes
added a commit
that referenced
this pull request
Jun 4, 2026
…riendly) The previous attempt invoked the deco bin straight from the workflow YAML (`./node_modules/.bin/deco --version`), which knip's "unlisted binaries" check flagged because knip scans workflow `run:` blocks for bare binary names and doesn't know `deco` comes from the package we're publishing. Per the repo's "never silence knip" policy, hide the bin behind a TS shim — same pattern as the existing scripts/smoke-link.ts. The shim still runs the bin, just via `bun run scripts/smoke-tarball.ts`, which knip is happy with. Catches the #2.393.0 failure exactly the same way: ESM bundle's top-level imports execute eagerly on load, so a missing external still crashes before --version prints. Co-Authored-By: Claude Opus 4.7 <[email protected]>
tlgimenes
added a commit
that referenced
this pull request
Jun 4, 2026
…ked tarball (#3683) * fix(bundler): force-include every OTel devDep so nft doesn't drop them decocms 2.393.0 shipped with @opentelemetry/sdk-metrics missing from dist/server/node_modules/, so every consumer crashed at startup with: Cannot find module '@opentelemetry/sdk-metrics' from /app/apps/mesh/node_modules/decocms/dist/server/cli.js Root cause: `bun build --target bun` auto-externalizes every node_modules import, and the bundler relies on @vercel/nft to trace + copy the package files into dist/server/node_modules/. OTel v2 packages use conditional exports + lazy requires that nft can't follow statically. When nft drops one, the bundle still emits `from "@opentelemetry/..."` for it, and the published cli.js can't resolve it at startup. The existing ALWAYS_INCLUDE entry for @opentelemetry/resources was already the manual escape hatch for one such failure. Extending it to every OTel package the runtime imports closes the same hole for the rest. Adds verifyBundlesShipExternals() that runs at the end of the build and fails it if any ALWAYS_INCLUDE entry didn't make it to disk, or if any external @opentelemetry/* import in the bundles has no shipped package. Scoped to @opentelemetry/* via STRICT_SHIPPING_PREFIXES so it doesn't false-positive on consumer-installed deps like pg / react / node-fetch that resolve via decocms's runtime dependencies tree. Co-Authored-By: Claude Opus 4.7 <[email protected]> * ci(release-mesh): smoke-test packed tarball before publishing Backstop for the decocms 2.393.0 incident — install the just-packed tarball into a scratch dir exactly the way a consumer would (`bun add decocms@<ver>`), then `bun cli.js --version`. Because bun emits ESM `from "pkg"` for externals, loading cli.js eagerly resolves every top-level external before --version ever prints — a missing one (e.g. nft dropped an OTel package) crashes here with "Cannot find module …". The static-side defense in apps/mesh/scripts/bundle-server-script.ts (verifyBundlesShipExternals) catches the same failure at build time without npm publish in the picture. This step is the publish-time backstop that also catches failure modes the static check can't (files-field stripping, prepublishOnly side-effects, signing weirdness). Runs after `npm pack`, before `upload-artifact` — a failure stops the mesh-package artifact from being produced, so publish-npm and build-docker never see the bad bytes. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(event-bus): remove unused SubscriptionEntity export * fix(bundler): drop transitive-only ALWAYS_INCLUDE entries; scope verifier to direct-resolvable strict deps The first pass at the OTel ship-everything fix listed transitive-only packages (context-async-hooks, otlp-exporter-base, otlp-transformer, semantic-conventions) in ALWAYS_INCLUDE. Bun's isolated install puts those under node_modules/.bun/<pkg>@<ver>/... and only surfaces direct deps at apps/mesh/node_modules/, so Bun.resolveSync() — which is how the bundler turns ALWAYS_INCLUDE entries into nft entry points — couldn't find them and failed the build: ❌ Failed to resolve @opentelemetry/context-async-hooks: error: Cannot find module '@opentelemetry/context-async-hooks' from '…/apps/mesh' Direct deps only. Transitives get picked up by nft as it walks from the direct entries — verified by inspecting the 2.393.0 tarball, which shipped context-async-hooks and otlp-exporter-base despite neither being direct deps. The runtime-resolution check (next paragraph) catches any @opentelemetry/* package the bundle references but doesn't ship, so demoting an entry from ALWAYS_INCLUDE to transitive isn't a silent regression vector. While here, narrow verifyBundlesShipExternals(): - Drop the "every ALWAYS_INCLUDE entry must be shipped" invariant. React is in ALWAYS_INCLUDE as an nft entry point but it's also a runtime `dependency`, so the consumer install brings it in and the bundler never copies it. The invariant was false for the existing code, not just for the entries I added. - Exempt runtime `dependencies` from the strict @opentelemetry/* check. @opentelemetry/core is in the runtime dependencies list, so even if it's somehow absent from dist/server/node_modules/, the consumer's install resolves it. Locally builds clean now: bun run --cwd=apps/mesh build:server prints "✅ Bundle externalization OK — every @opentelemetry/* import resolves." and dist/server/node_modules/@opentelemetry/ contains sdk-metrics, sdk-node, exporter-prometheus, instrumentation-runtime-node, plus the transitively-traced otlp-transformer and semantic-conventions. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(ci): use deco bin name for smoke test; restore eventbus/schema fmt Two follow-up fixes from the first CI run on this PR: 1. release-mesh.yaml smoke test referenced cli.js by its raw bundle path (`bun ./node_modules/decocms/dist/server/cli.js --version`), which tripped knip's "unlisted binaries" check. Use the `deco` bin name (from decocms's `bin` field in package.json) so knip can resolve the reference: `./node_modules/.bin/deco --version`. The check still runs against the same compiled file — the bin is just a renamed entry point. 2. apps/mesh/src/tools/eventbus/schema.ts had a stray double blank line introduced by an earlier commit on this branch (e6d6b4d "fix(event-bus): remove unused SubscriptionEntity export"). Local `bun run fmt` caught it; commit it so format:check in CI passes. Co-Authored-By: Claude Opus 4.7 <[email protected]> * ci(smoke): extract bin invocation to scripts/smoke-tarball.ts (knip-friendly) The previous attempt invoked the deco bin straight from the workflow YAML (`./node_modules/.bin/deco --version`), which knip's "unlisted binaries" check flagged because knip scans workflow `run:` blocks for bare binary names and doesn't know `deco` comes from the package we're publishing. Per the repo's "never silence knip" policy, hide the bin behind a TS shim — same pattern as the existing scripts/smoke-link.ts. The shim still runs the bin, just via `bun run scripts/smoke-tarball.ts`, which knip is happy with. Catches the #2.393.0 failure exactly the same way: ESM bundle's top-level imports execute eagerly on load, so a missing external still crashes before --version prints. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
7 tasks done
tlgimenes
added a commit
that referenced
this pull request
Jun 8, 2026
…st-leg republish (TDD, all gates green) Fixes #3698-follow: cluster-daemon proxy channel now tolerant of transient subscriber gaps. PART #1 — Per-slot backoff (proxy-poller.ts) - Root cause: shared errorStreak across proxy concurrency slots. One systemic error (e.g. Cloudflare 520 on the 28s long-poll) backed off BOTH slots → 1–30s zero-subscriber gap → dispatch publish to links.proxy.req.<userSub> dropped → proxy_no_first_frame 15s later. - Fix: move errorStreak into each slot(). Each slot backs off only its own failures; one recovering slot re-polls immediately while another retries, keeping ≥1 live subscriber through intermittent errors. - Test: new "per-slot backoff" test with concurrency:2 asserts seenStreaks=[0,0] not [0,1]. PART #2 — Request-leg tolerance (link-proxy-routes.ts, proxy-poller.ts) - Root cause: fire-and-forget core-NATS publish with no buffer. A single blind publish is lost if it lands in a daemon poll/backoff gap; no retry, no durability. - Fix: cluster-side bounded republish + daemon reqId dedup. (A) proxy-abort-registry.register() now returns AbortController|null; null if reqId already in-flight (duplicate delivery dedup). handleProxyRequest bails on null before try/finally, so duplicate copy doesn't unregister the original. (B) createProxyDispatch republishes RequestFrame every 1s (injectable republishIntervalMs, 0=off) until first reply frame. Stopped by markFirstFrame/cleanup/first-frame-timeout (never outlives dispatch, bounded by 15s window). Daemon dedup makes double-execution impossible (emits first frame only after upstream responds). - Tests: registry dedup test + "re-publishes...then stops" cluster test. Verification: 36 affected-test pass, 110 link tests pass, fmt/lint/typecheck clean.⚠️ Daemon caveat: proxy-abort-registry.ts marked "SHIPPED DAEMON — needs human review before merge." Small change, well-tested, but shipped in `decocms` CLI. Remaining: #3 tie proxy-readiness to claim (doc-vs-code defect), infra fix for CF 520, plus this dedup safety pattern may apply elsewhere (runAbortRegistry in thread-gate-workflow). Co-Authored-By: Claude Haiku 4.5 <[email protected]>
tlgimenes
added a commit
that referenced
this pull request
Jun 8, 2026
…st-leg republish (TDD, all gates green) (#3704) Fixes #3698-follow: cluster-daemon proxy channel now tolerant of transient subscriber gaps. PART #1 — Per-slot backoff (proxy-poller.ts) - Root cause: shared errorStreak across proxy concurrency slots. One systemic error (e.g. Cloudflare 520 on the 28s long-poll) backed off BOTH slots → 1–30s zero-subscriber gap → dispatch publish to links.proxy.req.<userSub> dropped → proxy_no_first_frame 15s later. - Fix: move errorStreak into each slot(). Each slot backs off only its own failures; one recovering slot re-polls immediately while another retries, keeping ≥1 live subscriber through intermittent errors. - Test: new "per-slot backoff" test with concurrency:2 asserts seenStreaks=[0,0] not [0,1]. PART #2 — Request-leg tolerance (link-proxy-routes.ts, proxy-poller.ts) - Root cause: fire-and-forget core-NATS publish with no buffer. A single blind publish is lost if it lands in a daemon poll/backoff gap; no retry, no durability. - Fix: cluster-side bounded republish + daemon reqId dedup. (A) proxy-abort-registry.register() now returns AbortController|null; null if reqId already in-flight (duplicate delivery dedup). handleProxyRequest bails on null before try/finally, so duplicate copy doesn't unregister the original. (B) createProxyDispatch republishes RequestFrame every 1s (injectable republishIntervalMs, 0=off) until first reply frame. Stopped by markFirstFrame/cleanup/first-frame-timeout (never outlives dispatch, bounded by 15s window). Daemon dedup makes double-execution impossible (emits first frame only after upstream responds). - Tests: registry dedup test + "re-publishes...then stops" cluster test. Verification: 36 affected-test pass, 110 link tests pass, fmt/lint/typecheck clean.⚠️ Daemon caveat: proxy-abort-registry.ts marked "SHIPPED DAEMON — needs human review before merge." Small change, well-tested, but shipped in `decocms` CLI. Remaining: #3 tie proxy-readiness to claim (doc-vs-code defect), infra fix for CF 520, plus this dedup safety pattern may apply elsewhere (runAbortRegistry in thread-gate-workflow). Co-authored-by: Claude Haiku 4.5 <[email protected]>
tlgimenes
added a commit
that referenced
this pull request
Jun 13, 2026
… plumbing Follow-up to 199117e: that commit deleted the linkForCurrentRun field but left comments and test inputs that still describe it. - resolve-provider.ts: precedence rule #2 and the closing note no longer mention linkForCurrentRun. - studio-context.ts: linkClaimRegistry doc no longer references a prepareRun that pre-populates linkForCurrentRun. - cluster-sandbox-fs.ts: short-circuit comments now mention only sandboxPreference. - resolve-provider.test.ts: drop the dead linkForCurrentRun hint from stubCtx and the one test that passed it; the path now keys solely on sandboxPreference. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
tlgimenes
added a commit
that referenced
this pull request
Jun 13, 2026
Follow-up to 41b44b8: that scrub corrected the doc-block copy of precedence rule #2 but missed the inline copy in the function body. After 199117e the `sandboxPreference === "user-desktop"` branch builds the desktop provider unconditionally (no link/claim), so "carries its link inline" was actively misleading two lines above the branch it describes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
pedrofrxncx
added a commit
that referenced
this pull request
Jun 16, 2026
…palive (#3957) UX for the 'frozen then everything at once' streaming case: #1 Waiting state: the empty pre-first-chunk window showed only a silent 'Thinking…'. Add ThinkingState — a live elapsed clock next to the typing indicator and, after 20s, a 'taking longer than usual' hint + Cancel (wired to the existing stop()/cancel run). Uses useClockTick (singleton useSyncExternalStore interval) so the threshold flips without useEffect. #4 SSE keepalive 15s -> 10s: the tightest proxy idle timeout in the path is Istio's 15s; a 15s heartbeat lands ON that boundary, so a silent model gap (slow TTFB / between-step pauses — provider-agnostic, worse with proxied/ liteLLM) can race-lose and drop the socket mid-run. The client reconnects and the tail replays the whole in-flight run as one burst (the frozen-then- burst symptom). 10s keeps a ~5s margin. #2 (surface reasoning + tool steps) needs no code: reasoning already renders via ThoughtSummary and tool calls via the per-tool part components as soon as parts stream; the only blank window is pre-first-part, which #1 now covers. Verified: tsc + oxlint clean on changed files; sse-keepalive tests pass.
viktormarinho
added a commit
that referenced
this pull request
Jun 24, 2026
#1 Inherited-public files now render a read-only "shared via a parent folder" state instead of the editable 3-way control — clicking "Org only" used to toast success while the published parent kept serving it (false confirmation). Restores the guard the old 2-way switch had. #2 Unlock rate limiter no longer trusts the spoofable leftmost X-Forwarded-For alone: prefer cf-connecting-ip / x-real-ip, and add a per-share global cap (50/5min, IP-independent) as a backstop so rotating XFF can't fully unthrottle brute-force. Per-IP cap (10/5min) stays for the normal case. #3 Password hashing/verification moved to async scrypt — scryptSync on the public, unauthenticated /unlock route blocked the event loop and serialized concurrent attempts. Callers + tests updated to await. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
viktormarinho
added a commit
that referenced
this pull request
Jun 25, 2026
* feat(org-fs): scaffold password-share columns (share_password_hash, share_secret) First step of password-protected sharing (design: .context/file-share-password-spec.md). Adds the two nullable columns the gate needs — a scrypt hash (null = fully public, set = password-gated) and a per-node secret rotated on password change to invalidate unlock cookies. Layered on read_public (link-accessible); proxy gate + UI follow after design sign-off. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(org-fs): password-protected sharing (proxy gate + 3-way share UI) Adds a third share mode on top of public sharing. The /read proxy serves an interstitial password form before content; one unlock (a signed, scoped cookie) covers the node the password sits on — a file, or a whole folder + its assets — mirroring public. Most-specific published node governs. - crypto (share-password.ts): scrypt hash/verify, per-node share_secret, HMAC unlock tokens (MESH_JWT_SECRET); rotation + expiry fail closed. - storage: derive shareMode in the DTO (hash never leaves the server), setShareMode, resolveGoverningShare (most-specific public node). - service: OrgFs.setShareMode (hash + rotate secret), resolveReadAccess (private/public/password + govPath/secret). - route: read branch (cookie check → form), POST /unlock (scrypt verify, rate-limited, sets scoped cookie), /public now takes { mode, password? }. Members bypass the prompt; non-members/anonymous get the form. Password content is never shared-cached. - middleware: carve-out so non-members can POST /unlock. - UI: ShareControls 3-way control (Org only / Public / Password) + password field; card badge gains a password (key) tier. - tests: crypto unit (7) + integration (governing resolution, inheritance, most-specific override, password-change rotation). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(org-fs): rate-limit unlock by governing node, not requested path Address review #1: a folder password is one credential for the whole subtree, so keying the brute-force limiter on the requested file path let an attacker multiply the lockout by guessing sibling sub-paths under the same share. Resolve the governing share first, then key the limiter on access.govPath. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(org-fs): harden password gate per 2nd review (3 findings) #1 Inherited-public files now render a read-only "shared via a parent folder" state instead of the editable 3-way control — clicking "Org only" used to toast success while the published parent kept serving it (false confirmation). Restores the guard the old 2-way switch had. #2 Unlock rate limiter no longer trusts the spoofable leftmost X-Forwarded-For alone: prefer cf-connecting-ip / x-real-ip, and add a per-share global cap (50/5min, IP-independent) as a backstop so rotating XFF can't fully unthrottle brute-force. Per-IP cap (10/5min) stays for the normal case. #3 Password hashing/verification moved to async scrypt — scryptSync on the public, unauthenticated /unlock route blocked the event loop and serialized concurrent attempts. Callers + tests updated to await. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
viktormarinho
added a commit
that referenced
this pull request
Jun 26, 2026
- #1: stamp catalog items with the Deco Store well-known source id so connections.tsx's `_registryId` registry filter and source badges keep working under the single catalog (proper filter removal lands in a later phase, with the rest of the per-registry machinery). - #2: the catalog is live by default (REGISTRY_CATALOG_URL has a default), so fix the app.ts / settings comments that claimed it "ships dark when unset". - #3: drop the now-unused registry-utils helpers (inferRegistryListToolName, isWellKnownRegistry, flattenPaginatedItems, extractItemsFromResponse, callRegistryTool) left dangling by the REST migration — keeps knip green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
tlgimenes
added a commit
that referenced
this pull request
Jul 27, 2026
macOS stamps `com.apple.provenance` on every file and directory a non-App-Store process creates. NFS advertises no native xattrs, so the kernel spills it into a 4096-byte `._<name>` AppleDouble sidecar for every file AND every directory the agent writes. The merged filter accepted those writes (201) and answered reads with 404. rclone re-reads an object right after uploading it to confirm the write, so that combination put it in an unbounded retry loop — measured against a real mount: ERROR : adtest3/._h.txt: Failed to copy: object not found ERROR : vfs cache: failed to upload try #1, will retry in 2s ERROR : vfs cache: failed to upload try #2, will retry in 4s … try #4, will retry in 16s — never converging The file stays pinned in rclone's VFS upload queue and the ERROR noise buries real failures. `--exclude "._*"` does not help: it hides them from listings but rclone uploads them anyway. So the sidecars now round-trip through a bounded in-memory store — writes recorded, reads served, deletes forgotten — while still never reaching ORG_FS and still being omitted from directory listings. The test that encoded the 404 behavior is inverted rather than appended to. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
tlgimenes
added a commit
that referenced
this pull request
Jul 27, 2026
macOS stamps `com.apple.provenance` on every file and directory a non-App-Store process creates. NFS advertises no native xattrs, so the kernel spills it into a 4096-byte `._<name>` AppleDouble sidecar for every file AND every directory the agent writes. The merged filter accepted those writes (201) and answered reads with 404. rclone re-reads an object right after uploading it to confirm the write, so that combination put it in an unbounded retry loop — measured against a real mount: ERROR : adtest3/._h.txt: Failed to copy: object not found ERROR : vfs cache: failed to upload try #1, will retry in 2s ERROR : vfs cache: failed to upload try #2, will retry in 4s … try #4, will retry in 16s — never converging The file stays pinned in rclone's VFS upload queue and the ERROR noise buries real failures. `--exclude "._*"` does not help: it hides them from listings but rclone uploads them anyway. So the sidecars now round-trip through a bounded in-memory store — writes recorded, reads served, deletes forgotten — while still never reaching ORG_FS and still being omitted from directory listings. The test that encoded the 404 behavior is inverted rather than appended to. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This was referenced Aug 2, 2026
pedrofrxncx
added a commit
that referenced
this pull request
Sep 14, 2026
…exists (#7187) The + New instance option only lives inside SiblingInstanceSelector, which was hidden whenever a connection had fewer than 2 siblings of the same app. That meant the very first connection of an app could never spawn a second instance from the UI — the control that creates instance #2 only appeared after instance #2 already existed. Keep the selector mounted with a single sibling when onNewInstance is available, so + New instance stays reachable from the first connection.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
migrate agents to here