feat(ai-orchestration): generator-based workflows + orchestrators #542
main fromworktree-cryptic-singing-wadler·opened View on GitHubSummary#
- New
@tanstack/ai-orchestrationpackage: define agents, workflows, and orchestrators using async generators.yield* agents.x(...)for typed agent calls,yield* approve(...)for pause/resume on user decision, plain JS for everything else (if,for,await,Promise.all). defineOrchestratoris sugar overdefineWorkflow(same runtime, different vocabulary).defineRouter(config, fn)lets users extract the orchestrator router as a named function with full type inference.- All workflow lifecycle is emitted as native AG-UI events (
RunStarted,StepStarted/Finished,StateSnapshot,StateDeltavia JSON Patch RFC 6902,RunFinishedcarrying typed output,RunError). Approvals reuse the existingapproval-requestedcustom event. WorkflowClientadded to@tanstack/ai-client(mirrorsChatClient's connection-adapter pattern),useWorkflow/useOrchestrationhooks added to@tanstack/ai-react.- Server-side
parseWorkflowRequest(request)extractor; consumers userunWorkflow({ workflow, runStore, ...params })+toServerSentEventsResponse(stream)— symmetric with howchat()is called. - Pluggable
RunStoreinterface with defaultinMemoryRunStore(1h TTL). - Two demo pages on
ts-react-chat:/workflow(article writing pipeline with writer → legal → skeptic → editor → approve/revise loop, dramatic fullscreen ArticleModal on publish) and/orchestration(Claude Code-style spec → approve → implement [nested workflow] → review). - Editorial-brutalist UI: Fraunces variable serif + JetBrains Mono, warm ink/cream palette with citron accent, paper-grain textures, hazard-tape approval bands, live
DraftPreviewrendering the article-in-progress as the editor mutates state.
Architecture decisions captured during design#
- Workflow body is an async generator (
function*), not a node-array DSL — preserves "feels like JavaScript". - State lives in a declared schema, mutated as a plain object inside the generator; engine snapshots between yields and emits JSON Patches.
succeed({...})/fail(reason)helpers replaceas constdiscriminator casts at return sites.- v1
runStoreis in-memory only; engine uses live generator handles (no replay) for resume. Pluggable interface in place for future durable stores.
Out of scope (post-prototype)#
- Comprehensive test suite (3 engine smoke tests included; full coverage deferred per the prototype-first direction)
- Full API docs
- Streaming structured output integration (waits on a separate in-flight chat() PR)
- Abort signal plumbing through API routes (engine supports it; route handlers no-op for now)
parallel/loop/step/askprimitives- Dedicated devtools workflow panel (events render in the existing iteration timeline)
Test plan#
- `pnpm --filter @tanstack/ai-orchestration test:lib` — 3 smoke tests pass
- `pnpm --filter @tanstack/ai-orchestration build` — builds clean
- `pnpm --filter @tanstack/ai-orchestration test:types` — clean
- `pnpm --filter @tanstack/ai-orchestration test:eslint` — clean
- `pnpm --filter @tanstack/ai-client test:types` and `@tanstack/ai-react test:types` — clean
- In the example app (`pnpm --filter ts-react-chat dev`):
- Open `/workflow`, click Run with default topic — writer → legal → skeptic → editor steps stream live in the timeline rail; `DraftPreview` populates and refreshes
- Approve the published-article approval card → modal opens with the full typeset article (esc / backdrop closes it)
- Click Revise with feedback in the textarea → editor re-runs (visible in timeline + DraftPreview), approval prompts again
- Open `/orchestration`, click Run — triage routes through spec → await-approval → implementation sub-workflow (nested steps appear under their parent) → review
- Verify `State Snapshot` paper card on the right reflects `STATE_DELTA` updates as the workflow progresses
Summary by CodeRabbit#
Release Notes#
New Features
- Added
@tanstack/ai-orchestrationfor multi-step LLM workflows with typed agents and router-based orchestration - Added
useWorkflowanduseOrchestrationReact hooks for client-side workflow management - Added human approval/feedback loops, run persistence, and refinement capabilities
- Added article workflow and feature orchestration examples in demo app with terminal UI
- Added
Documentation
- Comprehensive guides for workflows, orchestrators, approvals, and run persistence
- Added API reference and integration examples
Tests
- Full test coverage for orchestration engine, run store, and client behavior
- 1
🚀 Changeset Version Preview#
7 package(s) bumped directly, 24 bumped as dependents.
🟥 Major bumps#
Package Version Reason @tanstack/ai-preact0.6.35 → 1.0.0 Changeset @tanstack/ai-react0.12.1 → 1.0.0 Changeset @tanstack/ai-solid0.10.10 → 1.0.0 Changeset @tanstack/ai-svelte0.10.10 → 1.0.0 Changeset @tanstack/ai-vue0.10.11 → 1.0.0 Changeset @tanstack/ai-anthropic0.11.0 → 1.0.0 Dependent @tanstack/ai-code-mode0.1.22 → 1.0.0 Dependent @tanstack/ai-code-mode-skills0.1.22 → 1.0.0 Dependent @tanstack/ai-elevenlabs0.2.13 → 1.0.0 Dependent @tanstack/ai-event-client0.4.0 → 1.0.0 Dependent @tanstack/ai-fal0.7.15 → 1.0.0 Dependent @tanstack/ai-gemini0.12.0 → 1.0.0 Dependent @tanstack/ai-grok0.9.0 → 1.0.0 Dependent @tanstack/ai-groq0.2.7 → 1.0.0 Dependent @tanstack/ai-isolate-node0.1.22 → 1.0.0 Dependent @tanstack/ai-isolate-quickjs0.1.22 → 1.0.0 Dependent @tanstack/ai-ollama0.6.22 → 1.0.0 Dependent @tanstack/ai-openai0.10.3 → 1.0.0 Dependent @tanstack/ai-openrouter0.9.8 → 1.0.0 Dependent @tanstack/ai-orchestration0.0.1 → 1.0.0 Dependent @tanstack/ai-react-ui0.8.3 → 1.0.0 Dependent @tanstack/ai-solid-ui0.7.3 → 1.0.0 Dependent @tanstack/openai-base0.4.0 → 1.0.0 Dependent 🟨 Minor bumps#
Package Version Reason @tanstack/ai0.22.1 → 0.23.0 Changeset @tanstack/ai-client0.13.0 → 0.14.0 Changeset 🟩 Patch bumps#
Package Version Reason @tanstack/ai-devtools-core0.4.0 → 0.4.1 Dependent @tanstack/ai-isolate-cloudflare0.2.13 → 0.2.14 Dependent @tanstack/ai-vue-ui0.2.6 → 0.2.7 Dependent @tanstack/preact-ai-devtools0.1.43 → 0.1.44 Dependent @tanstack/react-ai-devtools0.2.43 → 0.2.44 Dependent @tanstack/solid-ai-devtools0.2.43 → 0.2.44 Dependent View your CI Pipeline Execution ↗ for commit 9de8cfa591236d225f425226d819e8fda99ea53e
Command Status Duration Result nx run-many --targets=build --exclude=examples/...✅ Succeeded 1m 12s View ↗
☁️ Nx Cloud last updated this comment at
2026-05-28 19:01:45UTC@tanstack/ai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@542@tanstack/ai-anthropic
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@542@tanstack/ai-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@542@tanstack/ai-code-mode
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode@542@tanstack/ai-code-mode-skills
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode-skills@542@tanstack/ai-devtools-core
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@542@tanstack/ai-elevenlabs
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-elevenlabs@542@tanstack/ai-event-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-event-client@542@tanstack/ai-fal
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-fal@542@tanstack/ai-gemini
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@542@tanstack/ai-grok
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@542@tanstack/ai-groq
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-groq@542@tanstack/ai-isolate-cloudflare
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-cloudflare@542@tanstack/ai-isolate-node
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-node@542@tanstack/ai-isolate-quickjs
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-quickjs@542@tanstack/ai-ollama
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@542@tanstack/ai-openai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@542@tanstack/ai-openrouter
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@542@tanstack/ai-orchestration
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-orchestration@542@tanstack/ai-preact
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@542@tanstack/ai-react
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@542@tanstack/ai-react-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@542@tanstack/ai-solid
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@542@tanstack/ai-solid-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@542@tanstack/ai-svelte
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@542@tanstack/ai-utils
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-utils@542@tanstack/ai-vue
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@542@tanstack/ai-vue-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@542@tanstack/openai-base
npm i https://pkg.pr.new/TanStack/ai/@tanstack/openai-base@542@tanstack/preact-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@542@tanstack/react-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@542@tanstack/solid-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@542commit:
9de8cfaActionable comments posted: 15
🧹 Nitpick comments (14)
examples/ts-react-chat/src/components/DraftPreview.tsx (1)
55-58: ⚡ Quick winAvoid remounting the preview container on every update.
Using
key={bumpKey}remounts the scrollable panel each time content changes, which can reset scroll position/focus during streaming updates.Suggested direction
- <div - key={bumpKey} - className="relative px-6 py-7 max-h-[34rem] overflow-auto anim-log-in" - > + <div + className="relative px-6 py-7 max-h-[34rem] overflow-auto anim-log-in" + data-bump={bumpKey} + >Then trigger pulse via CSS/animation based on
data-bump(or a short-livedisPulsingclass), without remounting the node.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/components/DraftPreview.tsx` around lines 55 - 58, The preview container in DraftPreview currently uses key={bumpKey} which forces a remount and resets scroll/focus; remove the dynamic key and instead add a stable root element (the existing div with className "relative px-6 py-7...") and toggle a data attribute or short-lived CSS class (e.g. data-bump={bumpKey} or isPulsing) on that same div to trigger the pulse animation via CSS/animation, ensuring you update where bumpKey is produced so it sets the attribute/class rather than the key.examples/ts-react-chat/src/components/ArticleModal.tsx (1)
10-21: ⚡ Quick winRefine useEffect dependencies to prevent unnecessary re-runs.
The effect depends on the entire
propsobject, which will cause the keyboard listener and scroll lock to be re-registered whenever the props object identity changes—even if only unrelated props likearticlechange. Since the effect only usesprops.onClose, specify that in the dependency array instead.♻️ Proposed fix
document.body.style.overflow = prev } - }, [props]) + }, [props.onClose])🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/components/ArticleModal.tsx` around lines 10 - 21, The useEffect in ArticleModal registers a keydown listener and toggles body overflow but incorrectly depends on the entire props object, causing unnecessary re-runs; change the dependency array to only include the specific callback used (props.onClose) by referencing the onKey handler and the effect that sets document.body.style.overflow so the listener and scroll lock are only re-registered when props.onClose changes.packages/typescript/ai-orchestration/src/primitives/bind-agents.ts (1)
13-41: 💤 Low valueOptional: collapse the two branches by building the descriptor inline.
The two
function*definitions differ only in thekinddiscriminator and theagent/workflowpayload field. A single closure that switches ondef.__kindreads about as clearly and removes duplicated descriptor wiring if this evolves (e.g., adds tracing fields).♻️ Possible consolidation
for (const [name, def] of Object.entries(agents)) { - if (def.__kind === 'agent') { - bound[name] = function* ( - input: unknown, - ): Generator<StepDescriptor, unknown, unknown> { - const descriptor: StepDescriptor = { - kind: 'agent', - name, - input, - agent: def, - } - const result = yield descriptor - return result - } - } else { - bound[name] = function* ( - input: unknown, - ): Generator<StepDescriptor, unknown, unknown> { - const descriptor: StepDescriptor = { - kind: 'nested-workflow', - name, - input, - workflow: def, - } - const result = yield descriptor - return result - } - } + bound[name] = function* ( + input: unknown, + ): Generator<StepDescriptor, unknown, unknown> { + const descriptor: StepDescriptor = + def.__kind === 'agent' + ? { kind: 'agent', name, input, agent: def } + : { kind: 'nested-workflow', name, input, workflow: def } + return yield descriptor + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/primitives/bind-agents.ts` around lines 13 - 41, The two generator functions for entries of agents and nested workflows duplicate descriptor construction; refactor the loop that builds bound[name] so a single generator closure creates a StepDescriptor with common fields (kind, name, input) and then sets the specific payload field based on def.__kind (e.g., set descriptor.agent = def for 'agent' or descriptor.workflow = def for 'nested-workflow'), yield the descriptor and return the result; update references to StepDescriptor, agents, bound, and def.__kind in that single generator to remove the duplicated function bodies.packages/typescript/ai-orchestration/src/server/parse-request.ts (1)
9-14: 💤 Low valueDead
abortfield onRawBody.abortis declared on the parsed body shape but never returned fromparseWorkflowRequest, andWorkflowRequestParamshas no place to forward it. Since abort plumbing is explicitly out of scope for this PR, consider dropping the field fromRawBodyuntil it's wired up, so the parser shape doesn't advertise a capability it doesn't deliver.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/server/parse-request.ts` around lines 9 - 14, RawBody currently includes an unused abort?: boolean field which isn't propagated by parseWorkflowRequest and isn't represented on WorkflowRequestParams; remove abort from the RawBody interface to avoid advertising an unsupported capability, update any related types/usages that reference RawBody (e.g., the RawBody declaration in parse-request.ts) and run type checks to ensure no consumers relied on that field.packages/typescript/ai-orchestration/src/run-store/in-memory.ts (1)
26-26: 💤 Low valuePrefer a runtime-agnostic timer type.
NodeJS.Timeoutadds a dependency on@types/nodefor this utility. UseReturnType<typeof setTimeout>instead, which works uniformly across Node, browsers, and Workers without environment-specific type imports.♻️ Proposed change
- const expirations = new Map<string, NodeJS.Timeout>() + const expirations = new Map<string, ReturnType<typeof setTimeout>>()🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts` at line 26, The Map declaration uses NodeJS.Timeout which ties the code to `@types/node`; change the type to a runtime-agnostic one by replacing NodeJS.Timeout with ReturnType<typeof setTimeout> in the declaration of expirations (the const expirations = new Map<string, ...>()), and ensure any places that read/clear timers (e.g., where clearTimeout is called) continue to accept that type without importing Node types.packages/typescript/ai-orchestration/src/engine/invoke-agent.ts (2)
42-47: 💤 Low valueShape detection is positional — a small
incheck on shape (c) is OK but worth a comment.'stream' in result && 'output' in resultaccepts any object with those keys. The case is narrow (Promises don't have them, async iterables don't either), but a one-line comment noting that ordering matters (shape (c) before (a) before (b)) would help future maintainers who add a new shape.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/engine/invoke-agent.ts` around lines 42 - 47, The shape detection in the result handling block (the `'stream' in result && 'output' in result` check inside invoke-agent.ts that returns { stream: filterInnerRunBoundaries(result.stream), output: result.output.then((o) => parseOutput<T>(agent, o)) }) relies on positional checks and intentionally accepts any object with those keys; add a concise one-line comment immediately above this if explaining that this is a narrow, positional shape check (shape (c)) and must remain ordered before the other shape branches (shape (a) then (b)) so future maintainers understand the rationale and don’t reorder or replace the check.
148-155: 💤 Low valueMinor: hoist
SchemaValidationErrorabove its usage.The class is declared at the bottom but referenced at lines 30 and 122. Works at runtime (calls happen after module init), but conventional ordering improves readability and avoids any future
no-use-before-definelint trips.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/engine/invoke-agent.ts` around lines 148 - 155, Move the exported SchemaValidationError class declaration above any code that constructs or references it so its definition precedes its usages; locate the places in this module where new SchemaValidationError(...) is thrown/checked (the earlier references in the same file) and cut-paste the class block to the top of the file (keeping export class SchemaValidationError ... unchanged) so lint rules like no-use-before-define no longer flag the symbol.packages/typescript/ai-orchestration/src/primitives/retry.ts (1)
14-29: 💤 Low valueOptional: jitter for
exponentialbackoff.For the documented use (retrying agent calls that often hit shared upstream rate limits), unjittered exponential delays cause synchronized retry storms across concurrent runs. Adding ±20% jitter is trivial and standard.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/primitives/retry.ts` around lines 14 - 29, The exponential backoff should include jitter to avoid synchronized retry storms: update computeDelay (the exponential branch) to compute the base exponential delay as currently done (using base and attempt), then apply ±20% random jitter (e.g., multiply by a random factor in [0.8, 1.2]), clamp the final value to <= maxDelayMs and >= 0 and return it (rounded to an integer if desired); keep the existing behavior for the 'none' and 'linear' branches and keep delay(ms: number): Promise<void> as-is.packages/typescript/ai-orchestration/src/engine/state-diff.ts (1)
18-20: 💤 Low valuestructuredClonerequires Node ≥ 17 / modern browsers. Consider adding a one-line note about the Node version requirement to the package'senginesfield or README, since it's not currently documented.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/engine/state-diff.ts` around lines 18 - 20, The function snapshotState uses structuredClone which requires Node >=17 / modern browsers; update the package metadata to document this requirement by adding an engines entry (e.g., Node >=17) in this package's package.json and/or add a one-line note to the README mentioning that snapshotState (structuredClone) needs Node ≥17 or a modern browser runtime; reference the snapshotState function and structuredClone in your change so reviewers can see the compatibility note tied to the implementation.packages/typescript/ai-orchestration/src/engine/emit-events.ts (1)
9-122: 💤 Low valueType-safety opportunity: helpers can return specific event types instead of generic
StreamChunkcasts.All event helper functions currently use
as StreamChunkcasts that bypass TypeScript's structural validation. Since all event types (RunStartedEvent,RunFinishedEvent,StepStartedEvent, etc.) are already exported from@tanstack/aiand are members of theAGUIEventunion (whichStreamChunkaliases), you can improve type safety by having each helper return its specific event type instead. This lets TypeScript validate the payload shape at construction without the cast:export function runStartedEvent(args: { runId: string threadId?: string }): RunStartedEvent { // instead of StreamChunk return { type: 'RUN_STARTED', timestamp: Date.now(), runId: args.runId, threadId: args.threadId ?? args.runId, } }The return type is still compatible with
StreamChunkvia the union, so callers see no difference. This catches any future misalignment between the payload and AG-UI's event schemas at the source.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/engine/emit-events.ts` around lines 9 - 122, Change each helper to return its specific AG-UI event type (e.g. runStartedEvent -> RunStartedEvent, runFinishedEvent -> RunFinishedEvent, runErrorEvent -> RunErrorEvent, stepStartedEvent -> StepStartedEvent, stepFinishedEvent -> StepFinishedEvent, stateSnapshotEvent -> StateSnapshotEvent, stateDeltaEvent -> StateDeltaEvent, customEvent -> CustomEvent) instead of the generic StreamChunk and remove the trailing "as StreamChunk" casts; import those concrete types from `@tanstack/ai` so TypeScript validates the payload shape at construction (leave approvalRequestedEvent returning customEvent as-is since it delegates to customEvent). Ensure signatures and returned object shapes match the imported types.packages/typescript/ai-orchestration/tests/engine.smoke.test.ts (1)
98-145: ⚡ Quick winConsider adding a resume smoke test alongside the pause assertion.
The pause behavior is well-covered, but the symmetric path — calling
runWorkflow({ workflow, runId, approval, runStore })after the pause and assertingSTEP_FINISHED(approval)plusRUN_FINISHEDwith the expected output — is the more failure-prone half of approval handling (state restore,pendingApprovalStepIdfinalization, generator.next seed value). A second assertion block on the samestorewould lock that contract.🧪 Sketch
// after the pause assertions: const events2: Array<unknown> = [] for await (const c of runWorkflow({ workflow: wf as any, runId: runStarted.runId, approval: { approved: true }, runStore: store, })) { events2.push(c) } const types2 = events2.map((e) => (e as { type: string }).type) expect(types2).toContain('STEP_FINISHED') expect(types2).toContain('RUN_FINISHED') const finished = events2.find( (e) => (e as { type: string }).type === 'RUN_FINISHED', ) as { output: { ok: boolean } } expect(finished.output).toEqual({ ok: true })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/tests/engine.smoke.test.ts` around lines 98 - 145, Add a symmetric resume smoke test after the existing pause assertions in the 'pauses on approval — stream ends after approval-requested, RUN_FINISHED not emitted' test: call runWorkflow again with the same workflow (wf), runId (from runStarted.runId), approval payload (e.g., { approved: true }) and the same runStore (store), collect emitted events into a new array (events2), then assert that events2 includes STEP_FINISHED and RUN_FINISHED and that the RUN_FINISHED event's output equals the expected { ok: true }; this verifies state restore, pendingApproval finalization, and the generator.next seed value are handled correctly.examples/ts-react-chat/src/routes/api.orchestration.ts (1)
10-10: 💤 Low valueConsider extracting the TTL constant for clarity.
The TTL is specified inline as
60 * 60 * 1000. Consider extracting this to a named constant for improved readability and maintainability.♻️ Suggested refactor
+const RUN_STORE_TTL_MS = 60 * 60 * 1000 // 1 hour + -const runStore = inMemoryRunStore({ ttl: 60 * 60 * 1000 }) +const runStore = inMemoryRunStore({ ttl: RUN_STORE_TTL_MS })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/routes/api.orchestration.ts` at line 10, The inline TTL literal passed to inMemoryRunStore (60 * 60 * 1000) reduces readability; extract it to a named constant (e.g., RUN_STORE_TTL_MS) near the top of the module and use that constant when constructing runStore so the purpose and units are clear; update any related comments or usages of runStore if needed to reference the constant.packages/typescript/ai-react/src/use-workflow.ts (1)
37-40: 💤 Low valueConsider clarifying the comment about fresh values.
The comment states "Track latest options so callbacks read fresh values" but the
bodyoption is captured at client construction time (line 51) and won't reflect prop changes. Consider clarifying that only the event callbacks (onCustomEvent,onStateChange) read fresh values, while structural options likebodyandconnectionare fixed at client creation.📝 Suggested clarification
- // Track latest options so callbacks read fresh values without recreating - // the client. Mirrors useChat's pattern. + // Track latest options so event callbacks (onCustomEvent, onStateChange) + // read fresh values without recreating the client. Structural options like + // `body` and `connection` are captured at construction. Mirrors useChat's pattern. const optsRef = useRef(opts)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-react/src/use-workflow.ts` around lines 37 - 40, The comment near optsRef (where const optsRef = useRef(opts); optsRef.current = opts) is misleading because some options (like body and connection) are captured at client construction and not updated, while event callbacks do read fresh values; update the comment to state that optsRef is used so callback handlers (onCustomEvent, onStateChange) will see the latest opts via optsRef.current, but structural options such as body and connection are fixed when the client is created (refer to the client construction site where body is passed) and will not change if props update.examples/ts-react-chat/src/components/WorkflowTimeline.tsx (1)
105-109: 💤 Low valueConsider using
replaceAllfor consistent formatting.The current code uses
replace('-', ' · '), which only replaces the first occurrence. IfstepTypecontains multiple dashes (e.g., "agent-call-retry"), only the first will be replaced.♻️ Suggested fix
- {step.stepType.replace('-', ' · ')} + {step.stepType.replaceAll('-', ' · ')}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/components/WorkflowTimeline.tsx` around lines 105 - 109, The JSX rendering in WorkflowTimeline.tsx uses step.stepType.replace('-', ' · ') which only replaces the first dash; update the expression in the span rendering (the usage of step.stepType) to replace all dashes (e.g., use step.stepType.replaceAll('-', ' · ') or step.stepType.split('-').join(' · ')) so multi-dash types like "agent-call-retry" become "agent · call · retry".🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@examples/ts-react-chat/src/components/DraftPreview.tsx`: - Around line 9-11: The current cast of props.draft to Draft lets malformed payloads reach code that calls draft.paragraphs.map and crash; update the DraftPreview component to perform runtime shape checks instead of blind casting: ensure props.draft is an object and that draft.paragraphs is an Array (and optionally validate each item has the expected fields) before using .map or rendering; modify the draft initialization and any other places that access draft.paragraphs (the draft variable and the rendering logic that iterates paragraphs) to guard with Array.isArray(draft.paragraphs) (or fallback to an empty array) so .map is only called on a real array and malformed inputs are safely handled. In `@examples/ts-react-chat/src/components/WorkflowTimeline.tsx`: - Around line 175-177: FailureBlock currently asserts props.result to a specific shape without runtime checks; replace the unchecked assertion with a defensive runtime guard: implement a small type guard (e.g., isErrorLike) or inline checks that verify props.result is an object and that result.error is an object with a string message before reading result.error.message, otherwise fall back to JSON.stringify(props.result) or a generic message; update the FailureBlock logic to use that guard when deriving msg so accessing result.error?.message cannot throw or return misleading values. In `@examples/ts-react-chat/src/routes/api.orchestration.ts`: - Around line 15-23: The POST handler should guard against exceptions from parseWorkflowRequest and runWorkflow by wrapping their calls in a try/catch: call parseWorkflowRequest(...) and runWorkflow(...) inside the try, and on success return toServerSentEventsResponse(stream); in the catch block construct and return a structured error response (JSON body with an error message and appropriate status like 400 for bad input or 500 for server error) so clients get a clear failure instead of an unhandled exception; reference the POST handler, parseWorkflowRequest, runWorkflow, featureOrchestrator, runStore and toServerSentEventsResponse when making the changes. In `@packages/typescript/ai-client/src/connection-adapters.ts`: - Around line 553-558: The loop in readStreamLines/connection-adapters is yielding raw JSON.parse output (in the for-await over readStreamLines(reader, abortSignal)) without runtime validation; add Zod validation after JSON.parse: import z from 'zod', define a WorkflowSseChunkSchema (or WorkflowEventSchema) that matches the expected SSE chunk shape, then replace the raw yield with validation via WorkflowSseChunkSchema.safeParse(parsed) and only yield the validated .data (or continue on failure), logging or ignoring invalid chunks as appropriate so malformed chunks don't propagate. In `@packages/typescript/ai-client/src/workflow-client.ts`: - Around line 109-124: Wrap the async stream-handling in approve() (and the similar blocks in start() and the other approval path) with a try/catch so that any exceptions from openStream/consumeStream (or connect/iteration) update client state to reflect the failure: call this.setState({ status: 'error', error: err, pendingApproval: null }) inside the catch, then rethrow the error. Locate the stream flow in approve(), start(), and the other approval-handling code paths and apply the same pattern to ensure state is not left as 'running' when stream errors occur. - Around line 301-306: The traversal over path segments currently assumes every intermediate node exists and is an object/array, which can throw on malformed deltas; update the loop that walks segments (the code using variables segments, cursor and last) to validate at each iteration that cursor is non-null and typeof cursor === 'object' and that segments[i] exists (and is indexable) before assigning cursor = cursor[segments[i]]; if any check fails, abort/skip applying this delta (return/continue) rather than letting it throw. Apply the same defensive checks to the other similar block (the splice/delete handling around lines 317-321) so both deletion and insertion/splice paths safely ignore invalid paths instead of crashing the stream. - Around line 135-142: The stop() method currently constructs an async iterable by calling openStream(...) but never consumes it, so the abort payload is never sent; change stop to async and consume the returned async iterable from openStream({ abort: true, runId: this.clientState.runId }) (e.g., use a for-await-of loop to iterate the stream until completion or break immediately after first send) and propagate/handle any errors, then call this.setState({ status: 'aborted' })—this ensures openStream actually executes the abort request. Reference: stop(), openStream(), this.clientState.runId, this.setState(). - Around line 152-249: handleChunk currently casts incoming streaming chunks without runtime checks which can corrupt this.clientState or throw; add Zod schemas for the different chunk shapes (e.g., CUSTOM, RUN_ERROR, RUN_FINISHED, RUN_STARTED, STATE_DELTA, STATE_SNAPSHOT, STEP_FINISHED, STEP_STARTED, TEXT_MESSAGE_CONTENT) and validate each incoming chunk at the top of handleChunk before any casting or state updates (use a discriminated union on chunk.type), then reject/log invalid chunks and return early; update references in this function (handleChunk, setState, this.clientState, applyJsonPatch, WorkflowClientState) to use the validated/typed data instead of unchecked casts. In `@packages/typescript/ai-orchestration/package.json`: - Line 47: The package.json entry for the internal peer dependency "@tanstack/ai" uses "workspace:^" instead of the required internal protocol "workspace:*"; update the dependency value for "@tanstack/ai" in packages/typescript/ai-orchestration/package.json to "workspace:*" so the internal peer dependency follows the project's workspace protocol conventions. In `@packages/typescript/ai-orchestration/src/engine/invoke-agent.ts`: - Around line 52-82: The output Promise can hang if the async iterator exits early; update drain() to always settle output in a finally block: introduce a local boolean (e.g., settled = false) and move the parseOutputFromText(agent, lastTextContent) + resolveOutput(parsed) / rejectOutput(err) logic into a finally that runs after the for-await loop so output is resolved or rejected on every exit path, and guard resolveOutput/rejectOutput with the settled flag to avoid double-settling; keep the existing catch to rethrow errors but ensure it sets settled so the finally knows whether it must call resolve/reject; reference drain(), output, resolveOutput, rejectOutput, lastTextContent, parseOutputFromText and filterInnerRunBoundaries when making the change. In `@packages/typescript/ai-orchestration/src/engine/run-workflow.ts`: - Around line 332-364: The nested-workflow branch in runWorkflow currently yields nested chunks but then always emits STEP_FINISHED and continues even if the nested run errored or paused; update the nested-workflow handling (the runWorkflow call and the for-await loop over nestedIter) to mirror the agent error handler logic: when a nested chunk with type 'RUN_ERROR' is received, emit STEP_FINISHED for the step with the error content and propagate the failure into the parent (call the parent generator's throw equivalent as done in the agent handler) instead of continuing, and when an approval-related pause/approval-requested is observed, do not treat the nested step as finished—either block here or explicitly fail the nested approval at this boundary until parent-pause-on-nested-pause is supported; refer to the nested-workflow descriptor handling and the agent error handler (lines around the existing error catch that emits STEP_FINISHED and calls live.generator.throw(err)) to implement identical error/approval propagation behavior. - Around line 51-62: mergeStateDefaults currently calls workflow.stateSchema['~standard'].validate(initial) but ignores Promise results, causing async validations to be skipped and defaults/coercions lost; change mergeStateDefaults to be async, await the validate(...) call, then check the awaited result for issues (same logic as the synchronous branch) and return the coerced validated.value when present, otherwise return initial; update any callers (e.g., startRun) if needed to await mergeStateDefaults so both sync and async schema validators are handled consistently. In `@packages/typescript/ai-orchestration/src/engine/state-diff.ts`: - Around line 32-72: The diff function can emit operations with value: undefined which JSON.stringify drops; update the places that create ops (the top-level replace in diff when types disagree or arrays differ, and the per-key add in the object branch) to normalize undefined to null (or alternatively treat undefined as a remove); specifically, change the value payloads created in diff (both the replace op that uses value: next and the add op that uses value: nextObj[key]) to use a helper normalization (e.g., normalizedValue = next === undefined ? null : next) before constructing the Operation so no op is emitted with value: undefined. In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts`: - Around line 28-55: The teardown in scheduleExpiry and delete currently removes live entries but leaves LiveRun.abortController un-aborted and LiveRun.approvalResolver unresolved, leaking paused generators and pendingEvents; update scheduleExpiry (where the timeout handle is created) and delete to first retrieve the live entry from live.get(runId) and if present call abortController.abort(), reject/resolve the approvalResolver (reject with a clear Abort/Error) and clear/publish pendingEvents before deleting; also ensure the created timeout handle uses setTimeout(...).unref?.() so the TTL won't keep the Node process alive. Ensure you reference and operate on the LiveRun object obtained via live.get(runId) when implementing these changes. In `@packages/typescript/ai-orchestration/src/server/parse-request.ts`: - Around line 30-39: Replace the unsafe cast in parseWorkflowRequest by defining a Zod schema for RawBody/WorkflowRequestParams (including approval with approvalId types, input, runId) and use it to parse/validate await request.json(); on parse failure throw a 400 HTTP error (or return a clear validation error) so malformed bodies are rejected at the HTTP boundary before calling runWorkflow; update parseWorkflowRequest to return the validated, typed result from zod.parse/zod.safeParse instead of the structural cast. --- Nitpick comments: In `@examples/ts-react-chat/src/components/ArticleModal.tsx`: - Around line 10-21: The useEffect in ArticleModal registers a keydown listener and toggles body overflow but incorrectly depends on the entire props object, causing unnecessary re-runs; change the dependency array to only include the specific callback used (props.onClose) by referencing the onKey handler and the effect that sets document.body.style.overflow so the listener and scroll lock are only re-registered when props.onClose changes. In `@examples/ts-react-chat/src/components/DraftPreview.tsx`: - Around line 55-58: The preview container in DraftPreview currently uses key={bumpKey} which forces a remount and resets scroll/focus; remove the dynamic key and instead add a stable root element (the existing div with className "relative px-6 py-7...") and toggle a data attribute or short-lived CSS class (e.g. data-bump={bumpKey} or isPulsing) on that same div to trigger the pulse animation via CSS/animation, ensuring you update where bumpKey is produced so it sets the attribute/class rather than the key. In `@examples/ts-react-chat/src/components/WorkflowTimeline.tsx`: - Around line 105-109: The JSX rendering in WorkflowTimeline.tsx uses step.stepType.replace('-', ' · ') which only replaces the first dash; update the expression in the span rendering (the usage of step.stepType) to replace all dashes (e.g., use step.stepType.replaceAll('-', ' · ') or step.stepType.split('-').join(' · ')) so multi-dash types like "agent-call-retry" become "agent · call · retry". In `@examples/ts-react-chat/src/routes/api.orchestration.ts`: - Line 10: The inline TTL literal passed to inMemoryRunStore (60 * 60 * 1000) reduces readability; extract it to a named constant (e.g., RUN_STORE_TTL_MS) near the top of the module and use that constant when constructing runStore so the purpose and units are clear; update any related comments or usages of runStore if needed to reference the constant. In `@packages/typescript/ai-orchestration/src/engine/emit-events.ts`: - Around line 9-122: Change each helper to return its specific AG-UI event type (e.g. runStartedEvent -> RunStartedEvent, runFinishedEvent -> RunFinishedEvent, runErrorEvent -> RunErrorEvent, stepStartedEvent -> StepStartedEvent, stepFinishedEvent -> StepFinishedEvent, stateSnapshotEvent -> StateSnapshotEvent, stateDeltaEvent -> StateDeltaEvent, customEvent -> CustomEvent) instead of the generic StreamChunk and remove the trailing "as StreamChunk" casts; import those concrete types from `@tanstack/ai` so TypeScript validates the payload shape at construction (leave approvalRequestedEvent returning customEvent as-is since it delegates to customEvent). Ensure signatures and returned object shapes match the imported types. In `@packages/typescript/ai-orchestration/src/engine/invoke-agent.ts`: - Around line 42-47: The shape detection in the result handling block (the `'stream' in result && 'output' in result` check inside invoke-agent.ts that returns { stream: filterInnerRunBoundaries(result.stream), output: result.output.then((o) => parseOutput<T>(agent, o)) }) relies on positional checks and intentionally accepts any object with those keys; add a concise one-line comment immediately above this if explaining that this is a narrow, positional shape check (shape (c)) and must remain ordered before the other shape branches (shape (a) then (b)) so future maintainers understand the rationale and don’t reorder or replace the check. - Around line 148-155: Move the exported SchemaValidationError class declaration above any code that constructs or references it so its definition precedes its usages; locate the places in this module where new SchemaValidationError(...) is thrown/checked (the earlier references in the same file) and cut-paste the class block to the top of the file (keeping export class SchemaValidationError ... unchanged) so lint rules like no-use-before-define no longer flag the symbol. In `@packages/typescript/ai-orchestration/src/engine/state-diff.ts`: - Around line 18-20: The function snapshotState uses structuredClone which requires Node >=17 / modern browsers; update the package metadata to document this requirement by adding an engines entry (e.g., Node >=17) in this package's package.json and/or add a one-line note to the README mentioning that snapshotState (structuredClone) needs Node ≥17 or a modern browser runtime; reference the snapshotState function and structuredClone in your change so reviewers can see the compatibility note tied to the implementation. In `@packages/typescript/ai-orchestration/src/primitives/bind-agents.ts`: - Around line 13-41: The two generator functions for entries of agents and nested workflows duplicate descriptor construction; refactor the loop that builds bound[name] so a single generator closure creates a StepDescriptor with common fields (kind, name, input) and then sets the specific payload field based on def.__kind (e.g., set descriptor.agent = def for 'agent' or descriptor.workflow = def for 'nested-workflow'), yield the descriptor and return the result; update references to StepDescriptor, agents, bound, and def.__kind in that single generator to remove the duplicated function bodies. In `@packages/typescript/ai-orchestration/src/primitives/retry.ts`: - Around line 14-29: The exponential backoff should include jitter to avoid synchronized retry storms: update computeDelay (the exponential branch) to compute the base exponential delay as currently done (using base and attempt), then apply ±20% random jitter (e.g., multiply by a random factor in [0.8, 1.2]), clamp the final value to <= maxDelayMs and >= 0 and return it (rounded to an integer if desired); keep the existing behavior for the 'none' and 'linear' branches and keep delay(ms: number): Promise<void> as-is. In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts`: - Line 26: The Map declaration uses NodeJS.Timeout which ties the code to `@types/node`; change the type to a runtime-agnostic one by replacing NodeJS.Timeout with ReturnType<typeof setTimeout> in the declaration of expirations (the const expirations = new Map<string, ...>()), and ensure any places that read/clear timers (e.g., where clearTimeout is called) continue to accept that type without importing Node types. In `@packages/typescript/ai-orchestration/src/server/parse-request.ts`: - Around line 9-14: RawBody currently includes an unused abort?: boolean field which isn't propagated by parseWorkflowRequest and isn't represented on WorkflowRequestParams; remove abort from the RawBody interface to avoid advertising an unsupported capability, update any related types/usages that reference RawBody (e.g., the RawBody declaration in parse-request.ts) and run type checks to ensure no consumers relied on that field. In `@packages/typescript/ai-orchestration/tests/engine.smoke.test.ts`: - Around line 98-145: Add a symmetric resume smoke test after the existing pause assertions in the 'pauses on approval — stream ends after approval-requested, RUN_FINISHED not emitted' test: call runWorkflow again with the same workflow (wf), runId (from runStarted.runId), approval payload (e.g., { approved: true }) and the same runStore (store), collect emitted events into a new array (events2), then assert that events2 includes STEP_FINISHED and RUN_FINISHED and that the RUN_FINISHED event's output equals the expected { ok: true }; this verifies state restore, pendingApproval finalization, and the generator.next seed value are handled correctly. In `@packages/typescript/ai-react/src/use-workflow.ts`: - Around line 37-40: The comment near optsRef (where const optsRef = useRef(opts); optsRef.current = opts) is misleading because some options (like body and connection) are captured at client construction and not updated, while event callbacks do read fresh values; update the comment to state that optsRef is used so callback handlers (onCustomEvent, onStateChange) will see the latest opts via optsRef.current, but structural options such as body and connection are fixed when the client is created (refer to the client construction site where body is passed) and will not change if props update.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
eeed6f10-2679-46f2-97cf-1966e42df69f📥 Commits
Reviewing files that changed from the base of the PR and between 4a943d686160fc4f34d79a0e6a3847240003be8b and 16354b71b0312b52c6208518074a18d489b05db6.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (44)
examples/ts-react-chat/package.jsonexamples/ts-react-chat/src/components/ArticleModal.tsxexamples/ts-react-chat/src/components/DraftPreview.tsxexamples/ts-react-chat/src/components/Header.tsxexamples/ts-react-chat/src/components/StateInspector.tsxexamples/ts-react-chat/src/components/WorkflowTimeline.tsxexamples/ts-react-chat/src/lib/workflows/article-workflow.tsexamples/ts-react-chat/src/lib/workflows/orchestrator.tsexamples/ts-react-chat/src/routeTree.gen.tsexamples/ts-react-chat/src/routes/api.orchestration.tsexamples/ts-react-chat/src/routes/api.workflow.tsexamples/ts-react-chat/src/routes/orchestration.tsxexamples/ts-react-chat/src/routes/workflow.tsxexamples/ts-react-chat/src/styles.csspackages/typescript/ai-client/src/connection-adapters.tspackages/typescript/ai-client/src/index.tspackages/typescript/ai-client/src/workflow-client.tspackages/typescript/ai-orchestration/README.mdpackages/typescript/ai-orchestration/eslint.config.jspackages/typescript/ai-orchestration/package.jsonpackages/typescript/ai-orchestration/src/define/define-agent.tspackages/typescript/ai-orchestration/src/define/define-orchestrator.tspackages/typescript/ai-orchestration/src/define/define-router.tspackages/typescript/ai-orchestration/src/define/define-workflow.tspackages/typescript/ai-orchestration/src/engine/emit-events.tspackages/typescript/ai-orchestration/src/engine/invoke-agent.tspackages/typescript/ai-orchestration/src/engine/run-workflow.tspackages/typescript/ai-orchestration/src/engine/state-diff.tspackages/typescript/ai-orchestration/src/index.tspackages/typescript/ai-orchestration/src/primitives/approve.tspackages/typescript/ai-orchestration/src/primitives/bind-agents.tspackages/typescript/ai-orchestration/src/primitives/index.tspackages/typescript/ai-orchestration/src/primitives/retry.tspackages/typescript/ai-orchestration/src/result.tspackages/typescript/ai-orchestration/src/run-store/in-memory.tspackages/typescript/ai-orchestration/src/run-store/index.tspackages/typescript/ai-orchestration/src/server/index.tspackages/typescript/ai-orchestration/src/server/parse-request.tspackages/typescript/ai-orchestration/src/types.tspackages/typescript/ai-orchestration/tests/engine.smoke.test.tspackages/typescript/ai-orchestration/tsconfig.jsonpackages/typescript/ai-orchestration/vite.config.tspackages/typescript/ai-react/src/index.tspackages/typescript/ai-react/src/use-workflow.ts
examples/ts-react-chat/src/components/DraftPreview.tsx lines 9 to 11OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,11 @@1+import { useEffect, useRef, useState } from 'react'2+3+interface Draft {4+ title?: string5+ paragraphs?: Array<string>6+}7+8+export function DraftPreview(props: { draft: unknown; phase?: string }) {9+ const draft = (10+ props.draft && typeof props.draft === 'object' ? props.draft : null11+ ) as Draft | null⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Harden
draftshape validation before usingparagraphs.map.draftis only object-checked/cast, so malformed payloads (e.g.paragraphs: "text"or{}) can reach Line 77 and crash when.mapis invoked.Suggested fix
interface Draft { title?: string paragraphs?: Array<string> } export function DraftPreview(props: { draft: unknown; phase?: string }) { - const draft = ( - props.draft && typeof props.draft === 'object' ? props.draft : null - ) as Draft | null + const raw = props.draft + const draft: Draft | null = + raw && typeof raw === 'object' + ? { + title: typeof (raw as { title?: unknown }).title === 'string' + ? (raw as { title: string }).title + : undefined, + paragraphs: Array.isArray((raw as { paragraphs?: unknown }).paragraphs) + ? (raw as { paragraphs: unknown[] }).paragraphs.filter( + (p): p is string => typeof p === 'string', + ) + : undefined, + } + : nullAlso applies to: 24-26, 77-92
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/components/DraftPreview.tsx` around lines 9 - 11, The current cast of props.draft to Draft lets malformed payloads reach code that calls draft.paragraphs.map and crash; update the DraftPreview component to perform runtime shape checks instead of blind casting: ensure props.draft is an object and that draft.paragraphs is an Array (and optionally validate each item has the expected fields) before using .map or rendering; modify the draft initialization and any other places that access draft.paragraphs (the draft variable and the rendering logic that iterates paragraphs) to guard with Array.isArray(draft.paragraphs) (or fallback to an empty array) so .map is only called on a real array and malformed inputs are safely handled.✅ Addressed in commits 62bb9d6 to 04dcab8
examples/ts-react-chat/src/components/WorkflowTimeline.tsx lines 175 to 177OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +157,21 @@157+ className="text-bone leading-relaxed text-[15px]"158+ style={{159+ fontFamily: 'var(--font-display)',160+ fontVariationSettings: "'opsz' 14, 'SOFT' 100, 'WONK' 0",161+ }}162+ >163+ {text}164+ </p>165+ ) : (166+ <pre className="font-mono text-[11.5px] leading-relaxed text-taupe whitespace-pre-wrap bg-ink-soft/40 border-l border-ink-line px-3 py-2 max-h-72 overflow-auto">167+ {JSON.stringify(props.result, null, 2)}168+ </pre>169+ )}170+ </div>171+ </details>172+ )173+}174+175+function FailureBlock(props: { result: unknown }) {176+ const result = props.result as { error?: { message?: string } }177+ const msg = result.error?.message ?? JSON.stringify(props.result)⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Type assertion lacks runtime validation.
The code asserts
props.resultas{ error?: { message?: string } }without validation. If the actual error structure differs, accessingresult.error?.messagemight fail silently or produce unexpected output. Consider adding runtime validation or a more defensive check.🛡️ Suggested fix
function FailureBlock(props: { result: unknown }) { - const result = props.result as { error?: { message?: string } } - const msg = result.error?.message ?? JSON.stringify(props.result) + const msg = + typeof props.result === 'object' && + props.result !== null && + 'error' in props.result && + typeof props.result.error === 'object' && + props.result.error !== null && + 'message' in props.result.error && + typeof props.result.error.message === 'string' + ? props.result.error.message + : JSON.stringify(props.result) return (🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/components/WorkflowTimeline.tsx` around lines 175 - 177, FailureBlock currently asserts props.result to a specific shape without runtime checks; replace the unchecked assertion with a defensive runtime guard: implement a small type guard (e.g., isErrorLike) or inline checks that verify props.result is an object and that result.error is an object with a string message before reading result.error.message, otherwise fall back to JSON.stringify(props.result) or a generic message; update the FailureBlock logic to use that guard when deriving msg so accessing result.error?.message cannot throw or return misleading values.✅ Addressed in commits 62bb9d6 to 04dcab8
examples/ts-react-chat/src/routes/api.orchestration.ts lines 17 to 63Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +3,21 @@3+import {4+ inMemoryRunStore,5+ parseWorkflowRequest,6+ runWorkflow,7+} from '@tanstack/ai-orchestration'8+import { featureOrchestrator } from '@/lib/workflows/orchestrator'9+10+const runStore = inMemoryRunStore({ ttl: 60 * 60 * 1000 })11+12+export const Route = createFileRoute('/api/orchestration')({13+ server: {14+ handlers: {15+ POST: async ({ request }) => {16+ const params = await parseWorkflowRequest(request)17+ const stream = runWorkflow({18+ runStore,19+ workflow: featureOrchestrator,20+ ...params,21+ })22+ return toServerSentEventsResponse(stream)23+ },⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Add error handling for the workflow execution.
The POST handler does not wrap
parseWorkflowRequestorrunWorkflowin try/catch blocks. If either throws (e.g., malformed request body, workflow initialization failure), the server will return an unhandled error response. Consider adding error handling to return structured error responses to the client.🛡️ Proposed fix
POST: async ({ request }) => { + try { const params = await parseWorkflowRequest(request) const stream = runWorkflow({ runStore, workflow: featureOrchestrator, ...params, }) return toServerSentEventsResponse(stream) + } catch (error) { + return new Response( + JSON.stringify({ + error: error instanceof Error ? error.message : 'Unknown error' + }), + { status: 400, headers: { 'Content-Type': 'application/json' } } + ) + } },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/routes/api.orchestration.ts` around lines 15 - 23, The POST handler should guard against exceptions from parseWorkflowRequest and runWorkflow by wrapping their calls in a try/catch: call parseWorkflowRequest(...) and runWorkflow(...) inside the try, and on success return toServerSentEventsResponse(stream); in the catch block construct and return a structured error response (JSON body with an error message and appropriate status like 400 for bad input or 500 for server error) so clients get a clear failure instead of an unhandled exception; reference the POST handler, parseWorkflowRequest, runWorkflow, featureOrchestrator, runStore and toServerSentEventsResponse when making the changes.✅ Addressed in commits 62bb9d6 to 04dcab8
@@ -485,0 +538,21 @@538+ credentials: resolvedOptions.credentials ?? 'same-origin',539+ headers: requestHeaders,540+ method: 'POST',541+ signal: abortSignal ?? resolvedOptions.signal,542+ })543+544+ if (!response.ok) {545+ throw new Error(`HTTP ${response.status}: ${response.statusText}`)546+ }547+548+ const reader = response.body?.getReader()549+ if (!reader) {550+ throw new Error('Response body is not readable')551+ }552+553+ for await (const line of readStreamLines(reader, abortSignal)) {554+ const data = line.startsWith('data: ') ? line.slice(6) : line555+ if (!data) continue556+ try {557+ yield JSON.parse(data)558+ } catch {🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
cd packages/typescript/ai-client/src && wc -l connection-adapters.tsRepository: TanStack/ai
Length of output: 82
🏁 Script executed:
cd packages/typescript/ai-client/src && sed -n '540,570p' connection-adapters.ts | cat -nRepository: TanStack/ai
Length of output: 863
🏁 Script executed:
cd packages/typescript/ai-client/src && head -20 connection-adapters.ts | cat -nRepository: TanStack/ai
Length of output: 744
🏁 Script executed:
cd packages/typescript && rg "import.*zod" --type tsRepository: TanStack/ai
Length of output: 2168
🏁 Script executed:
cd packages/typescript && rg "WorkflowChunkSchema\|z\.object\|safeParse" src/ -A 2 -B 2Repository: TanStack/ai
Length of output: 100
🏁 Script executed:
cd packages/typescript/ai-client && grep -n "JSON.parse\|safeParse\|parse\|\.z\." src/connection-adapters.tsRepository: TanStack/ai
Length of output: 468
🏁 Script executed:
cd packages/typescript/ai-client && grep -n "readStreamLines\|for await" src/connection-adapters.ts | head -20Repository: TanStack/ai
Length of output: 364
🏁 Script executed:
cd packages/typescript/ai-client/src && cat -n workflow-client.ts | head -100Repository: TanStack/ai
Length of output: 3301
🏁 Script executed:
cd packages/typescript/ai-client/src && grep -n "WorkflowChunk\|StreamChunk" connection-adapters.tsRepository: TanStack/ai
Length of output: 1286
🏁 Script executed:
cd packages/typescript/ai-client && find . -name "*.ts" -exec grep -l "JSON.parse" {} \; | head -10Repository: TanStack/ai
Length of output: 162
🏁 Script executed:
cd packages/typescript/ai-client/src && sed -n '480,495p' connection-adapters.ts | cat -nRepository: TanStack/ai
Length of output: 653
🏁 Script executed:
cd packages/typescript/ai-client/src && sed -n '310,330p' connection-adapters.ts | cat -nRepository: TanStack/ai
Length of output: 914
Add Zod schema validation for workflow SSE chunks.
Line 557 yields raw JSON.parse output without runtime schema validation. Per coding guidelines for
packages/typescript/**/src/**/*.ts, Zod must be used for schema validation. This makes the workflow event handling fragile when chunks are malformed or unexpectedly shaped.Proposed fix
+import { z } from 'zod' + +const WorkflowChunkSchema = z.object({ + type: z.string(), +}).passthrough() ... for await (const line of readStreamLines(reader, abortSignal)) { const data = line.startsWith('data: ') ? line.slice(6) : line if (!data) continue try { - yield JSON.parse(data) + const parsed = WorkflowChunkSchema.safeParse(JSON.parse(data)) + if (parsed.success) { + yield parsed.data + } } catch { // skip malformed lines } }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change1104+ for await (const line of readStreamLines(reader, abortSignal)) {1105+ const data = line.startsWith('data: ') ? line.slice(6) : line1106+ if (!data) continue1107+ try {1108+ const parsed = WorkflowChunkSchema.safeParse(JSON.parse(data))1109+ if (parsed.success) {1110+ yield parsed.data1111+ }1112+ } catch {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-client/src/connection-adapters.ts` around lines 553 - 558, The loop in readStreamLines/connection-adapters is yielding raw JSON.parse output (in the for-await over readStreamLines(reader, abortSignal)) without runtime validation; add Zod validation after JSON.parse: import z from 'zod', define a WorkflowSseChunkSchema (or WorkflowEventSchema) that matches the expected SSE chunk shape, then replace the raw yield with validation via WorkflowSseChunkSchema.safeParse(parsed) and only yield the validated .data (or continue on failure), logging or ignoring invalid chunks as appropriate so malformed chunks don't propagate.packages/ai-client/src/workflow-client.ts lines 122 to 137Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +104,21 @@104+ return () => {105+ this.subscribers.delete(cb)106+ }107+ }108+109+ async approve(approved: boolean, feedback?: string): Promise<void> {110+ if (!this.clientState.pendingApproval || !this.clientState.runId) {111+ throw new Error('No pending approval')112+ }113+ const approvalId = this.clientState.pendingApproval.approvalId114+ const runId = this.clientState.runId115+ this.setState({116+ pendingApproval: null,117+ status: 'running',118+ })119+ const workflowStream = this.openStream({120+ approval: { approvalId, approved, feedback },121+ runId,122+ })123+ await this.consumeStream(workflowStream)124+ }⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Stream exceptions are not mapped into client state.
If
connect()/iteration throws,start()andapprove()reject but state can remainrunningwith noerror, which breaks UI recovery.Proposed fix
private async consumeStream(stream: AsyncIterable<unknown>): Promise<void> { - for await (const raw of stream) { - this.handleChunk(raw as Record<string, unknown>) + try { + for await (const raw of stream) { + this.handleChunk(raw as Record<string, unknown>) + } + } catch (err) { + this.setState({ + error: { + message: err instanceof Error ? err.message : 'Unknown workflow stream error', + }, + status: 'error', + }) + throw err } }Also applies to: 126-133, 146-150
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-client/src/workflow-client.ts` around lines 109 - 124, Wrap the async stream-handling in approve() (and the similar blocks in start() and the other approval path) with a try/catch so that any exceptions from openStream/consumeStream (or connect/iteration) update client state to reflect the failure: call this.setState({ status: 'error', error: err, pendingApproval: null }) inside the catch, then rethrow the error. Locate the stream flow in approve(), start(), and the other approval-handling code paths and apply the same pattern to ensure state is not left as 'running' when stream errors occur.✅ Addressed in commits 62bb9d6 to 04dcab8
packages/ai-client/src/workflow-client.ts lines 210 to 229Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +122,21 @@122+ })123+ await this.consumeStream(workflowStream)124+ }125+126+ async start(input: TInput): Promise<void> {127+ this.setState({128+ ...(initialState as WorkflowClientState<TState, TOutput>),129+ status: 'running',130+ })131+ const workflowStream = this.openStream({ input })132+ await this.consumeStream(workflowStream)133+ }134+135+ stop(): void {136+ if (!this.clientState.runId) return137+ this.openStream({138+ abort: true,139+ runId: this.clientState.runId,140+ })141+ this.setState({ status: 'aborted' })142+ }⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy lift
stop()does not actually execute the abort stream request.Line 137 creates an async iterable but never consumes it, so the abort payload is never sent. This leaves active runs effectively un-stoppable from the client path.
Proposed direction
+private activeAbortController: AbortController | null = null ... async start(input: TInput): Promise<void> { + this.activeAbortController?.abort() + const controller = new AbortController() + this.activeAbortController = controller this.setState({ ...(initialState as WorkflowClientState<TState, TOutput>), status: 'running', }) - const workflowStream = this.openStream({ input }) + const workflowStream = this.openStream({ input }, controller.signal) await this.consumeStream(workflowStream) } stop(): void { - if (!this.clientState.runId) return - this.openStream({ - abort: true, - runId: this.clientState.runId, - }) + this.activeAbortController?.abort() + this.activeAbortController = null this.setState({ status: 'aborted' }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-client/src/workflow-client.ts` around lines 135 - 142, The stop() method currently constructs an async iterable by calling openStream(...) but never consumes it, so the abort payload is never sent; change stop to async and consume the returned async iterable from openStream({ abort: true, runId: this.clientState.runId }) (e.g., use a for-await-of loop to iterate the stream until completion or break immediately after first send) and propagate/handle any errors, then call this.setState({ status: 'aborted' })—this ensures openStream actually executes the abort request. Reference: stop(), openStream(), this.clientState.runId, this.setState().✅ Addressed in commit 5486c02
@@ -0,0 +229,21 @@229+ case 'STEP_STARTED': {230+ const step: WorkflowStep = {231+ startedAt: chunk.timestamp as number,232+ status: 'running',233+ stepId: chunk.stepId as string,234+ stepName: chunk.stepName as string,235+ stepType: chunk.stepType as WorkflowStep['stepType'],236+ }237+ this.setState({238+ currentStep: step,239+ currentText: '',240+ steps: [...this.clientState.steps, step],241+ })242+ break243+ }244+ case 'TEXT_MESSAGE_CONTENT':245+ this.setState({246+ currentText: this.clientState.currentText + (chunk.delta as string),247+ })248+ break249+ }🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
# Check if the file exists and examine its structure ls -la packages/typescript/ai-client/src/ 2>/dev/null | head -20Repository: TanStack/ai
Length of output: 1038
🏁 Script executed:
# Verify Zod is in project dependencies fd package.json packages/typescript | head -3Repository: TanStack/ai
Length of output: 194
🏁 Script executed:
# Search for Zod usage in the typescript packages rg -l "zod|Zod" packages/typescript --type ts --type jsonRepository: TanStack/ai
Length of output: 3265
🏁 Script executed:
# Check ai-client package.json for dependencies cat packages/typescript/ai-client/package.jsonRepository: TanStack/ai
Length of output: 1362
🏁 Script executed:
# Read the workflow-client.ts file to understand the full context cat -n packages/typescript/ai-client/src/workflow-client.ts | head -100Repository: TanStack/ai
Length of output: 3301
🏁 Script executed:
# Check how validation/schema handling is done in similar client files cat -n packages/typescript/ai-client/src/chat-client.ts | head -150Repository: TanStack/ai
Length of output: 6752
🏁 Script executed:
# Read the handleChunk method and surrounding context in workflow-client.ts cat -n packages/typescript/ai-client/src/workflow-client.ts | sed -n '140,260p'Repository: TanStack/ai
Length of output: 4613
🏁 Script executed:
# Check the full workflow-client.ts for imports and helper functions cat -n packages/typescript/ai-client/src/workflow-client.tsRepository: TanStack/ai
Length of output: 11593
🏁 Script executed:
# Check if there are other similar chunk/event validation patterns in the ai-client package rg -A 10 "handleChunk|processChunk|validateChunk" packages/typescript/ai-client/src --type tsRepository: TanStack/ai
Length of output: 2388
🏁 Script executed:
# Check how Zod is used elsewhere in the typescript packages for event/stream validation rg -B 3 -A 5 "z\.(object|discriminatedUnion|union)" packages/typescript/ai/src --type ts | head -80Repository: TanStack/ai
Length of output: 4901
Use Zod to validate inbound workflow chunks.
handleChunkrelies on unchecked casts for externally streamed events without runtime validation. Per coding guidelines, schema validation with Zod is mandatory acrosspackages/typescript/**/src/**/*.tsfiles. A malformed chunk can corrupt state transitions or throw mid-reducer.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-client/src/workflow-client.ts` around lines 152 - 249, handleChunk currently casts incoming streaming chunks without runtime checks which can corrupt this.clientState or throw; add Zod schemas for the different chunk shapes (e.g., CUSTOM, RUN_ERROR, RUN_FINISHED, RUN_STARTED, STATE_DELTA, STATE_SNAPSHOT, STEP_FINISHED, STEP_STARTED, TEXT_MESSAGE_CONTENT) and validate each incoming chunk at the top of handleChunk before any casting or state updates (use a discriminated union on chunk.type), then reject/log invalid chunks and return early; update references in this function (handleChunk, setState, this.clientState, applyJsonPatch, WorkflowClientState) to use the validated/typed data instead of unchecked casts.packages/ai-client/src/workflow-client.ts lines 490 to 503Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +286,21 @@286+ setAt(doc, segments, op.value)287+ } else if (op.op === 'remove') {288+ removeAt(doc, segments)289+ }290+ }291+ return doc292+}293+294+function removeAt(295+ target: Record<string, unknown>,296+ segments: Array<string>,297+): void {298+ if (segments.length === 0) return299+ const last = segments[segments.length - 1]!300+ let cursor: Record<string, unknown> = target301+ for (let i = 0; i < segments.length - 1; i++) {302+ cursor = cursor[segments[i]!] as Record<string, unknown>303+ }304+ if (Array.isArray(cursor))305+ (cursor as unknown as Array<unknown>).splice(Number(last), 1)306+ else delete cursor[last]⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Patch path traversal can throw on missing intermediate nodes.
Lines 301-303 and 320 assume every path segment exists and is object-like. Invalid or out-of-order deltas can throw and terminate stream processing.
Proposed fix
for (let i = 0; i < segments.length - 1; i++) { - cursor = cursor[segments[i]!] as Record<string, unknown> + const next = cursor[segments[i]!] + if (next === null || next === undefined || typeof next !== 'object') { + return + } + cursor = next as Record<string, unknown> } ... for (let i = 0; i < segments.length - 1; i++) { const seg = segments[i]! - if (cursor[seg] === undefined) cursor[seg] = {} - cursor = cursor[seg] as Record<string, unknown> + const next = cursor[seg] + if (next === undefined || next === null || typeof next !== 'object') { + cursor[seg] = {} + } + cursor = cursor[seg] as Record<string, unknown> }Also applies to: 317-321
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-client/src/workflow-client.ts` around lines 301 - 306, The traversal over path segments currently assumes every intermediate node exists and is an object/array, which can throw on malformed deltas; update the loop that walks segments (the code using variables segments, cursor and last) to validate at each iteration that cursor is non-null and typeof cursor === 'object' and that segments[i] exists (and is indexable) before assigning cursor = cursor[segments[i]]; if any check fails, abort/skip applying this delta (return/continue) rather than letting it throw. Apply the same defensive checks to the other similar block (the splice/delete handling around lines 317-321) so both deletion and insertion/splice paths safely ignore invalid paths instead of crashing the stream.✅ Addressed in commits 62bb9d6 to e86b405
packages/typescript/ai-orchestration/package.json line 47OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +27,21 @@27+ },28+ "files": [29+ "dist",30+ "src"31+ ],32+ "scripts": {33+ "build": "vite build",34+ "clean": "premove ./build ./dist",35+ "lint:fix": "eslint ./src --fix",36+ "test:build": "publint --strict",37+ "test:coverage": "vitest run --coverage",38+ "test:eslint": "eslint ./src",39+ "test:lib": "vitest",40+ "test:lib:dev": "pnpm test:lib --watch",41+ "test:types": "tsc"42+ },43+ "dependencies": {44+ "@tanstack/ai-event-client": "workspace:*"45+ },46+ "peerDependencies": {47+ "@tanstack/ai": "workspace:^"⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Use
workspace:*protocol for internal peer dependencies.The peer dependency on
@tanstack/aiusesworkspace:^instead ofworkspace:*. As per coding guidelines, internal package dependencies should use theworkspace:*protocol consistently.📦 Proposed fix
"peerDependencies": { - "@tanstack/ai": "workspace:^" + "@tanstack/ai": "workspace:*" },As per coding guidelines: Use workspace:* protocol for internal package dependencies in package.json
📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change47- "@tanstack/ai": "workspace:^"47+ "peerDependencies": {48+ "@tanstack/ai": "workspace:*"49+ },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/package.json` at line 47, The package.json entry for the internal peer dependency "@tanstack/ai" uses "workspace:^" instead of the required internal protocol "workspace:*"; update the dependency value for "@tanstack/ai" in packages/typescript/ai-orchestration/package.json to "workspace:*" so the internal peer dependency follows the project's workspace protocol conventions.✅ Addressed in commits 62bb9d6 to 04dcab8
packages/ai-orchestration/src/engine/invoke-agent.ts lines 70 to 130Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +62,21 @@62+ for await (const chunk of filterInnerRunBoundaries(stream)) {63+ if (chunk.type === 'TEXT_MESSAGE_CONTENT' && 'delta' in chunk) {64+ lastTextContent += String((chunk as any).delta ?? '')65+ }66+ yield chunk67+ }68+ // Try to parse final text as the typed output via the agent's outputSchema.69+ try {70+ const parsed = parseOutputFromText<T>(agent, lastTextContent)71+ resolveOutput(parsed)72+ } catch (err) {73+ rejectOutput(err)74+ }75+ } catch (err) {76+ rejectOutput(err)77+ throw err78+ }79+ }80+81+ return { stream: drain(), output }82+ }⚠️ Potential issue | 🟠 Major | ⚡ Quick win
outputPromise can hang if the stream isn't fully consumed.resolveOutput/rejectOutputare only invoked at the end ofdrain()'sfor awaitloop (or in itscatch). If the engine stops iterating early — most importantly once abort plumbing lands, but also if an outer consumer breaks on the first error — the async iterator's cleanup runs without ever settlingoutput, so anyawait outputdangles forever.Settle the promise from a
finallyblock to guarantee resolution under all exit paths.🛡️ Proposed fix
async function* drain(): AsyncIterable<StreamChunk> { - let lastTextContent = '' + let accumulatedText = '' + let settled = false try { for await (const chunk of filterInnerRunBoundaries(stream)) { if (chunk.type === 'TEXT_MESSAGE_CONTENT' && 'delta' in chunk) { - lastTextContent += String((chunk as any).delta ?? '') + accumulatedText += String((chunk as any).delta ?? '') } yield chunk } - // Try to parse final text as the typed output via the agent's outputSchema. try { - const parsed = parseOutputFromText<T>(agent, lastTextContent) + const parsed = parseOutputFromText<T>(agent, accumulatedText) resolveOutput(parsed) + settled = true } catch (err) { rejectOutput(err) + settled = true } } catch (err) { rejectOutput(err) + settled = true throw err + } finally { + if (!settled) { + rejectOutput( + new Error( + `Agent "${agent.name}" stream was not fully consumed; output unavailable`, + ), + ) + } } }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change70+ async function* drain(): AsyncIterable<StreamChunk> {71+ let accumulatedText = ''72+ let settled = false73+ try {74+ for await (const chunk of filterInnerRunBoundaries(stream)) {75+ if (chunk.type === 'TEXT_MESSAGE_CONTENT' && 'delta' in chunk) {76+ accumulatedText += String((chunk as any).delta ?? '')77+ }78+ yield chunk79+ }80+ try {81+ const parsed = parseOutputFromText<T>(agent, accumulatedText)82+ resolveOutput(parsed)83+ settled = true84+ } catch (err) {85+ rejectOutput(err)86+ settled = true87+ }88+ } catch (err) {89+ rejectOutput(err)90+ settled = true91+ throw err92+ } finally {93+ if (!settled) {94+ rejectOutput(95+ new Error(96+ `Agent "${agent.name}" stream was not fully consumed; output unavailable`,97+ ),98+ )99+ }100+ }101+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/engine/invoke-agent.ts` around lines 52 - 82, The output Promise can hang if the async iterator exits early; update drain() to always settle output in a finally block: introduce a local boolean (e.g., settled = false) and move the parseOutputFromText(agent, lastTextContent) + resolveOutput(parsed) / rejectOutput(err) logic into a finally that runs after the for-await loop so output is resolved or rejected on every exit path, and guard resolveOutput/rejectOutput with the settled flag to avoid double-settling; keep the existing catch to rethrow errors but ensure it sets settled so the finally knows whether it must call resolve/reject; reference drain(), output, resolveOutput, rejectOutput, lastTextContent, parseOutputFromText and filterInnerRunBoundaries when making the change.✅ Addressed in commits 62bb9d6 to 04dcab8
packages/typescript/ai-orchestration/src/engine/run-workflow.ts lines 51 to 62OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +42,21 @@42+ outputSink?: (output: unknown) => void43+}44+45+// ----- helpers -----46+47+function generateId(prefix: string): string {48+ return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`49+}50+51+function mergeStateDefaults(52+ workflow: AnyWorkflowDefinition,53+ initial: Record<string, unknown>,54+): Record<string, unknown> {55+ if (workflow.stateSchema) {56+ const validated = workflow.stateSchema['~standard'].validate(initial)57+ if (!(validated instanceof Promise) && !validated.issues) {58+ return validated.value as Record<string, unknown>59+ }60+ }61+ return initial62+}⚠️ Potential issue | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
Standard Schema spec ~standard.validate sync vs async return type💡 Result:
In the Standard Schema v1 specification, the ~standard.validate function has a dual return type: Result<Output> | Promise<Result<Output>>. It can return either a synchronous Result object (for success with value and undefined issues, or failure with issues array) or a Promise resolving to that Result if async operations are involved [1][2][3][4]. Libraries are encouraged to prefer synchronous validation when possible, only returning Promises when necessary [1][2]. Consumers expecting only sync validation can check if the result is a Promise and throw an error if so [1][5][2]. Some libraries like Zod attempt sync first then fallback to async, potentially causing multiple calls for async schemas [6].
Citations:
- 1: https://standardschema.dev/schema
- 2: https://github.com/standard-schema/standard-schema/tree/24384111d696b8539bc8d6ac9d131c71305f7c11
- 3: https://registry.npmjs.org/@standard-schema/spec
- 4: https://github.com/standard-schema/standard-schema
- 5: https://github.com/standard-schema/standard-schema/issues/22
- 6: https://github.com/colinhacks/zod/issues/5137
🏁 Script executed:
# First, let's locate and examine the actual file and function find . -type f -name "run-workflow.ts" | head -20Repository: TanStack/ai
Length of output: 121
🏁 Script executed:
# Check the full context of the file around the mergeStateDefaults function if [ -f "packages/typescript/ai-orchestration/src/engine/run-workflow.ts" ]; then wc -l "packages/typescript/ai-orchestration/src/engine/run-workflow.ts" fiRepository: TanStack/ai
Length of output: 123
🏁 Script executed:
# Search for all occurrences of mergeStateDefaults to find call sites rg "mergeStateDefaults" --type ts --type tsx -A 3 -B 3Repository: TanStack/ai
Length of output: 83
🏁 Script executed:
# Check the complete function and surrounding context if [ -f "packages/typescript/ai-orchestration/src/engine/run-workflow.ts" ]; then cat -n "packages/typescript/ai-orchestration/src/engine/run-workflow.ts" | head -100 fiRepository: TanStack/ai
Length of output: 3825
🏁 Script executed:
# Search for mergeStateDefaults usage (fixing the ts/tsx issue) rg "mergeStateDefaults" --type ts -A 3 -B 3Repository: TanStack/ai
Length of output: 1397
🏁 Script executed:
# Get more of the file to see how mergeStateDefaults is called cat -n "packages/typescript/ai-orchestration/src/engine/run-workflow.ts" | sed -n '100,200p'Repository: TanStack/ai
Length of output: 3359
🏁 Script executed:
# Check if there are any other call sites of mergeStateDefaults rg "mergeStateDefaults" --type ts -B 5 -A 5Repository: TanStack/ai
Length of output: 2097
🏁 Script executed:
# Check if the function is exported or used anywhere else rg "mergeStateDefaults" --type tsRepository: TanStack/ai
Length of output: 248
🏁 Script executed:
# Let's also check the schema validation behavior by looking at types rg "stateSchema" --type ts -B 2 -A 2 | head -50Repository: TanStack/ai
Length of output: 1607
🏁 Script executed:
# Let's see the complete context of how state is used after mergeStateDefaults cat -n "packages/typescript/ai-orchestration/src/engine/run-workflow.ts" | sed -n '117,145p'Repository: TanStack/ai
Length of output: 1035
🏁 Script executed:
# Check if there are any type constraints that would prevent making mergeStateDefaults async rg "RunState" --type ts -A 5 -B 2 | head -40Repository: TanStack/ai
Length of output: 3542
🏁 Script executed:
# Let's verify the Standard Schema import and usage to understand the validation contract rg "~standard" --type ts -B 3 -A 3Repository: TanStack/ai
Length of output: 8437
🏁 Script executed:
# Check how stateSchema is typed rg "stateSchema" --type ts -B 3 -A 3 | head -60Repository: TanStack/ai
Length of output: 2135
🏁 Script executed:
# Let's look at the invoke-agent error handling more closely cat -n "packages/typescript/ai-orchestration/src/engine/invoke-agent.ts" | sed -n '1,100p'Repository: TanStack/ai
Length of output: 3925
🏁 Script executed:
# Check the exact error handling pattern for async validation in invoke-agent rg "Async.*schema validation not supported" --type ts -B 5 -A 2Repository: TanStack/ai
Length of output: 1719
🏁 Script executed:
# Let's check if there are any tests for mergeStateDefaults behavior rg "mergeStateDefaults" --type tsRepository: TanStack/ai
Length of output: 248
🏁 Script executed:
# Check the full parseOutput function to see how agent output handles async cat -n "packages/typescript/ai-orchestration/src/engine/invoke-agent.ts" | sed -n '115,145p'Repository: TanStack/ai
Length of output: 1238
🏁 Script executed:
# Let's check if there's any documentation or comments about why async validation is rejected rg "Async.*schema validation not supported" --type ts -B 10 -A 5 | head -80Repository: TanStack/ai
Length of output: 3248
🏁 Script executed:
# Check if there are any other schema validation patterns we should be aware of rg "\.validate\(" --type ts -B 2 -A 4 | head -100Repository: TanStack/ai
Length of output: 3562
🏁 Script executed:
# Check the schema-converter pattern for context - how it handles the Promise case cat -n "packages/typescript/ai/src/activities/chat/tools/schema-converter.ts" | sed -n '70,130p'Repository: TanStack/ai
Length of output: 2311
🏁 Script executed:
# Let's find the validateSync and async validation patterns in schema-converter rg "validateSync|validate\(" "packages/typescript/ai/src/activities/chat/tools/schema-converter.ts" -B 5 -A 8Repository: TanStack/ai
Length of output: 894
🏁 Script executed:
# Let's check what the standard practice is - look for any comments or documentation about stateSchema rg "stateSchema" --type ts -B 5 -A 5 | grep -A 10 -B 10 "comment\|//\|validation"Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
# Final check: see the complete behavior of mergeStateDefaults one more time with context cat -n "packages/typescript/ai-orchestration/src/engine/run-workflow.ts" | sed -n '45,175p'Repository: TanStack/ai
Length of output: 4683
mergeStateDefaultssilently loses schema defaults on async validation.When
workflow.stateSchema['~standard'].validate(initial)returns aPromise(which the Standard Schema spec allows for any conforming schema), the early-return branch is skipped and the function returns the unparsedinitialinstead of the schema-coerced value. The run then proceeds with state missing schema-applied defaults and coercions, silently diverging from the typedstate.The codebase establishes a clear pattern: either explicitly reject async validation (as in
invoke-agent.ts) or await it (as inschema-converter.ts).mergeStateDefaultsdoes neither. Since the call site instartRunis already async, make this function async with await to properly handle both sync and async validation paths.🛡️ Suggested fix
-function mergeStateDefaults( +async function mergeStateDefaults( workflow: AnyWorkflowDefinition, initial: Record<string, unknown>, -): Record<string, unknown> { +): Promise<Record<string, unknown>> { if (workflow.stateSchema) { - const validated = workflow.stateSchema['~standard'].validate(initial) - if (!(validated instanceof Promise) && !validated.issues) { - return validated.value as Record<string, unknown> - } + const validated = await workflow.stateSchema['~standard'].validate(initial) + if (!validated.issues) { + return validated.value as Record<string, unknown> + } } return initial }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/engine/run-workflow.ts` around lines 51 - 62, mergeStateDefaults currently calls workflow.stateSchema['~standard'].validate(initial) but ignores Promise results, causing async validations to be skipped and defaults/coercions lost; change mergeStateDefaults to be async, await the validate(...) call, then check the awaited result for issues (same logic as the synchronous branch) and return the coerced validated.value when present, otherwise return initial; update any callers (e.g., startRun) if needed to await mergeStateDefaults so both sync and async schema validators are handled consistently.✅ Addressed in commit 5486c02
packages/typescript/ai-orchestration/src/engine/run-workflow.ts lines 332 to 364OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +344,21 @@344+ signal: abortController.signal,345+ outputSink: (o) => {346+ nestedOutput = o347+ },348+ })349+350+ for await (const chunk of nestedIter) {351+ if (chunk.type === 'RUN_STARTED' || chunk.type === 'RUN_FINISHED') {352+ continue353+ }354+ yield chunk355+ }356+357+ yield stepFinishedEvent({358+ stepId,359+ stepName: descriptor.name,360+ content: nestedOutput,361+ })362+ nextValue = nestedOutput363+ continue364+ }⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Confirm there is no other site that observes nested run errors / pauses. rg -nP --type=ts -C3 "nested-workflow|nestedIter|RUN_ERROR" packages/typescript/ai-orchestrationRepository: TanStack/ai
Length of output: 5560
🏁 Script executed:
# Get the full nested-workflow section to see complete error handling sed -n '328,370p' packages/typescript/ai-orchestration/src/engine/run-workflow.tsRepository: TanStack/ai
Length of output: 1159
🏁 Script executed:
# Check what happens with RUN_ERROR chunks - do they reach the yield? rg -nP --type=ts "RUN_ERROR" packages/typescript/ai-orchestration/src/engine/run-workflow.ts -A5 -B5Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
# Look for approval handling in the file rg -nP --type=ts "approval|APPROVAL" packages/typescript/ai-orchestration/src/engine/run-workflow.ts -C3Repository: TanStack/ai
Length of output: 4097
🏁 Script executed:
# Check the StreamChunk type to see all possible chunk types rg -nP --type=ts "type StreamChunk|type.*ChunkType|STEP_FINISHED|RUN_ERROR|approval" packages/typescript/ai-orchestration/src/types.ts -A2Repository: TanStack/ai
Length of output: 732
🏁 Script executed:
# Look for error handling in the parent generator/main loop sed -n '1,330p' packages/typescript/ai-orchestration/src/engine/run-workflow.ts | tail -50Repository: TanStack/ai
Length of output: 1319
🏁 Script executed:
# Check for try-catch around the nested-workflow section sed -n '260,380p' packages/typescript/ai-orchestration/src/engine/run-workflow.ts | grep -nE "try|catch|throw|RUN_ERROR" -A2 -B2Repository: TanStack/ai
Length of output: 463
🏁 Script executed:
# See the full startRun function to understand error handling at top level sed -n '210,280p' packages/typescript/ai-orchestration/src/engine/run-workflow.tsRepository: TanStack/ai
Length of output: 2244
🏁 Script executed:
# Check StreamChunk type definition to see all event types rg -nP --type=ts "type StreamChunk|export type.*Event" packages/typescript/ai-orchestration/src/types.ts -A5 | head -100Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
# Search for StreamChunk type definition rg -nP --type=ts "export.*StreamChunk|interface StreamChunk" packages/typescript/ai-orchestration/src/ -A10Repository: TanStack/ai
Length of output: 1061
🏁 Script executed:
# Look for all the event types defined rg -nP --type=ts "RunErrorEvent|RunStartedEvent|RunFinishedEvent|ApprovalRequestedEvent" packages/typescript/ai-orchestration/src/engine/emit-events.ts -B2Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
# Get all event functions from emit-events.ts rg -nP --type=ts "^export function" packages/typescript/ai-orchestration/src/engine/emit-events.tsRepository: TanStack/ai
Length of output: 486
🏁 Script executed:
# Check the types.ts for StreamChunk union type rg -nP --type=ts "StreamChunk" packages/typescript/ai-orchestration/src/types.ts -B2 -A15 | head -80Repository: TanStack/ai
Length of output: 1527
🏁 Script executed:
# Find where StreamChunk is defined - it might be in a different package fd -t f "*.ts" packages/typescript/ | xargs rg -l "type StreamChunk|interface StreamChunk" | head -5Repository: TanStack/ai
Length of output: 533
🏁 Script executed:
# Look in the main ai package types rg -nP --type=ts "type StreamChunk|StreamChunk =" packages/typescript/ai/src/ -B2 -A20 | head -100Repository: TanStack/ai
Length of output: 3173
🏁 Script executed:
# Now let's check if RUN_ERROR in a nested-workflow properly propagates # Look at the complete nested-workflow section with full context sed -n '330,365p' packages/typescript/ai-orchestration/src/engine/run-workflow.tsRepository: TanStack/ai
Length of output: 976
🏁 Script executed:
# Check the top-level error handling in the try-catch of driveLoop sed -n '226,410p' packages/typescript/ai-orchestration/src/engine/run-workflow.ts | grep -nE "try|catch|throw|finally" -A5 -B2Repository: TanStack/ai
Length of output: 1207
🏁 Script executed:
# Look at what happens after the driveLoop completes - error handling sed -n '100,180p' packages/typescript/ai-orchestration/src/engine/run-workflow.tsRepository: TanStack/ai
Length of output: 2129
🏁 Script executed:
# See the complete catch block in driveLoop sed -n '390,430p' packages/typescript/ai-orchestration/src/engine/run-workflow.tsRepository: TanStack/ai
Length of output: 1218
🏁 Script executed:
# Check if there's any special handling for RUN_ERROR in nested context rg -nP --type=ts "chunk.type.*RUN_ERROR|RUN_ERROR.*chunk" packages/typescript/ai-orchestration/src/Repository: TanStack/ai
Length of output: 37
Nested workflow errors and approval pauses are not propagated to the parent.
The nested-workflow handler yields all chunks except
RUN_STARTED/RUN_FINISHED, but lacks error handling that agents have. When a nested run emitsRUN_ERROR, the parent yields it but then emitsSTEP_FINISHEDwithnestedOutput = undefinedand continues—the parent run is not failed or paused. Similarly, when a nested workflow yieldsapproval-requestedand returns, the parent yields the event but then continues past the nested step withSTEP_FINISHED, while the nested run remainsstatus: 'paused'in the store. This creates data flow corruption and inconsistent run state.Model the nested-workflow case after the agent error handler (lines 301–325), which catches errors, emits
STEP_FINISHEDwith error content, and callslive.generator.throw(err)to propagate the failure. HandleRUN_ERRORchunks similarly, and either block or explicitly fail nested approvals at this boundary until parent-pause-on-nested-pause is supported.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/engine/run-workflow.ts` around lines 332 - 364, The nested-workflow branch in runWorkflow currently yields nested chunks but then always emits STEP_FINISHED and continues even if the nested run errored or paused; update the nested-workflow handling (the runWorkflow call and the for-await loop over nestedIter) to mirror the agent error handler logic: when a nested chunk with type 'RUN_ERROR' is received, emit STEP_FINISHED for the step with the error content and propagate the failure into the parent (call the parent generator's throw equivalent as done in the agent handler) instead of continuing, and when an approval-related pause/approval-requested is observed, do not treat the nested step as finished—either block here or explicitly fail the nested approval at this boundary until parent-pause-on-nested-pause is supported; refer to the nested-workflow descriptor handling and the agent error handler (lines around the existing error catch that emits STEP_FINISHED and calls live.generator.throw(err)) to implement identical error/approval propagation behavior.✅ Addressed in commits 62bb9d6 to 53532dc
packages/typescript/ai-orchestration/src/engine/state-diff.ts lines 32 to 72OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +52,21 @@52+ return ops53+ }54+55+ // Both are plain objects.56+ const prevObj = prev as Record<string, unknown>57+ const nextObj = next as Record<string, unknown>58+ const ops: Array<Operation> = []59+ const allKeys = new Set([...Object.keys(prevObj), ...Object.keys(nextObj)])60+61+ for (const key of allKeys) {62+ const subPath = `${path}/${escapeJsonPointer(key)}`63+ const prevHas = Object.prototype.hasOwnProperty.call(prevObj, key)64+ const nextHas = Object.prototype.hasOwnProperty.call(nextObj, key)65+66+ if (prevHas && nextHas) {67+ ops.push(...diff(prevObj[key], nextObj[key], subPath))68+ } else if (nextHas) {69+ ops.push({ op: 'add', path: subPath, value: nextObj[key] })70+ } else {71+ ops.push({ op: 'remove', path: subPath })72+ }⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
undefinedvalues produce malformed JSON Patch ops on the wire.When
next(or a child value) isundefined, both the top-levelreplace(Line 40/46) and the per-keyadd(Line 69) emit{ op, path, value: undefined }.JSON.stringifydropsundefinedproperties, so the SSE consumer sees{ "op": "add", "path": "..." }with novalue— RFC 6902 invalid and the client applier will silently set the key toundefined(or throw, depending on the implementation).If state values can ever be
undefined, normalize tonull(or omit the key entirely and emitremoveinstead).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/engine/state-diff.ts` around lines 32 - 72, The diff function can emit operations with value: undefined which JSON.stringify drops; update the places that create ops (the top-level replace in diff when types disagree or arrays differ, and the per-key add in the object branch) to normalize undefined to null (or alternatively treat undefined as a remove); specifically, change the value payloads created in diff (both the replace op that uses value: next and the add op that uses value: nextObj[key]) to use a helper normalization (e.g., normalizedValue = next === undefined ? null : next) before constructing the Operation so no op is emitted with value: undefined.✅ Addressed in commits 62bb9d6 to 04dcab8
packages/typescript/ai-orchestration/src/run-store/in-memory.ts lines 28 to 55OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +35,21 @@35+ }, ttl)36+ expirations.set(runId, handle)37+ }38+39+ return {40+ get(runId) {41+ return Promise.resolve(runs.get(runId))42+ },43+ set(runId, state) {44+ runs.set(runId, state)45+ scheduleExpiry(runId)46+ return Promise.resolve()47+ },48+ delete(runId, _reason) {49+ runs.delete(runId)50+ live.delete(runId)51+ const handle = expirations.get(runId)52+ if (handle) clearTimeout(handle)53+ expirations.delete(runId)54+ return Promise.resolve()55+ },⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Cleanup on
delete/ TTL expiry can leave pending approvals hanging.When a run is paused at an approval step,
LiveRun.approvalResolveris a promise resolver waiting forgen.next(approvalResult). If the TTL fires (Lines 31–35) ordelete(Lines 48–55) is called while paused, the live entry is dropped but the resolver is never invoked andabortControlleris not aborted — any code awaiting that resolver, plus the underlying generator, will silently hang and leak. ThependingEventsqueue is also discarded without notice.Consider aborting the controller and rejecting the approval resolver as part of teardown so callers observe a clean failure rather than a stuck promise.
🛡️ Suggested teardown
+ function teardownLive(runId: string, reason: DeleteReason) { + const l = live.get(runId) + if (!l) return + try { + l.abortController.abort(new Error(`run ${reason}`)) + } catch {} + if (l.approvalResolver) { + // Resolve as not-approved so awaiters unblock; engine can interpret. + l.approvalResolver({ approved: false, approvalId: '', feedback: `run ${reason}` }) + } + live.delete(runId) + } + function scheduleExpiry(runId: string) { const existing = expirations.get(runId) if (existing) clearTimeout(existing) const handle = setTimeout(() => { + teardownLive(runId, 'aborted') runs.delete(runId) - live.delete(runId) expirations.delete(runId) }, ttl) expirations.set(runId, handle) } @@ - delete(runId, _reason) { + delete(runId, reason) { + teardownLive(runId, reason) runs.delete(runId) - live.delete(runId) const handle = expirations.get(runId) if (handle) clearTimeout(handle) expirations.delete(runId) return Promise.resolve() },You may also want
setTimeout(...).unref?.()so a long TTL doesn't keep a Node process alive after the request finishes.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts` around lines 28 - 55, The teardown in scheduleExpiry and delete currently removes live entries but leaves LiveRun.abortController un-aborted and LiveRun.approvalResolver unresolved, leaking paused generators and pendingEvents; update scheduleExpiry (where the timeout handle is created) and delete to first retrieve the live entry from live.get(runId) and if present call abortController.abort(), reject/resolve the approvalResolver (reject with a clear Abort/Error) and clear/publish pendingEvents before deleting; also ensure the created timeout handle uses setTimeout(...).unref?.() so the TTL won't keep the Node process alive. Ensure you reference and operate on the LiveRun object obtained via live.get(runId) when implementing these changes.✅ Addressed in commits 62bb9d6 to 04dcab8
packages/typescript/ai-orchestration/src/server/parse-request.ts lines 30 to 39OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +19,21 @@19+ * out of `request.json()`.20+ *21+ * @example22+ * ```typescript23+ * POST: async ({ request }) => {24+ * const params = await parseWorkflowRequest(request)25+ * const stream = runWorkflow({ workflow, runStore, ...params })26+ * return toServerSentEventsResponse(stream)27+ * }28+ * ```29+ */30+export async function parseWorkflowRequest(31+ request: Request,32+): Promise<WorkflowRequestParams> {33+ const body = (await request.json()) as RawBody34+ return {35+ approval: body.approval,36+ input: body.input,37+ runId: body.runId,38+ }39+}⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Validate the parsed body with Zod instead of a structural cast.
(await request.json()) as RawBodyblindly trusts the wire format — a malformedapprovalshape (e.g., missingapprovalIdor wrong types) will silently flow intorunWorkflowand only surface as obscure failures inside the engine. A small Zod schema here would give you an early, typed error at the HTTP boundary, and bring this in line with the rest of the library.🛡️ Suggested validation
-import type { ApprovalResult } from '../types' +import { z } from 'zod' +import type { ApprovalResult } from '../types' + +const approvalSchema = z.object({ + approved: z.boolean(), + approvalId: z.string(), + feedback: z.string().optional(), +}) + +const rawBodySchema = z.object({ + abort: z.boolean().optional(), + approval: approvalSchema.optional(), + input: z.unknown().optional(), + runId: z.string().optional(), +}) @@ - const body = (await request.json()) as RawBody + const body = rawBodySchema.parse(await request.json()) return { - approval: body.approval, + approval: body.approval as ApprovalResult | undefined, input: body.input, runId: body.runId, }As per coding guidelines: "Use Zod for schema validation and tool definition across the library".
📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change30-export async function parseWorkflowRequest(31- request: Request,32-): Promise<WorkflowRequestParams> {33- const body = (await request.json()) as RawBody34- return {35- approval: body.approval,36- input: body.input,37- runId: body.runId,38- }39-}30+import { z } from 'zod'31+import type { ApprovalResult } from '../types'32+33+const approvalSchema = z.object({34+ approved: z.boolean(),35+ approvalId: z.string(),36+ feedback: z.string().optional(),37+})38+39+const rawBodySchema = z.object({40+ abort: z.boolean().optional(),41+ approval: approvalSchema.optional(),42+ input: z.unknown().optional(),43+ runId: z.string().optional(),44+})45+46+export async function parseWorkflowRequest(47+ request: Request,48+): Promise<WorkflowRequestParams> {49+ const body = rawBodySchema.parse(await request.json())50+ return {51+ approval: body.approval as ApprovalResult | undefined,52+ input: body.input,53+ runId: body.runId,54+ }55+}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/server/parse-request.ts` around lines 30 - 39, Replace the unsafe cast in parseWorkflowRequest by defining a Zod schema for RawBody/WorkflowRequestParams (including approval with approvalId types, input, runId) and use it to parse/validate await request.json(); on parse failure throw a 400 HTTP error (or return a clear validation error) so malformed bodies are rejected at the HTTP boundary before calling runWorkflow; update parseWorkflowRequest to return the validated, typed result from zod.parse/zod.safeParse instead of the structural cast.✅ Addressed in commits 62bb9d6 to 53532dc
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
examples/ts-react-chat/src/routes/api.workflow.ts (1)
16-28: ⚠️ Potential issue | 🟠 Major | ⚡ Quick winAdd structured error handling around request parsing and run startup.
parseWorkflowRequestandrunWorkflowcan throw; without a guard this route returns unstructured failures and drops client context.Suggested minimal fix
POST: async ({ request }) => { - const params = await parseWorkflowRequest(request) - if (params.abort && params.runId) { - runStore.getLive(params.runId)?.abortController.abort() - return new Response(null, { status: 204 }) - } - const stream = runWorkflow({ - runStore, - workflow: articleWorkflow, - ...params, - }) - return toServerSentEventsResponse(stream) + try { + const params = await parseWorkflowRequest(request) + if (params.abort && params.runId) { + runStore.getLive(params.runId)?.abortController.abort() + return new Response(null, { status: 204 }) + } + const stream = runWorkflow({ + runStore, + workflow: articleWorkflow, + ...params, + }) + return toServerSentEventsResponse(stream) + } catch (error) { + return new Response( + JSON.stringify({ + error: error instanceof Error ? error.message : 'Unknown error', + }), + { status: 400, headers: { 'Content-Type': 'application/json' } }, + ) + } },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/routes/api.workflow.ts` around lines 16 - 28, Wrap the request handling in a try/catch that separately guards parseWorkflowRequest and runWorkflow so thrown errors return structured HTTP responses instead of unhandled failures: catch parse errors from parseWorkflowRequest and return a 400 JSON error, preserve the existing abort logic when params indicate abort, then wrap the runWorkflow call and stream conversion in its own try/catch that logs the error and returns a 500 JSON error if runWorkflow or toServerSentEventsResponse throws; reference parseWorkflowRequest, runWorkflow, runStore, and toServerSentEventsResponse to locate the code and keep the existing abortController abort path intact.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/orchestration/orchestrators.md`: - Around line 24-29: The fenced code block containing "for turn = 0..maxTurns:" is unlabeled and triggers MD040; update the opening fence (the triple backticks before the block) to include a language tag such as text or pseudo (e.g., change ``` to ```text) so the block is labeled, preserving the existing lines with router, run, decision, and lastResult. In `@examples/ts-react-chat/src/components/CodeBlock.tsx`: - Around line 40-67: The effect in CodeBlock leaves previous errored/html state across runs, so at the start of the async work inside the useEffect you should reset the highlight state: call setErrored(false) and clear stale HTML via setHtml('') (or equivalent initial value) before awaiting getHighlighter(), so subsequent successful highlights render after a prior failure; keep the existing cancellation object (ctl) and error handling around getHighlighter()/highlighter.codeToHtml unchanged. --- Outside diff comments: In `@examples/ts-react-chat/src/routes/api.workflow.ts`: - Around line 16-28: Wrap the request handling in a try/catch that separately guards parseWorkflowRequest and runWorkflow so thrown errors return structured HTTP responses instead of unhandled failures: catch parse errors from parseWorkflowRequest and return a 400 JSON error, preserve the existing abort logic when params indicate abort, then wrap the runWorkflow call and stream conversion in its own try/catch that logs the error and returns a 500 JSON error if runWorkflow or toServerSentEventsResponse throws; reference parseWorkflowRequest, runWorkflow, runStore, and toServerSentEventsResponse to locate the code and keep the existing abortController abort path intact.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
4ab30fa8-c053-478b-aa83-fbf0a01a7518📥 Commits
Reviewing files that changed from the base of the PR and between 16354b71b0312b52c6208518074a18d489b05db6 and 0f662123642802e1c0f3ee7bf6ceccf936765650.
📒 Files selected for processing (31)
.agent/self-learning/coupling.jsondocs/api/ai-orchestration.mddocs/chat/agentic-cycle.mddocs/config.jsondocs/getting-started/overview.mddocs/orchestration/approvals.mddocs/orchestration/orchestrators.mddocs/orchestration/overview.mddocs/orchestration/refining-across-runs.mddocs/orchestration/retries-and-errors.mddocs/orchestration/run-persistence.mddocs/orchestration/workflows.mddocs/structured-outputs/multi-turn.mddocs/tools/tools.mdexamples/ts-react-chat/package.jsonexamples/ts-react-chat/src/components/CodeBlock.tsxexamples/ts-react-chat/src/components/DraftPreview.tsxexamples/ts-react-chat/src/components/FileTreePanel.tsxexamples/ts-react-chat/src/components/Header.tsxexamples/ts-react-chat/src/lib/diff-extract.tsexamples/ts-react-chat/src/lib/shiki/highlighter.tsexamples/ts-react-chat/src/lib/shiki/theme.tsexamples/ts-react-chat/src/lib/workflows/article-workflow.tsexamples/ts-react-chat/src/lib/workflows/orchestrator.tsexamples/ts-react-chat/src/routeTree.gen.tsexamples/ts-react-chat/src/routes/api.orchestration.tsexamples/ts-react-chat/src/routes/api.workflow.tsexamples/ts-react-chat/src/routes/orchestration.tsxexamples/ts-react-chat/src/routes/workflow.tsxexamples/ts-react-chat/src/styles.cssknip.json
✅ Files skipped from review due to trivial changes (7)
- docs/tools/tools.md
- docs/chat/agentic-cycle.md
- docs/api/ai-orchestration.md
- docs/structured-outputs/multi-turn.md
- docs/orchestration/overview.md
- docs/orchestration/refining-across-runs.md
- docs/orchestration/approvals.md
docs/orchestration/orchestrators.md lines 24 to 29OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +9,21 @@9+ - defineRouter10+ - useOrchestration11+ - router pattern12+ - state machine ai13+ - dynamic agent routing14+---15+16+A workflow expects a path you can write out in advance: A, then B, then C. The moment the path branches on a model decision — "if the spec is ready, implement; otherwise refine; otherwise ask the user" — a linear generator stops being the right shape. You either nest `if/else` until the body is unreadable, or you reach for an orchestrator.17+18+By the end of this guide you'll have rewritten the linear pipeline from [Workflows](./workflows) as an orchestrator whose **router** picks the next agent each turn based on accumulated state.19+20+## The mental model21+22+An **orchestrator** is a workflow whose `run` body is a fixed routing loop:23+24+```25+for turn = 0..maxTurns:26+ decision = router({ input, state, agents, turn, lastResult })27+ if decision.done: return decision.output28+ lastResult = run(decision.agent, decision.input)29+```⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Add a language tag to this fenced code block.
Line 24 uses an unlabeled fence and will fail MD040 in markdown lint.
Proposed fix
-``` +```text for turn = 0..maxTurns: decision = router({ input, state, agents, turn, lastResult }) if decision.done: return decision.output lastResult = run(decision.agent, decision.input)</details> <details> <summary>🧰 Tools</summary> <details> <summary>🪛 markdownlint-cli2 (0.22.1)</summary> [warning] 24-24: Fenced code blocks should have a language specified (MD040, fenced-code-language) </details> </details> <details> <summary>🤖 Prompt for AI Agents</summary>Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.
In
@docs/orchestration/orchestrators.mdaround lines 24 - 29, The fenced code block containing "for turn = 0..maxTurns:" is unlabeled and triggers MD040; update the opening fence (the triple backticks before the block) to include a language tag such as text or pseudo (e.g., changetotext) so the block is labeled, preserving the existing lines with router, run, decision, and lastResult.</details> <!-- fingerprinting:phantom:poseidon:hawk --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits 62bb9d6 to 04dcab8examples/ts-react-chat/src/components/CodeBlock.tsx lines 40 to 73Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +47,21 @@47+ const highlighter = await getHighlighter()48+ if (!highlighter.getLoadedLanguages().includes(lang)) {49+ await highlighter.loadLanguage(50+ lang as Parameters<typeof highlighter.loadLanguage>[0],51+ )52+ }53+ if (ctl.cancelled) return54+ const out = highlighter.codeToHtml(props.code, {55+ lang,56+ theme: 'tanstack-ink',57+ })58+ setHtml(out)59+ } catch {60+ if (!ctl.cancelled) setErrored(true)61+ }62+ })()63+ return () => {64+ ctl.cancelled = true65+ }66+ }, [props.code, lang])67+⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Reset highlight state at the start of each effect run.
Line 40 can leave
erroredstucktrueandhtmlstale across updates, so re-highlighting may never display after a prior failure.Proposed fix
useEffect(() => { + setErrored(false) + setHtml(null) + // Object wrapper so the cleanup closure can mutate without ESLint's // no-unnecessary-condition narrowing the bool to `false` at the check // sites (it doesn't see the deferred cleanup mutation). const ctl = { cancelled: false } void (async () => { try { const highlighter = await getHighlighter() if (!highlighter.getLoadedLanguages().includes(lang)) { await highlighter.loadLanguage( lang as Parameters<typeof highlighter.loadLanguage>[0], ) } if (ctl.cancelled) return const out = highlighter.codeToHtml(props.code, { lang, theme: 'tanstack-ink', }) + if (ctl.cancelled) return setHtml(out) } catch { - if (!ctl.cancelled) setErrored(true) + if (!ctl.cancelled) setErrored(true) } })()🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/components/CodeBlock.tsx` around lines 40 - 67, The effect in CodeBlock leaves previous errored/html state across runs, so at the start of the async work inside the useEffect you should reset the highlight state: call setErrored(false) and clear stale HTML via setHtml('') (or equivalent initial value) before awaiting getHighlighter(), so subsequent successful highlights render after a prior failure; keep the existing cancellation object (ctl) and error handling around getHighlighter()/highlighter.codeToHtml unchanged.✅ Addressed in commits 62bb9d6 to b9d3fcd
Actionable comments posted: 4
♻️ Duplicate comments (1)
packages/typescript/ai-orchestration/src/run-store/in-memory.ts (1)
32-61: ⚠️ Potential issue | 🟠 Major | ⚡ Quick winRun teardown still drops live state without unblocking paused workflows.
TTL expiry and
deleteRunremoveliveentries, but they don’t abort the live controller or resolve/reject a pending approval wait, so paused generators can hang/leak.🔧 Suggested patch
const expirations = new Map<string, NodeJS.Timeout>() + function teardownLive(runId: string) { + const l = live.get(runId) + if (!l) return + try { + l.abortController.abort() + } catch {} + if (l.approvalResolver) { + l.approvalResolver({ + approved: false, + approvalId: '', + feedback: 'run terminated', + }) + } + live.delete(runId) + } + function scheduleExpiry(runId: string) { const existing = expirations.get(runId) if (existing) clearTimeout(existing) const handle = setTimeout(() => { runs.delete(runId) - live.delete(runId) + teardownLive(runId) stepLogs.delete(runId) expirations.delete(runId) }, ttl) expirations.set(runId, handle) } @@ deleteRun(runId, _reason) { runs.delete(runId) - live.delete(runId) + teardownLive(runId) stepLogs.delete(runId) const handle = expirations.get(runId) if (handle) clearTimeout(handle) expirations.delete(runId) return Promise.resolve() },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts` around lines 32 - 61, The TTL expiry handler in scheduleExpiry and the deleteRun implementation remove entries from runs/live/stepLogs but never notify the live controller or settle any pending approval waiters, causing paused generators to hang; update both the timeout callback in scheduleExpiry and the deleteRun function to first retrieve the live entry (live.get(runId)), and if present call the live controller's cancellation/unblock API (e.g., controller.abort() or controller.cancel()) and settle any stored approval promise (resolve/reject it with a consistent Error like "run deleted" or "run expired"), then proceed to clear timeouts and delete the maps; ensure setRunState still calls scheduleExpiry so expiry path is covered.🧹 Nitpick comments (2)
packages/typescript/ai-orchestration/tests/engine.primitives.test.ts (1)
304-306: ⚡ Quick winUUID assertion is not v4-specific.
The current pattern allows non-v4 UUIDs while the test intent says v4.
Suggested regex
- expect(recordedId).toMatch( - /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, - ) + expect(recordedId).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, + )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/tests/engine.primitives.test.ts` around lines 304 - 306, The test currently asserts recordedId against a generic UUID regex; change it to validate a v4 UUID specifically by using a v4-specific pattern or the project's UUID validator (e.g., assert / validate via the uuid library) for the recordedId variable in engine.primitives.test.ts; update the expect(recordedId).toMatch(...) to a regex that enforces the v4 variant (correct hex and the '4' in the version nibble and the appropriate variant bits) or replace the regex check with a call like isV4(recordedId) if a helper exists.packages/typescript/ai-orchestration/tests/engine.timeout.test.ts (1)
206-250: ⚡ Quick winThis test doesn’t reliably prove retry short-circuiting.
callCountis never incremented, and Line 249 (< 200) can still pass with all retries. The assertion is currently too permissive for the stated behavior.Suggested tightening
try { yield* step( 'timing-out', - () => new Promise(() => {}), // never resolves + () => + new Promise<void>(() => { + callCount++ + }), // never resolves { timeout: 20, retry: { @@ - // allow generous slack here for CI noise. - expect(elapsed).toBeLessThan(200) + expect(elapsed).toBeLessThan(120) + expect(callCount).toBe(1) @@ - expect(finished).toBeDefined() + expect(finished?.output.caughtImmediately).toBe(true)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/tests/engine.timeout.test.ts` around lines 206 - 250, The test never increments callCount so it can't prove retry short-circuiting; modify the workflow step function passed to step(...) (the anon function that returns new Promise(() => {})) to increment callCount each invocation (so callCount reflects attempts), then replace or augment the elapsed-based assertion with a deterministic check such as expect(callCount).toBe(1) (or assert caughtImmediately is true) after collect(...) completes; this uses the existing wf/step, callCount, collect, runWorkflow and StepTimeoutError symbols to observe that retries were short-circuited rather than relying on the flaky elapsed < 200 timing check.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/typescript/ai-orchestration/src/engine/fingerprint.ts`: - Around line 38-40: The current fingerprint uses join(',') which can collide when patch names contain commas; instead serialize the sorted patches unambiguously before feeding fnv1a64—e.g., replace the join(',') usage with a robust serializer like JSON.stringify(sorted) (or another deterministic escaping) so the input to fnv1a64 (referenced here as workflow.patches, sorted, and fnv1a64) cannot collide. In `@packages/typescript/ai-orchestration/src/server/parse-request.ts`: - Around line 49-51: The returned params currently include both approval and signalDelivery which allows ambiguous downstream behavior; modify the normalization in parse-request.ts so that when body.signal is present you do not forward body.approval (e.g., compute a normalizedApproval = body.signal ? undefined : body.approval or set approval: body.signal ? undefined : body.approval) and continue to set signalDelivery: body.signal and input: body.input; update the object construction that currently references approval, signalDelivery, input to use this normalized approval value so signal takes precedence over approval. In `@packages/typescript/ai-orchestration/tests/engine.cas.test.ts`: - Around line 33-71: Test never performs the duplicate delivery step; after the first runWorkflow call that delivers signalDelivery with signalId 'same-id' you must call runWorkflow again with the same runId and signalDelivery: { signalId: 'same-id', payload: { ok: true } } (using the same inMemoryRunStore) and collect its events, then assert the duplicate attempt returns the existing record/idempotent result (e.g., verify the returned events still include RUN_FINISHED and/or that the duplicate response indicates the existing delivery rather than creating a new one). Use the same helpers shown (runWorkflow, collect, inMemoryRunStore, signalDelivery) and add an expect on the second collect to confirm idempotent behavior. In `@packages/typescript/ai-orchestration/tests/engine.idempotency.test.ts`: - Around line 162-206: The test "persists signalDelivery.signalId on the resulting step record" is incomplete (ends with a `void 0` no-op) and either needs to be finished or skipped; replace the `void 0` placeholder by implementing the verification using the same pattern as the later working test: use the defined workflow `wf`, the `inMemoryRunStore()` `store`, call `collect(runWorkflow(...))` to start and pause, then resume with `runWorkflow` passing `signalDelivery: { signalId: 'sig-abc-123', payload: {...} }`, and assert that the persisted step record in `store` contains the `signalId` (or alternatively mark the test with `.skip`/`.todo` to reflect it's intentionally incomplete) — look for usages of `runWorkflow`, `collect`, `inMemoryRunStore`, and the test name to place the assertion or skip. --- Duplicate comments: In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts`: - Around line 32-61: The TTL expiry handler in scheduleExpiry and the deleteRun implementation remove entries from runs/live/stepLogs but never notify the live controller or settle any pending approval waiters, causing paused generators to hang; update both the timeout callback in scheduleExpiry and the deleteRun function to first retrieve the live entry (live.get(runId)), and if present call the live controller's cancellation/unblock API (e.g., controller.abort() or controller.cancel()) and settle any stored approval promise (resolve/reject it with a consistent Error like "run deleted" or "run expired"), then proceed to clear timeouts and delete the maps; ensure setRunState still calls scheduleExpiry so expiry path is covered. --- Nitpick comments: In `@packages/typescript/ai-orchestration/tests/engine.primitives.test.ts`: - Around line 304-306: The test currently asserts recordedId against a generic UUID regex; change it to validate a v4 UUID specifically by using a v4-specific pattern or the project's UUID validator (e.g., assert / validate via the uuid library) for the recordedId variable in engine.primitives.test.ts; update the expect(recordedId).toMatch(...) to a regex that enforces the v4 variant (correct hex and the '4' in the version nibble and the appropriate variant bits) or replace the regex check with a call like isV4(recordedId) if a helper exists. In `@packages/typescript/ai-orchestration/tests/engine.timeout.test.ts`: - Around line 206-250: The test never increments callCount so it can't prove retry short-circuiting; modify the workflow step function passed to step(...) (the anon function that returns new Promise(() => {})) to increment callCount each invocation (so callCount reflects attempts), then replace or augment the elapsed-based assertion with a deterministic check such as expect(callCount).toBe(1) (or assert caughtImmediately is true) after collect(...) completes; this uses the existing wf/step, callCount, collect, runWorkflow and StepTimeoutError symbols to observe that retries were short-circuited rather than relying on the flaky elapsed < 200 timing check.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
31b1c1cb-f2c1-479a-8cf6-cf2edba5fd8e📥 Commits
Reviewing files that changed from the base of the PR and between 0f662123642802e1c0f3ee7bf6ceccf936765650 and 5486c02be2701abc0cdc1883e3a1635d35327393.
📒 Files selected for processing (34)
docs/config.jsondocs/getting-started/workflows.mdpackages/typescript/ai-client/src/index.tspackages/typescript/ai-client/src/workflow-client.tspackages/typescript/ai-orchestration/README.mdpackages/typescript/ai-orchestration/src/define/define-workflow.tspackages/typescript/ai-orchestration/src/engine/emit-events.tspackages/typescript/ai-orchestration/src/engine/fingerprint.tspackages/typescript/ai-orchestration/src/engine/run-workflow.tspackages/typescript/ai-orchestration/src/index.tspackages/typescript/ai-orchestration/src/primitives/now.tspackages/typescript/ai-orchestration/src/primitives/patched.tspackages/typescript/ai-orchestration/src/primitives/sleep.tspackages/typescript/ai-orchestration/src/primitives/step.tspackages/typescript/ai-orchestration/src/primitives/uuid.tspackages/typescript/ai-orchestration/src/primitives/wait-for-signal.tspackages/typescript/ai-orchestration/src/registry/select-version.tspackages/typescript/ai-orchestration/src/run-store/in-memory.tspackages/typescript/ai-orchestration/src/server/parse-request.tspackages/typescript/ai-orchestration/src/types.tspackages/typescript/ai-orchestration/tests/engine.attach.test.tspackages/typescript/ai-orchestration/tests/engine.cas.test.tspackages/typescript/ai-orchestration/tests/engine.durability.test.tspackages/typescript/ai-orchestration/tests/engine.idempotency.test.tspackages/typescript/ai-orchestration/tests/engine.patched.test.tspackages/typescript/ai-orchestration/tests/engine.primitives.test.tspackages/typescript/ai-orchestration/tests/engine.publisher.test.tspackages/typescript/ai-orchestration/tests/engine.retry.test.tspackages/typescript/ai-orchestration/tests/engine.signals.test.tspackages/typescript/ai-orchestration/tests/engine.smoke.test.tspackages/typescript/ai-orchestration/tests/engine.timeout.test.tspackages/typescript/ai-orchestration/tests/in-memory-store.test.tspackages/typescript/ai-orchestration/tests/registry.test.tspackages/typescript/ai-react/src/use-workflow.ts
✅ Files skipped from review due to trivial changes (2)
- packages/typescript/ai-orchestration/src/primitives/uuid.ts
- packages/typescript/ai-orchestration/README.md
packages/typescript/ai-orchestration/src/engine/fingerprint.ts lines 38 to 40OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +20,21 @@20+ * builds may minify, so the fingerprint is sensitive to whitespace and21+ * symbol renaming. That's the conservative choice (Temporal does the22+ * same): false-positive mismatches force a redeploy decision rather23+ * than silently corrupting an in-flight run.24+ *25+ * The fingerprint is a 64-bit FNV-1a hash rendered as base36. Crypto26+ * strength is not required — we're comparing equality, not resisting27+ * collision attacks.28+ */29+export function fingerprintWorkflow(workflow: AnyWorkflowDefinition): string {30+ // Patch-versioned mode: workflows that declare `patches` opt out of31+ // the strict source-hash fingerprint. The fingerprint then covers32+ // only the compatibility surface (name + sorted patch list), so33+ // code-body changes don't trigger workflow_version_mismatch. The34+ // patches-subset check on resume (see run-workflow.ts) enforces35+ // that the run's recorded patches are a subset of the current36+ // workflow's patches — i.e., we can ADD patches across deploys but37+ // not REMOVE them while runs are in flight.38+ if (workflow.patches !== undefined) {39+ const sorted = [...workflow.patches].sort().join(',')40+ return fnv1a64(`patch-versioned:${workflow.name}:${sorted}`)⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Use unambiguous patch serialization for fingerprint input.
Line 39’s
join(',')can collide for different patch-name sets when names contain commas. That can produce false fingerprint matches.Suggested fix
- if (workflow.patches !== undefined) { - const sorted = [...workflow.patches].sort().join(',') - return fnv1a64(`patch-versioned:${workflow.name}:${sorted}`) - } + if (workflow.patches !== undefined) { + const sorted = [...workflow.patches].sort() + return fnv1a64(`patch-versioned:${workflow.name}:${JSON.stringify(sorted)}`) + }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change38- if (workflow.patches !== undefined) {39- const sorted = [...workflow.patches].sort().join(',')40- return fnv1a64(`patch-versioned:${workflow.name}:${sorted}`)38+ if (workflow.patches !== undefined) {39+ const sorted = [...workflow.patches].sort()40+ return fnv1a64(`patch-versioned:${workflow.name}:${JSON.stringify(sorted)}`)41+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/engine/fingerprint.ts` around lines 38 - 40, The current fingerprint uses join(',') which can collide when patch names contain commas; instead serialize the sorted patches unambiguously before feeding fnv1a64—e.g., replace the join(',') usage with a robust serializer like JSON.stringify(sorted) (or another deterministic escaping) so the input to fnv1a64 (referenced here as workflow.patches, sorted, and fnv1a64) cannot collide.✅ Addressed in commits 62bb9d6 to 04dcab8
packages/typescript/ai-orchestration/src/server/parse-request.ts lines 49 to 51OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +31,21 @@31+ * @example32+ * ```typescript33+ * POST: async ({ request }) => {34+ * const params = await parseWorkflowRequest(request)35+ * if (params.abort && params.runId) {36+ * runStore.getLive(params.runId)?.abortController.abort()37+ * return new Response(null, { status: 204 })38+ * }39+ * const stream = runWorkflow({ workflow, runStore, ...params })40+ * return toServerSentEventsResponse(stream)41+ * }42+ * ```43+ */44+export async function parseWorkflowRequest(45+ request: Request,46+): Promise<WorkflowRequestParams> {47+ const body = (await request.json()) as RawBody48+ return {49+ approval: body.approval,50+ signalDelivery: body.signal,51+ input: body.input,⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Enforce the documented signal-over-approval precedence in returned params.
Line 50 forwards
signalDelivery, but Line 49 still forwardsapprovaleven when both are present. Normalize at parse-time to avoid ambiguous downstream handling.Suggested normalization
return { - approval: body.approval, + approval: body.signal ? undefined : body.approval, signalDelivery: body.signal, input: body.input, runId: body.runId, abort: body.abort, }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/src/server/parse-request.ts` around lines 49 - 51, The returned params currently include both approval and signalDelivery which allows ambiguous downstream behavior; modify the normalization in parse-request.ts so that when body.signal is present you do not forward body.approval (e.g., compute a normalizedApproval = body.signal ? undefined : body.approval or set approval: body.signal ? undefined : body.approval) and continue to set signalDelivery: body.signal and input: body.input; update the object construction that currently references approval, signalDelivery, input to use this normalized approval value so signal takes precedence over approval.✅ Addressed in commits 62bb9d6 to 04dcab8
packages/typescript/ai-orchestration/tests/engine.cas.test.ts lines 33 to 71OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +51,21 @@51+52+ const store = inMemoryRunStore()53+ await collect(54+ runWorkflow({55+ workflow: wf as any,56+ input: {},57+ runId: 'run-a',58+ runStore: store,59+ }),60+ )61+62+ // First delivery — succeeds, run finishes.63+ const first = await collect(64+ runWorkflow({65+ workflow: wf as any,66+ runId: 'run-a',67+ signalDelivery: { signalId: 'same-id', payload: { ok: true } },68+ runStore: store,69+ }),70+ )71+ expect(first.find((e) => e.type === 'RUN_FINISHED')).toBeDefined()⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Duplicate-delivery scenario is not actually executed.
This spec says it validates retry/idempotency for duplicate
signalId, but it only performs the first delivery and never sends the duplicate request.✅ Suggested patch
const first = await collect( runWorkflow({ workflow: wf as any, runId: 'run-a', signalDelivery: { signalId: 'same-id', payload: { ok: true } }, runStore: store, }), ) expect(first.find((e) => e.type === 'RUN_FINISHED')).toBeDefined() + + // Duplicate delivery with the same signalId should be idempotent. + const retry = await collect( + runWorkflow({ + workflow: wf as any, + runId: 'run-a', + signalDelivery: { signalId: 'same-id', payload: { ok: true } }, + runStore: store, + }), + ) + expect(retry.find((e) => e.type === 'RUN_FINISHED')).toBeDefined() + expect(retry.find((e) => e.type === 'RUN_ERROR')).toBeUndefined()📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change33+ it('returns the existing record on duplicate signal delivery (same signalId)', async () => {34+ // The scenario: client posts a signal, gets an SSE response back.35+ // Network drops mid-response. Client retries with the same36+ // signalId (generated once by the client lib, reused on retry).37+ // Server's second-attempt resume would replay through the log and38+ // then attempt to append at the same index — CAS catches that and39+ // the engine treats it as idempotent.40+ const wf = defineWorkflow({41+ name: 'idempotent-wf',42+ input: z.object({}).default({}),43+ output: z.object({ payload: z.any() }),44+ state: z.object({}).default({}),45+ agents: {},46+ run: async function* () {47+ const p = yield* waitForSignal<{ ok: boolean }>('go')48+ return { payload: p }49+ },50+ })51+52+ const store = inMemoryRunStore()53+ await collect(54+ runWorkflow({55+ workflow: wf as any,56+ input: {},57+ runId: 'run-a',58+ runStore: store,59+ }),60+ )61+62+ // First delivery — succeeds, run finishes.63+ const first = await collect(64+ runWorkflow({65+ workflow: wf as any,66+ runId: 'run-a',67+ signalDelivery: { signalId: 'same-id', payload: { ok: true } },68+ runStore: store,69+ }),70+ )71+ expect(first.find((e) => e.type === 'RUN_FINISHED')).toBeDefined()72+73+ // Duplicate delivery with the same signalId should be idempotent.74+ const retry = await collect(75+ runWorkflow({76+ workflow: wf as any,77+ runId: 'run-a',78+ signalDelivery: { signalId: 'same-id', payload: { ok: true } },79+ runStore: store,80+ }),81+ )82+ expect(retry.find((e) => e.type === 'RUN_FINISHED')).toBeDefined()83+ expect(retry.find((e) => e.type === 'RUN_ERROR')).toBeUndefined()84+ })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/tests/engine.cas.test.ts` around lines 33 - 71, Test never performs the duplicate delivery step; after the first runWorkflow call that delivers signalDelivery with signalId 'same-id' you must call runWorkflow again with the same runId and signalDelivery: { signalId: 'same-id', payload: { ok: true } } (using the same inMemoryRunStore) and collect its events, then assert the duplicate attempt returns the existing record/idempotent result (e.g., verify the returned events still include RUN_FINISHED and/or that the duplicate response indicates the existing delivery rather than creating a new one). Use the same helpers shown (runWorkflow, collect, inMemoryRunStore, signalDelivery) and add an expect on the second collect to confirm idempotent behavior.✅ Addressed in commit 62bb9d6
packages/ai-orchestration/tests/engine.idempotency.test.ts lines 158 to 201Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +186,21 @@186+ await collect(187+ runWorkflow({188+ workflow: wf as any,189+ runId: 'r1',190+ signalDelivery: {191+ signalId: 'sig-abc-123',192+ payload: { ok: true },193+ },194+ runStore: store,195+ }),196+ )197+198+ // After resume the run is finished and the store entry was deleted199+ // — but we can inspect the log right after the resume completes by200+ // grabbing it during a paused state. Restructure: start, pause,201+ // grab log midway. Actually the test above already shows the log202+ // entry gets the signalId via the resume path. Let's verify with a203+ // workflow that pauses again after the signal so we can read the204+ // store mid-flight.205+ void 0206+ })⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Test body is incomplete — no assertion after the
void 0placeholder.The test is named "persists signalDelivery.signalId on the resulting step record" but ends with a
void 0no-op after comments explaining a restructure is needed. The actual verification never happens. Either complete the test (the subsequent test at lines 208-254 shows the working pattern) or mark it as.skip/.todoso CI accurately reflects coverage.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/typescript/ai-orchestration/tests/engine.idempotency.test.ts` around lines 162 - 206, The test "persists signalDelivery.signalId on the resulting step record" is incomplete (ends with a `void 0` no-op) and either needs to be finished or skipped; replace the `void 0` placeholder by implementing the verification using the same pattern as the later working test: use the defined workflow `wf`, the `inMemoryRunStore()` `store`, call `collect(runWorkflow(...))` to start and pause, then resume with `runWorkflow` passing `signalDelivery: { signalId: 'sig-abc-123', payload: {...} }`, and assert that the persisted step record in `store` contains the `signalId` (or alternatively mark the test with `.skip`/`.todo` to reflect it's intentionally incomplete) — look for usages of `runWorkflow`, `collect`, `inMemoryRunStore`, and the test name to place the assertion or skip.✅ Addressed in commits 62bb9d6 to b9d3fcd
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
Diff Package Supply Chain
SecurityVulnerability Quality Maintenance License shiki@4.1.0 @tanstack/workflow-core@0.0.2 Closing as superseded by #979. We are standardizing on TanStack Workflow as the durable runtime and on one async handler/context authoring model. The generator/
yield*API and duplicate orchestration runtime/store will not move forward.The AG-UI, client, persistence, and interrupt questions are carried into the new RFC. Thank you for the extensive prototype work; it directly informed the ownership boundaries and decisions in #979.
tannerlinsley closed this
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
5f05beda-d3c3-4eba-845c-1eda8e3eedf6📥 Commits
Reviewing files that changed from the base of the PR and between d5645cfd4d1b9cfc877f7d4d714517e166a99ce3 and 9de8cfa591236d225f425226d819e8fda99ea53e.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml📒 Files selected for processing (91)
.agent/self-learning/coupling.jsondocs/api/ai-orchestration.mddocs/chat/agentic-cycle.mddocs/config.jsondocs/getting-started/overview.mddocs/getting-started/workflows.mddocs/orchestration/approvals.mddocs/orchestration/orchestrators.mddocs/orchestration/overview.mddocs/orchestration/refining-across-runs.mddocs/orchestration/retries-and-errors.mddocs/orchestration/run-persistence.mddocs/orchestration/workflows.mddocs/structured-outputs/multi-turn.mddocs/tools/tools.mdexamples/ts-react-chat/package.jsonexamples/ts-react-chat/src/components/ArticleModal.tsxexamples/ts-react-chat/src/components/CodeBlock.tsxexamples/ts-react-chat/src/components/DraftPreview.tsxexamples/ts-react-chat/src/components/FileTreePanel.tsxexamples/ts-react-chat/src/components/Header.tsxexamples/ts-react-chat/src/components/StateInspector.tsxexamples/ts-react-chat/src/components/WorkflowTimeline.tsxexamples/ts-react-chat/src/lib/diff-extract.tsexamples/ts-react-chat/src/lib/shiki/highlighter.tsexamples/ts-react-chat/src/lib/shiki/theme.tsexamples/ts-react-chat/src/lib/workflows/article-workflow.test.tsexamples/ts-react-chat/src/lib/workflows/article-workflow.tsexamples/ts-react-chat/src/lib/workflows/orchestrator.tsexamples/ts-react-chat/src/routeTree.gen.tsexamples/ts-react-chat/src/routes/api.orchestration.tsexamples/ts-react-chat/src/routes/api.workflow.tsexamples/ts-react-chat/src/routes/orchestration.tsxexamples/ts-react-chat/src/routes/workflow.tsxexamples/ts-react-chat/src/styles.cssknip.jsonpackages/ai-client/src/connection-adapters.tspackages/ai-client/src/index.tspackages/ai-client/src/workflow-client.tspackages/ai-client/tests/workflow-client.test.tspackages/ai-orchestration/README.mdpackages/ai-orchestration/eslint.config.jspackages/ai-orchestration/package.jsonpackages/ai-orchestration/skills/ai-orchestration/SKILL.mdpackages/ai-orchestration/src/define/define-agent.tspackages/ai-orchestration/src/define/define-orchestrator.tspackages/ai-orchestration/src/define/define-router.tspackages/ai-orchestration/src/define/define-workflow.tspackages/ai-orchestration/src/engine/emit-events.tspackages/ai-orchestration/src/engine/invoke-agent.tspackages/ai-orchestration/src/engine/run-workflow.tspackages/ai-orchestration/src/index.tspackages/ai-orchestration/src/primitives/approve.tspackages/ai-orchestration/src/primitives/bind-agents.tspackages/ai-orchestration/src/primitives/now.tspackages/ai-orchestration/src/primitives/patched.tspackages/ai-orchestration/src/primitives/retry.tspackages/ai-orchestration/src/primitives/sleep.tspackages/ai-orchestration/src/primitives/step.tspackages/ai-orchestration/src/primitives/uuid.tspackages/ai-orchestration/src/primitives/wait-for-signal.tspackages/ai-orchestration/src/registry/select-version.tspackages/ai-orchestration/src/result.tspackages/ai-orchestration/src/run-store/compat-events.tspackages/ai-orchestration/src/run-store/in-memory.tspackages/ai-orchestration/src/server/index.tspackages/ai-orchestration/src/server/parse-request.tspackages/ai-orchestration/src/types.tspackages/ai-orchestration/tests/engine.attach.test.tspackages/ai-orchestration/tests/engine.cas.test.tspackages/ai-orchestration/tests/engine.durability.test.tspackages/ai-orchestration/tests/engine.idempotency.test.tspackages/ai-orchestration/tests/engine.patched.test.tspackages/ai-orchestration/tests/engine.primitives.test.tspackages/ai-orchestration/tests/engine.publisher.test.tspackages/ai-orchestration/tests/engine.retry.test.tspackages/ai-orchestration/tests/engine.signals.test.tspackages/ai-orchestration/tests/engine.smoke.test.tspackages/ai-orchestration/tests/engine.timeout.test.tspackages/ai-orchestration/tests/in-memory-store.test.tspackages/ai-orchestration/tests/parse-request.test.tspackages/ai-orchestration/tests/registry.test.tspackages/ai-orchestration/tests/test-utils.tspackages/ai-orchestration/tests/workflow-core-delegation.test.tspackages/ai-orchestration/tsconfig.jsonpackages/ai-orchestration/vite.config.tspackages/ai-react/package.jsonpackages/ai-react/src/index.tspackages/ai-react/src/use-workflow.tspackages/ai-react/tests/use-workflow-schema-inference.test.tspackages/ai/skills/ai-core/SKILL.md📝 Walkthrough
Walkthrough#
Adds a full orchestration stack for generator-based workflows and orchestrators, with new engine primitives, streaming client support, example workflow pages, docs, and tests.
Changes#
AI Orchestration Stack
packages/ai-orchestration/src/types.ts,packages/ai-orchestration/src/define/*,packages/ai-orchestration/src/primitives/*,packages/ai-orchestration/src/registry/select-version.ts,packages/ai-orchestration/src/result.tspackages/ai-orchestration/src/engine/*,packages/ai-orchestration/src/run-store/*,packages/ai-orchestration/src/server/*packages/ai-client/src/*,packages/ai-react/src/*examples/ts-react-chat/src/*docs/*,packages/ai-orchestration/skills/*,packages/ai/skills/*,.agent/self-learning/coupling.json,knip.jsonpackages/ai-orchestration/tests/*,packages/ai-client/tests/*,packages/ai-react/tests/*,examples/ts-react-chat/src/lib/workflows/article-workflow.test.tsAI Orchestration Stack
packages/ai-orchestration/src/types.ts,packages/ai-orchestration/src/define/*,packages/ai-orchestration/src/primitives/*,packages/ai-orchestration/src/registry/select-version.ts,packages/ai-orchestration/src/result.tspackages/ai-orchestration/src/engine/*,packages/ai-orchestration/src/run-store/*,packages/ai-orchestration/src/server/*packages/ai-client/src/*,packages/ai-react/src/*examples/ts-react-chat/src/*docs/*,packages/ai-orchestration/skills/*,packages/ai/skills/*,.agent/self-learning/coupling.json,knip.jsonpackages/ai-orchestration/tests/*,packages/ai-client/tests/*,packages/ai-react/tests/*,examples/ts-react-chat/src/lib/workflows/article-workflow.test.tsSequence Diagram(s)#
Estimated code review effort#
🎯 5 (Critical) | ⏱️ ~120 minutes
Possibly related issues#
Suggested reviewers#
Poem#
✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)