Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/session-items-from-renderer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@flow-state-dev/react": patch
---

`ItemsRenderer` provides the session item list to nested stream-aware components when none is already in scope, and exports `SessionItemsProvider` / `useSessionItems` (FIX-1498).
19 changes: 17 additions & 2 deletions apps/docs/docs/api/react.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ See the [Voice guide](/docs/advanced/voice) for full usage details.

### `ItemRenderer`

Render a single item using the registered renderer.
Render a single item using the registered renderer. Does not put a list in scope for `useSessionItems()`.

```tsx
import { ItemRenderer } from "@flow-state-dev/react";
Expand All @@ -185,7 +185,7 @@ import { ItemRenderer } from "@flow-state-dev/react";

### `ItemsRenderer`

Render a list of items. By default, conversational items with `history: false` visibility (sub-agent output) are filtered out — they're available in `session.items` but hidden from the default conversation view so orchestrator chatter doesn't crowd the UI. Pass `showSubAgents` to surface them inline, or render a per-agent view via `session.getItemsByAgent(name)`.
Render a list of items. Nested `useSessionItems()` consumers receive the same `items` array you pass, unless a `SessionItemsProvider` is already mounted above `ItemsRenderer` — that list stays. By default, conversational items with `history: false` visibility (sub-agent output) are filtered out of the rendered stream — they're available in `session.items` but hidden from the default conversation view so orchestrator chatter doesn't crowd the UI. Pass `showSubAgents` to surface them inline, or render a per-agent view via `session.getItemsByAgent(name)`.

```tsx
import { ItemsRenderer } from "@flow-state-dev/react";
Expand All @@ -197,6 +197,21 @@ import { ItemsRenderer } from "@flow-state-dev/react";
<ItemsRenderer items={session.items} showSubAgents />
```

### `SessionItemsProvider` / `useSessionItems`

`ItemsRenderer` mounts this for its subtree when none is already mounted. Use it when you render a stream-aware card outside that helper, or above `ItemsRenderer` when the rendered list is a subset of the session.

```tsx
import { SessionItemsProvider } from "@flow-state-dev/react";
import { TaskPlan } from "@/components/flow-state/task-plan";

<SessionItemsProvider value={session.items}>
<TaskPlan collectionId="research-board" />
</SessionItemsProvider>
```

`useSessionItems()` returns `[]` when no provider is mounted, including under `ItemRenderer` alone.

### Custom Renderers

```tsx
Expand Down
2 changes: 2 additions & 0 deletions apps/docs/docs/client/react.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,8 @@ import { ItemRenderer, ItemsRenderer } from "@flow-state-dev/react";
<ItemRenderer item={item} />
```

`ItemsRenderer` puts its `items` array in scope for nested `useSessionItems()` consumers when no `SessionItemsProvider` is already mounted. An ancestor provider stays in place. `ItemRenderer` does not mount one. When you render a stream-aware card outside `ItemsRenderer`, wrap it in `<SessionItemsProvider value={items}>`.

### Custom Renderers

All custom renderers receive `{ item }` as their prop:
Expand Down
12 changes: 9 additions & 3 deletions apps/docs/docs/ui/flow-aware-components.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Human-in-the-loop approval card for `suspension` items. Shows the gate's message
fsdev ui add approval
```

The card is presentation over the `useApproval` hook from `@flow-state-dev/react`, which owns the resume call and resolved state. It reads the resolution from `SessionItemsProvider`, so wrap your item list in one for the receipt to show on reload. For the full server-to-UI walkthrough, see the [Human-in-the-Loop guide](/guides/human-in-the-loop).
The card is presentation over the `useApproval` hook from `@flow-state-dev/react`, which owns the resume call and resolved state. Under `<ItemsRenderer items={session.items} />`, `useSessionItems()` sees that list when no `SessionItemsProvider` is already mounted. Mount `<SessionItemsProvider value={session.items}>` when you render the card outside `ItemsRenderer`, or above it when the rendered list is a subset of the session. For the full server-to-UI walkthrough, see the [Human-in-the-Loop guide](/guides/human-in-the-loop).

## ModelBadge

Expand All @@ -71,7 +71,9 @@ fsdev ui add audit-annotation

## SessionItemsContext

React context for passing session items down to nested components. Required by any component that needs to subscribe to the item stream without prop drilling — `TaskPlan`, `RequestGroup`, and registry components that watch their own items.
React context that holds the session item list for `useSessionItems()`. `ItemsRenderer` mounts the provider when none is already mounted. Add this file and wrap a card yourself when you render it outside `ItemsRenderer`, or above `ItemsRenderer` when the rendered list is a subset of the session.

The file re-exports `SessionItemsProvider` and `useSessionItems` from `@flow-state-dev/react`.

```bash
fsdev ui add session-items-context
Expand All @@ -80,11 +82,13 @@ fsdev ui add session-items-context
```tsx
import { SessionItemsProvider } from "@/components/flow-state/session-items-context";

<SessionItemsProvider items={session.items}>
<SessionItemsProvider value={session.items}>
<TaskPlan collectionId="research-board" />
</SessionItemsProvider>
```

`useSessionItems()` returns `[]` when no provider is mounted.

## RequestGroup

Groups items by request id. Renders a streaming indicator while a request is in flight, surfaces sources at the bottom, and collapses consecutive tool calls into a single summary.
Expand All @@ -107,6 +111,8 @@ import { TaskPlan } from "@/components/flow-state/task-plan";
<TaskPlan collectionId="research-board" />
```

Under `ItemsRenderer`, `useSessionItems()` sees the list you passed. Outside it, pass `items` or wrap the card in `<SessionItemsProvider value={...}>`.

For a board-style horizontal layout, build a `TaskCollection` consumer of the same item streams rather than forking this renderer.

## Artifact
Expand Down
14 changes: 5 additions & 9 deletions apps/docs/guides/human-in-the-loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@ import {
ItemsRenderer,
} from "@flow-state-dev/react";
import { chatAssistantRenderers } from "@/components/flow-state/chat-assistant";
import { SessionItemsProvider } from "@/components/flow-state/session-items-context";
import { Conversation } from "@/components/flow-state/conversation";

export function ContentReview({ userId }: { userId: string }) {
Expand All @@ -149,11 +148,9 @@ function ReviewSurface() {

return (
<SuspensionResolverProvider resolve={session.resumeSuspension}>
<SessionItemsProvider value={session.items}>
<Conversation>
<ItemsRenderer items={session.items} />
</Conversation>
</SessionItemsProvider>
<Conversation>
<ItemsRenderer items={session.items} />
</Conversation>

<form
onSubmit={(e) => {
Expand All @@ -173,10 +170,9 @@ function ReviewSurface() {

Submitting runs the flow until the gate. The `Approval` card appears in the conversation with the gate's message and Approve / Reject buttons. Clicking one resolves the suspension, the flow's continuation streams back into `session.items`, and the card collapses to a one-line receipt (`✓ Approved`).

Two pieces make the live, in-place update work:
`SuspensionResolverProvider` hands the card the session's streaming resume (`session.resumeSuspension`). Without it, the card resolves, but the continuation only appears after the session refetches. With it, the resumed output streams onto the same request the user is watching. This matters most on serverless, where the continuation runs in a different invocation than the original stream.

- **`SuspensionResolverProvider`** hands the card the session's streaming resume (`session.resumeSuspension`). Without it, the card still resolves, but the continuation only appears after the session refetches. With it, the resumed output streams onto the same request the user is watching. This matters most on serverless, where the continuation runs in a different invocation than the original stream.
- **`SessionItemsProvider`** lets the card see the `suspension_resume` item that records the outcome, so it shows the receipt on resolve and after a reload. It's the same context `TaskPlan` and other stream-aware components use.
The `Approval` card reads the session list through `useSessionItems()`. `ItemsRenderer` puts `session.items` in that scope when no `SessionItemsProvider` is already mounted. Mount `<SessionItemsProvider value={session.items}>` when you render the card outside `ItemsRenderer`, or above it when the rendered list is a subset of the session.

### Without the ui registry

Expand Down
2 changes: 1 addition & 1 deletion apps/docs/guides/writing-ui-stories.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ Compose those instead of hand-rolling item shapes in each story. If your compone

Components that read `useFlowContext().renderers` (currently `RequestGroup` and `ChatAssistant`) need a `FlowProvider` in the tree. The global `preview.tsx` already wraps every story in `<FlowProvider renderers={chatAssistantRenderers}>`, so most of the time you don't need to think about it. Override it per-story by wrapping with your own `FlowProvider` if you want a different renderer registry.

`<TaskPlan />` reads from `<SessionItemsProvider />` rather than `FlowProvider`. Wrap it manually in the story when you want to drive it from a fixture session — see `task-plan.stories.tsx` for the pattern.
`<TaskPlan />` reads session items from `useSessionItems()`, or from an `items` prop. `FlowProvider` does not supply that list. In a story, pass `items` or wrap the card in `<SessionItemsProvider value={fixtureItems}>`. See `task-plan.stories.tsx`.

## Common variants worth writing

Expand Down
6 changes: 3 additions & 3 deletions apps/kitchen-sink/components/flow-state/approval.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ import { useSessionItems } from "./session-items-context";
* outcome) comes from `useApproval`; this component is presentation only.
*
* Wire it as a renderer type: it's included in `chatAssistantRenderers` as
* `suspension: Approval`. Resolved state is derived from the session item stream
* (via `useSessionItems`), so wrap your item list in `<SessionItemsProvider>` for
* the card to collapse to a receipt on reload — the same requirement as `TaskPlan`.
* `suspension: Approval`. Resolved state is derived from the session item
* list via `useSessionItems`. `ItemsRenderer` provides that list; mount
* `<SessionItemsProvider>` only when rendering this card outside it.
*/
export function Approval({ item }: { item: SuspensionItem }) {
// Find the matching resume in the stream to know if (and how) this resolved.
Expand Down
22 changes: 12 additions & 10 deletions apps/kitchen-sink/components/flow-state/session-items-context.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
"use client";

import { createContext, useContext } from "react";
import type { OutputItem } from "@flow-state-dev/core/items";

const SessionItemsContext = createContext<OutputItem[]>([]);

export const SessionItemsProvider = SessionItemsContext.Provider;

export function useSessionItems(): OutputItem[] {
return useContext(SessionItemsContext);
}
/**
* Re-export of the session item list context from `@flow-state-dev/react`.
*
* `ItemsRenderer` mounts the provider with the list it renders. Import
* `useSessionItems` / `SessionItemsProvider` from here in copied registry
* components so they share that context. Mount the provider yourself only
* when rendering stream-aware cards outside `ItemsRenderer`.
*/
export {
SessionItemsProvider,
useSessionItems,
} from "@flow-state-dev/react";
15 changes: 15 additions & 0 deletions packages/react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,21 @@ The player exposes `enqueueChunk(chunk)` for direct callers and `dispose()` for
<ItemsRenderer items={session.items} />
```

`ItemsRenderer` puts that `items` array in scope for nested `useSessionItems()` consumers when no `SessionItemsProvider` is already mounted. An ancestor provider stays in place. `ItemRenderer` does not mount one.

When you render a stream-aware card outside `ItemsRenderer`, mount the provider yourself:

```tsx
import { SessionItemsProvider } from "@flow-state-dev/react";
import { TaskPlan } from "@/components/flow-state/task-plan";

<SessionItemsProvider value={session.items}>
<TaskPlan collectionId="research-board" />
</SessionItemsProvider>
```

`useSessionItems()` returns `[]` when no provider is mounted.

Custom renderers receive `{ item }` as their prop:

```tsx
Expand Down
12 changes: 10 additions & 2 deletions packages/react/src/components/ItemsRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
} from "@flow-state-dev/core/items";
import type { SuspensionStatus } from "@flow-state-dev/core/types";
import { useFlowContext } from "../context/FlowContext";
import { SessionItemsGate } from "../context/SessionItemsContext";
import type { RendererRegistry } from "../registry/block-renderers";
import { ItemRenderer } from "./ItemRenderer";

Expand Down Expand Up @@ -214,8 +215,13 @@ export function buildItemRenderStream(
* When `toolGroupRenderer` is provided, consecutive `tool_output`
* items in the filtered stream render as a single group via the supplied
* component rather than individually.
*
* Mounts a session-items provider with `items` when none is already in
* scope, so container and HITL renderers can call `useSessionItems()`
* under the documented FlowProvider + ItemsRenderer composition. An
* ancestor provider is kept: its list may be a superset of `items`.
*/
export function ItemsRenderer(props: ItemsRendererProps): ReactNode[] {
export function ItemsRenderer(props: ItemsRendererProps): ReactNode {
const { deduplicateByKey = true, showSubAgents = false, toolGroupRenderer } = props;
const { renderers } = useFlowContext();

Expand All @@ -241,7 +247,7 @@ export function ItemsRenderer(props: ItemsRendererProps): ReactNode[] {
}
}

return stream.map((segment, index) => {
const nodes = stream.map((segment, index) => {
if (segment.kind === "group") {
const key = `tool-group-${segment.items[0]?.id ?? index}`;
return createElement(
Expand All @@ -262,4 +268,6 @@ export function ItemsRenderer(props: ItemsRendererProps): ReactNode[] {
}
return createElement(ItemRenderer, { item, key: item.id });
});

return createElement(SessionItemsGate, { value: props.items }, nodes);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using props.items here (not the filtered stream) is the right call—container/HITL hooks need owned snapshots and suspension pairing from the same array you pass in, while SessionItemsGate ensures you do not replace a fuller ancestor list. Worth keeping that invariant obvious in code review because it is easy to “simplify” incorrectly to stream items.

}
76 changes: 76 additions & 0 deletions packages/react/src/context/SessionItemsContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* Session item list for nested stream-aware renderers.
*
* Container and HITL cards (EventedActors, Debate, RoutedSpecialists,
* TaskPlan, Approval) read the current stream via {@link useSessionItems}.
* {@link ItemsRenderer} mounts {@link SessionItemsProvider} with the list it
* is rendering when no provider is already in scope, so the documented
* FlowProvider + ItemsRenderer composition supplies the items without a
* second provider. An ancestor provider is left in place: a caller such as
* RequestGroup passes a filtered subset, and TaskPlan still needs the
* fuller list above it.
*
* Mount {@link SessionItemsProvider} yourself when rendering those cards
* outside {@link ItemsRenderer} (tests, replayed snapshots). TaskPlan also
* accepts an explicit `items` prop for that case.
*/
import {
createContext,
createElement,
useContext,
type ReactNode
} from "react";
import type { OutputItem } from "@flow-state-dev/core/items";

const SessionItemsContext = createContext<OutputItem[] | null>(null);

/**
* Props for {@link SessionItemsProvider}.
*/
export type SessionItemsProviderProps = {
/** Session item list nested renderers should read. */
value: OutputItem[];
children?: ReactNode;
};

/**
* Provides the session item list to {@link useSessionItems} consumers.
*
* {@link ItemsRenderer} mounts this automatically. Wrap a subtree yourself
* only when rendering stream-aware cards outside that helper.
*/
export function SessionItemsProvider(
props: SessionItemsProviderProps
): ReactNode {
return createElement(
SessionItemsContext.Provider,
{ value: props.value },
props.children
);
}

/**
* Reads the nearest session item list, or `[]` when no provider is mounted.
*/
export function useSessionItems(): OutputItem[] {
return useContext(SessionItemsContext) ?? [];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplify (optional): ?? [] creates a new array on every call when no provider is mounted. A shared const EMPTY_ITEMS: OutputItem[] = [] (used only for the missing-provider case) avoids surprising memo deps in misconfigured trees. Not an issue on the happy path where ItemsRenderer or an ancestor provider is present.

Comment on lines +55 to +56

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reuse a stable empty items array

When useSessionItems() is called without a provider, this expression allocates a new array on every render. A consumer that treats the returned list as a dependency—for example, an effect that updates derived state—will observe a change on every render and can enter a render/effect loop even though the item list remains empty; memoized derivations also recompute unnecessarily. Return a shared empty constant or use a stable context default.

Useful? React with 👍 / 👎.

}

/**
* Mounts {@link SessionItemsProvider} only when none is already in scope.
*
* Used by {@link ItemsRenderer}. A filtered `items` prop must not hide a
* fuller list an ancestor already provided.
*/
export function SessionItemsGate(props: {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplify (optional): SessionItemsGate looks like an ItemsRenderer implementation detail. It is not on index.ts, but export function still invites deep imports. Dropping export (or colocating the gate next to ItemsRenderer) would keep the public API to SessionItemsProvider / useSessionItems only.

value: OutputItem[];
children?: ReactNode;
}): ReactNode {
const mounted = useContext(SessionItemsContext) !== null;
if (mounted) return props.children ?? null;
Comment on lines +69 to +70

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Let nested renderers establish their own session scope

When a child or background session's <ItemsRenderer items={child.items}> is nested beneath a provider for the parent session, this presence-only gate keeps the parent's list. Stream-aware renderers in the child then cannot find child-owned container snapshots or suspension-resume items, producing empty or unresolved cards. This is a normal composition for the child-session detail documented in packages/react/README.md; preserve an ancestor only when it represents the same stream, or provide an override for the nested renderer.

Useful? React with 👍 / 👎.

return createElement(
SessionItemsProvider,
{ value: props.value },
props.children
);
}
6 changes: 6 additions & 0 deletions packages/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,12 @@ export {
type FlowProviderProps
} from "./context/FlowContext";

export {
SessionItemsProvider,
useSessionItems,
type SessionItemsProviderProps
} from "./context/SessionItemsContext";

export {
SuspensionResolverProvider,
useSuspensionResolver,
Expand Down
4 changes: 4 additions & 0 deletions packages/react/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ApprovalRenderer,
FlowProvider,
ItemRenderer,
SessionItemsProvider,
coreItemImportProof,
deriveSuspensions,
reactPackageMarker,
Expand All @@ -13,6 +14,7 @@ import {
useClientData,
useRequestStream,
useSession,
useSessionItems,
useSuspensions
} from "../src";

Expand All @@ -36,6 +38,8 @@ describe("@flow-state-dev/react", () => {
it("exports FlowProvider and context helpers", () => {
expect(typeof FlowProvider).toBe("function");
expect(typeof useFlowContext).toBe("function");
expect(typeof SessionItemsProvider).toBe("function");
expect(typeof useSessionItems).toBe("function");
});

it("exports render helpers", () => {
Expand Down
Loading
Loading