@stigmer/react 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/channel/AgentChannelsPanel.d.ts.map +1 -1
  2. package/channel/AgentChannelsPanel.js +21 -2
  3. package/channel/AgentChannelsPanel.js.map +1 -1
  4. package/channel/ChannelConversationsDialog.d.ts +12 -4
  5. package/channel/ChannelConversationsDialog.d.ts.map +1 -1
  6. package/channel/ChannelConversationsDialog.js +18 -24
  7. package/channel/ChannelConversationsDialog.js.map +1 -1
  8. package/channel/providers.d.ts +23 -0
  9. package/channel/providers.d.ts.map +1 -1
  10. package/channel/providers.js +4 -0
  11. package/channel/providers.js.map +1 -1
  12. package/channel/useSaveAgentChannel.d.ts +5 -4
  13. package/channel/useSaveAgentChannel.d.ts.map +1 -1
  14. package/channel/useSaveAgentChannel.js +18 -4
  15. package/channel/useSaveAgentChannel.js.map +1 -1
  16. package/composer/ComposerToolbar.d.ts +1 -1
  17. package/composer/ComposerToolbar.d.ts.map +1 -1
  18. package/composer/SessionComposer.d.ts +1 -1
  19. package/composer/SessionComposer.js +1 -1
  20. package/composer/SessionComposer.js.map +1 -1
  21. package/conversation/ConversationAttentionBanner.d.ts +22 -0
  22. package/conversation/ConversationAttentionBanner.d.ts.map +1 -0
  23. package/conversation/ConversationAttentionBanner.js +25 -0
  24. package/conversation/ConversationAttentionBanner.js.map +1 -0
  25. package/conversation/ConversationComposer.d.ts +41 -0
  26. package/conversation/ConversationComposer.d.ts.map +1 -0
  27. package/conversation/ConversationComposer.js +57 -0
  28. package/conversation/ConversationComposer.js.map +1 -0
  29. package/conversation/ConversationControlBanner.d.ts +52 -0
  30. package/conversation/ConversationControlBanner.d.ts.map +1 -0
  31. package/conversation/ConversationControlBanner.js +59 -0
  32. package/conversation/ConversationControlBanner.js.map +1 -0
  33. package/conversation/ConversationListPane.d.ts +68 -0
  34. package/conversation/ConversationListPane.d.ts.map +1 -0
  35. package/conversation/ConversationListPane.js +120 -0
  36. package/conversation/ConversationListPane.js.map +1 -0
  37. package/conversation/ConversationTimelineView.d.ts +46 -0
  38. package/conversation/ConversationTimelineView.d.ts.map +1 -0
  39. package/conversation/ConversationTimelineView.js +166 -0
  40. package/conversation/ConversationTimelineView.js.map +1 -0
  41. package/conversation/ConversationsWorkbench.d.ts +63 -0
  42. package/conversation/ConversationsWorkbench.d.ts.map +1 -0
  43. package/conversation/ConversationsWorkbench.js +165 -0
  44. package/conversation/ConversationsWorkbench.js.map +1 -0
  45. package/conversation/conversationPresentation.d.ts +137 -0
  46. package/conversation/conversationPresentation.d.ts.map +1 -0
  47. package/conversation/conversationPresentation.js +230 -0
  48. package/conversation/conversationPresentation.js.map +1 -0
  49. package/conversation/index.d.ts +26 -0
  50. package/conversation/index.d.ts.map +1 -0
  51. package/conversation/index.js +14 -0
  52. package/conversation/index.js.map +1 -0
  53. package/conversation/polling.d.ts +39 -0
  54. package/conversation/polling.d.ts.map +1 -0
  55. package/conversation/polling.js +39 -0
  56. package/conversation/polling.js.map +1 -0
  57. package/conversation/useConversation.d.ts +61 -0
  58. package/conversation/useConversation.d.ts.map +1 -0
  59. package/conversation/useConversation.js +153 -0
  60. package/conversation/useConversation.js.map +1 -0
  61. package/conversation/useConversationList.d.ts +98 -0
  62. package/conversation/useConversationList.d.ts.map +1 -0
  63. package/conversation/useConversationList.js +200 -0
  64. package/conversation/useConversationList.js.map +1 -0
  65. package/conversation/useConversationParticipation.d.ts +63 -0
  66. package/conversation/useConversationParticipation.d.ts.map +1 -0
  67. package/conversation/useConversationParticipation.js +84 -0
  68. package/conversation/useConversationParticipation.js.map +1 -0
  69. package/conversation/useConversationTimeline.d.ts +71 -0
  70. package/conversation/useConversationTimeline.d.ts.map +1 -0
  71. package/conversation/useConversationTimeline.js +152 -0
  72. package/conversation/useConversationTimeline.js.map +1 -0
  73. package/conversation/useConversationsWantsHumanCount.d.ts +42 -0
  74. package/conversation/useConversationsWantsHumanCount.d.ts.map +1 -0
  75. package/conversation/useConversationsWantsHumanCount.js +40 -0
  76. package/conversation/useConversationsWantsHumanCount.js.map +1 -0
  77. package/index.d.ts +4 -0
  78. package/index.d.ts.map +1 -1
  79. package/index.js +8 -0
  80. package/index.js.map +1 -1
  81. package/internal/tooltip.d.ts.map +1 -1
  82. package/internal/tooltip.js +7 -1
  83. package/internal/tooltip.js.map +1 -1
  84. package/internal/useAutoScroll.d.ts +25 -4
  85. package/internal/useAutoScroll.d.ts.map +1 -1
  86. package/internal/useAutoScroll.js +55 -15
  87. package/internal/useAutoScroll.js.map +1 -1
  88. package/internal/useFetch.d.ts.map +1 -1
  89. package/internal/useFetch.js +14 -4
  90. package/internal/useFetch.js.map +1 -1
  91. package/models/ModelSelector.d.ts +24 -5
  92. package/models/ModelSelector.d.ts.map +1 -1
  93. package/models/ModelSelector.js +31 -9
  94. package/models/ModelSelector.js.map +1 -1
  95. package/models/registry.d.ts +3 -2
  96. package/models/registry.d.ts.map +1 -1
  97. package/models/registry.js.map +1 -1
  98. package/models/service-tier.d.ts +1 -1
  99. package/models/service-tier.d.ts.map +1 -1
  100. package/models/service-tier.js +1 -1
  101. package/models/service-tier.js.map +1 -1
  102. package/package.json +4 -4
  103. package/schedule/ScheduleDetailView.js +1 -1
  104. package/schedule/ScheduleDetailView.js.map +1 -1
  105. package/schedule/ScheduleForm.d.ts.map +1 -1
  106. package/schedule/ScheduleForm.js +7 -6
  107. package/schedule/ScheduleForm.js.map +1 -1
  108. package/sharing/useSaveAgentShare.d.ts +10 -1
  109. package/sharing/useSaveAgentShare.d.ts.map +1 -1
  110. package/sharing/useSaveAgentShare.js +9 -0
  111. package/sharing/useSaveAgentShare.js.map +1 -1
  112. package/sidebar/WorkspaceSidebar.d.ts +12 -4
  113. package/sidebar/WorkspaceSidebar.d.ts.map +1 -1
  114. package/sidebar/WorkspaceSidebar.js +19 -7
  115. package/sidebar/WorkspaceSidebar.js.map +1 -1
  116. package/src/channel/AgentChannelsPanel.tsx +33 -2
  117. package/src/channel/ChannelConversationsDialog.tsx +22 -25
  118. package/src/channel/__tests__/AgentChannelsPanel.test.tsx +36 -5
  119. package/src/channel/__tests__/ChannelConversationsDialog.test.tsx +38 -1
  120. package/src/channel/__tests__/useSaveAgentChannel.test.tsx +26 -0
  121. package/src/channel/providers.ts +27 -0
  122. package/src/channel/useSaveAgentChannel.ts +18 -4
  123. package/src/composer/ComposerToolbar.tsx +1 -1
  124. package/src/composer/SessionComposer.tsx +2 -2
  125. package/src/composer/__tests__/SessionComposer-serviceTier.test.tsx +4 -3
  126. package/src/conversation/ConversationAttentionBanner.tsx +77 -0
  127. package/src/conversation/ConversationComposer.tsx +156 -0
  128. package/src/conversation/ConversationControlBanner.tsx +193 -0
  129. package/src/conversation/ConversationListPane.tsx +459 -0
  130. package/src/conversation/ConversationTimelineView.tsx +435 -0
  131. package/src/conversation/ConversationsWorkbench.tsx +378 -0
  132. package/src/conversation/__tests__/ConversationAttentionBanner.test.tsx +82 -0
  133. package/src/conversation/__tests__/ConversationComposer.test.tsx +160 -0
  134. package/src/conversation/__tests__/ConversationControlBanner.test.tsx +190 -0
  135. package/src/conversation/__tests__/ConversationListPane.test.tsx +372 -0
  136. package/src/conversation/__tests__/ConversationTimelineView.layout.test.tsx +160 -0
  137. package/src/conversation/__tests__/ConversationTimelineView.test.tsx +405 -0
  138. package/src/conversation/__tests__/ConversationsWorkbench.test.tsx +860 -0
  139. package/src/conversation/__tests__/a11y/conversation-surfaces.a11y.test.tsx +235 -0
  140. package/src/conversation/__tests__/a11y/harness.tsx +100 -0
  141. package/src/conversation/__tests__/conversation-tooltips.layout.test.tsx +167 -0
  142. package/src/conversation/__tests__/conversationPollingComposition.test.tsx +138 -0
  143. package/src/conversation/__tests__/conversationPresentation.test.ts +289 -0
  144. package/src/conversation/__tests__/useConversation.test.tsx +243 -0
  145. package/src/conversation/__tests__/useConversationList.test.tsx +492 -0
  146. package/src/conversation/__tests__/useConversationParticipation.test.tsx +190 -0
  147. package/src/conversation/__tests__/useConversationTimeline.test.tsx +258 -0
  148. package/src/conversation/__tests__/useConversationsWantsHumanCount.test.tsx +102 -0
  149. package/src/conversation/conversationPresentation.ts +305 -0
  150. package/src/conversation/index.ts +80 -0
  151. package/src/conversation/polling.ts +41 -0
  152. package/src/conversation/useConversation.ts +221 -0
  153. package/src/conversation/useConversationList.ts +328 -0
  154. package/src/conversation/useConversationParticipation.ts +178 -0
  155. package/src/conversation/useConversationTimeline.ts +244 -0
  156. package/src/conversation/useConversationsWantsHumanCount.ts +86 -0
  157. package/src/index.ts +67 -0
  158. package/src/internal/__tests__/fake-timer-slices.ts +29 -0
  159. package/src/internal/__tests__/useAutoScroll.layout.test.tsx +143 -0
  160. package/src/internal/__tests__/useAutoScroll.test.tsx +62 -5
  161. package/src/internal/__tests__/useFetch-poll-under-render-pressure.test.tsx +79 -0
  162. package/src/internal/tooltip.tsx +6 -1
  163. package/src/internal/useAutoScroll.ts +66 -20
  164. package/src/internal/useFetch.ts +15 -4
  165. package/src/models/ModelSelector.tsx +81 -49
  166. package/src/models/__tests__/ModelSelector-serviceTier.test.tsx +105 -21
  167. package/src/models/registry.ts +3 -2
  168. package/src/models/service-tier.ts +1 -1
  169. package/src/schedule/ScheduleDetailView.tsx +1 -1
  170. package/src/schedule/ScheduleForm.tsx +7 -6
  171. package/src/schedule/__tests__/scheduleCreation.test.tsx +2 -2
  172. package/src/sharing/__tests__/useSaveAgentShare.test.tsx +55 -1
  173. package/src/sharing/__tests__/useShareToolReadiness.test.tsx +1 -0
  174. package/src/sharing/useSaveAgentShare.ts +19 -1
  175. package/src/sidebar/WorkspaceSidebar.tsx +62 -3
  176. package/src/sidebar/__tests__/WorkspaceSidebar.test.tsx +56 -1
  177. package/styles.css +1 -1
@@ -0,0 +1,178 @@
1
+ "use client";
2
+
3
+ import { create } from "@bufbuild/protobuf";
4
+ import type {
5
+ ChannelConversation,
6
+ } from "@stigmer/protos/ai/stigmer/agentic/agentchannel/v1/conversation_io_pb";
7
+ import {
8
+ ConversationControlInputSchema,
9
+ GetChannelConversationInputSchema,
10
+ ReplyToConversationInputSchema,
11
+ } from "@stigmer/protos/ai/stigmer/agentic/agentchannel/v1/conversation_io_pb";
12
+ import type { SendChannelMessageOutput } from "@stigmer/protos/ai/stigmer/agentic/agentchannel/v1/message_io_pb";
13
+ import { useCallback, useMemo } from "react";
14
+ import { useStigmer } from "../hooks.js";
15
+ import { useKeyedSubmission } from "../internal/useKeyedSubmission.js";
16
+
17
+ /** The four staff-facing participation commands. */
18
+ export type ConversationCommand = "reply" | "takeOver" | "handBack" | "clearAttention";
19
+
20
+ /** Options for {@link useConversationParticipation}. */
21
+ export interface UseConversationParticipationOptions {
22
+ /** AgentChannel the conversation belongs to. */
23
+ readonly agentChannelId: string;
24
+ /** Conversation key within the channel. */
25
+ readonly conversationKey: string;
26
+ /**
27
+ * Receives the fresh conversation row every command answers with —
28
+ * wire it to {@link useConversation}'s `applyServerState` so banners
29
+ * and controls adopt server truth immediately. Called for reply too
30
+ * (via a follow-up row read): a staff reply implicitly takes over
31
+ * BEFORE the send, unconditionally, so control has moved even when
32
+ * the send itself was refused.
33
+ */
34
+ readonly onConversation?: (fresh: ChannelConversation) => void;
35
+ }
36
+
37
+ /** Return value of {@link useConversationParticipation}. */
38
+ export interface UseConversationParticipationReturn {
39
+ /**
40
+ * Send a staff text reply. Resolves with the truthful outcome of the
41
+ * inline attempt: `accepted` (with `outboundMessageId` — the item will
42
+ * appear on the timeline as `ob:<that id>`), `queued`, or `refused`.
43
+ * A `refused` outcome WITHOUT an `outboundMessageId` left no ledger
44
+ * row and no timeline item will ever exist for it.
45
+ */
46
+ readonly reply: (text: string) => Promise<SendChannelMessageOutput>;
47
+ /**
48
+ * Take the conversation over: the agent goes quiet until handBack.
49
+ * Resolves with the fresh row — for the LOSER of a concurrent
50
+ * takeover too (success-with-the-winner's-state, never an error), so
51
+ * compare `controlledBy` against the caller rather than assuming the
52
+ * transition won.
53
+ */
54
+ readonly takeOver: () => Promise<ChannelConversation>;
55
+ /** Hand the conversation back to the agent. */
56
+ readonly handBack: () => Promise<ChannelConversation>;
57
+ /** Dismiss the needs-attention flag in place; control is untouched. */
58
+ readonly clearAttention: () => Promise<ChannelConversation>;
59
+ /** Commands currently in flight. */
60
+ readonly pendingCommands: ReadonlySet<ConversationCommand>;
61
+ /** Per-command failures, cleared when that command is retried. */
62
+ readonly commandErrors: ReadonlyMap<ConversationCommand, Error>;
63
+ /** Reset every recorded command error. */
64
+ readonly clearErrors: () => void;
65
+ }
66
+
67
+ /**
68
+ * Behavior hook for the participation commands on one conversation
69
+ * (channel-conversations DD-005/DD-007/DD-008/DD-009): reply, takeOver,
70
+ * handBack, clearAttention — each keyed independently so a slow reply
71
+ * and a takeover can be in flight at once with attributable spinners
72
+ * and errors.
73
+ *
74
+ * Every command re-throws its failure after recording it in
75
+ * {@link UseConversationParticipationReturn.commandErrors}, so callers
76
+ * choose the propagation (await-and-toast, or ignore and render the
77
+ * keyed error inline).
78
+ */
79
+ export function useConversationParticipation(
80
+ options: UseConversationParticipationOptions,
81
+ ): UseConversationParticipationReturn {
82
+ const { agentChannelId, conversationKey, onConversation } = options;
83
+ const stigmer = useStigmer();
84
+ const submission = useKeyedSubmission<unknown>();
85
+ const { run } = submission;
86
+
87
+ const controlInput = useCallback(
88
+ () => create(ConversationControlInputSchema, { agentChannelId, conversationKey }),
89
+ [agentChannelId, conversationKey],
90
+ );
91
+
92
+ const takeOver = useCallback(
93
+ () =>
94
+ run("takeOver", async () => {
95
+ const fresh = await stigmer.agentChannel.takeOver(controlInput());
96
+ onConversation?.(fresh);
97
+ return fresh;
98
+ }) as Promise<ChannelConversation>,
99
+ [run, stigmer, controlInput, onConversation],
100
+ );
101
+
102
+ const handBack = useCallback(
103
+ () =>
104
+ run("handBack", async () => {
105
+ const fresh = await stigmer.agentChannel.handBack(controlInput());
106
+ onConversation?.(fresh);
107
+ return fresh;
108
+ }) as Promise<ChannelConversation>,
109
+ [run, stigmer, controlInput, onConversation],
110
+ );
111
+
112
+ const clearAttention = useCallback(
113
+ () =>
114
+ run("clearAttention", async () => {
115
+ const fresh = await stigmer.agentChannel.clearAttention(controlInput());
116
+ onConversation?.(fresh);
117
+ return fresh;
118
+ }) as Promise<ChannelConversation>,
119
+ [run, stigmer, controlInput, onConversation],
120
+ );
121
+
122
+ const reply = useCallback(
123
+ (text: string) =>
124
+ run("reply", async () => {
125
+ const output = await stigmer.agentChannel.reply(
126
+ create(ReplyToConversationInputSchema, {
127
+ agentChannelId,
128
+ conversationKey,
129
+ payload: { kind: { case: "text", value: { body: text } } },
130
+ }),
131
+ );
132
+ // The implicit takeover flipped control BEFORE the send ran —
133
+ // even a refused reply moved it — but reply answers the send
134
+ // outcome, not the row. One follow-up read keeps the control
135
+ // banner honest without waiting a poll tick. Best-effort: a
136
+ // failed read only delays the banner until the next poll.
137
+ if (onConversation) {
138
+ try {
139
+ onConversation(
140
+ await stigmer.agentChannel.getConversation(
141
+ create(GetChannelConversationInputSchema, {
142
+ agentChannelId,
143
+ conversationKey,
144
+ }),
145
+ ),
146
+ );
147
+ } catch {
148
+ // The reply itself succeeded; the poll will catch the row up.
149
+ }
150
+ }
151
+ return output;
152
+ }) as Promise<SendChannelMessageOutput>,
153
+ [run, stigmer, agentChannelId, conversationKey, onConversation],
154
+ );
155
+
156
+ return useMemo(
157
+ () => ({
158
+ reply,
159
+ takeOver,
160
+ handBack,
161
+ clearAttention,
162
+ // The submission primitive keys by string; this hook only ever
163
+ // submits the four command names, so the narrowing is sound.
164
+ pendingCommands: submission.submittingKeys as ReadonlySet<ConversationCommand>,
165
+ commandErrors: submission.errorsByKey as ReadonlyMap<ConversationCommand, Error>,
166
+ clearErrors: submission.clearErrors,
167
+ }),
168
+ [
169
+ reply,
170
+ takeOver,
171
+ handBack,
172
+ clearAttention,
173
+ submission.submittingKeys,
174
+ submission.errorsByKey,
175
+ submission.clearErrors,
176
+ ],
177
+ );
178
+ }
@@ -0,0 +1,244 @@
1
+ "use client";
2
+
3
+ import { create, equals } from "@bufbuild/protobuf";
4
+ import type { ConversationTimelineItem } from "@stigmer/protos/ai/stigmer/agentic/agentchannel/v1/conversation_io_pb";
5
+ import {
6
+ ConversationTimelineItemSchema,
7
+ GetConversationTimelineInputSchema,
8
+ } from "@stigmer/protos/ai/stigmer/agentic/agentchannel/v1/conversation_io_pb";
9
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
10
+ import { useStigmer } from "../hooks.js";
11
+ import { toError } from "../internal/toError.js";
12
+ import { useFetch } from "../internal/useFetch.js";
13
+ import { compareTimelineItemsNewestFirst } from "./conversationPresentation.js";
14
+ import { CONVERSATION_DETAIL_POLL_INTERVAL_MS } from "./polling.js";
15
+
16
+ /** Options for {@link useConversationTimeline}. */
17
+ export interface UseConversationTimelineOptions {
18
+ /** Items per page, for the polled head and each loadOlder page. Default 50. */
19
+ readonly pageSize?: number;
20
+ /**
21
+ * Poll interval in milliseconds; `false` disables polling. Defaults to
22
+ * {@link CONVERSATION_DETAIL_POLL_INTERVAL_MS}. Only the head page
23
+ * polls — it is where new items land and where recent items' delivery
24
+ * and receipt states still move.
25
+ */
26
+ readonly refetchIntervalMs?: number | false;
27
+ }
28
+
29
+ /** Return value of {@link useConversationTimeline}. */
30
+ export interface UseConversationTimelineReturn {
31
+ /**
32
+ * Every item seen so far, in chronological (oldest → newest) order —
33
+ * the render order of a chat view. Items are never dropped: the polled
34
+ * head window may shift as new messages land, and an item that slides
35
+ * out of it stays here rather than vanishing mid-scroll.
36
+ */
37
+ readonly items: readonly ConversationTimelineItem[];
38
+ /**
39
+ * `true` while older history exists beyond what is loaded. Decided
40
+ * ONLY by the server's cursor — a short page mid-history is normal
41
+ * (same-second bursts narrow pages) and never means the end.
42
+ */
43
+ readonly hasOlder: boolean;
44
+ /** Load the next older page. No-op while one is already loading. */
45
+ readonly loadOlder: () => void;
46
+ /** `true` while a loadOlder page is in flight. */
47
+ readonly isLoadingOlder: boolean;
48
+ /** Error from the last failed loadOlder, or `null`. Cleared on retry. */
49
+ readonly loadOlderError: Error | null;
50
+ /** `true` only during the first head-page load. */
51
+ readonly isLoading: boolean;
52
+ /** `true` while the head page refreshes in the background. */
53
+ readonly isRefetching: boolean;
54
+ /** Error from the last failed head-page fetch, or `null`. */
55
+ readonly error: Error | null;
56
+ /** Re-fetch the head page. */
57
+ readonly refetch: () => void;
58
+ }
59
+
60
+ interface HeadPage {
61
+ readonly items: readonly ConversationTimelineItem[];
62
+ readonly nextPageToken: string;
63
+ }
64
+
65
+ const EMPTY_HEAD: HeadPage = { items: [], nextPageToken: "" };
66
+
67
+ /**
68
+ * Data hook for one conversation's customer-visible timeline
69
+ * (channel-conversations DD-004): newest-first cursor pages from the
70
+ * server, accumulated into one chronological list for a chat view.
71
+ *
72
+ * The accumulation is an UPSERT by `item_id`, not head/tail
73
+ * concatenation, for two verified server behaviors:
74
+ *
75
+ * - Item instants are stable but STATUSES mutate in place — an outbound
76
+ * item's delivery status and receipt ticks advance after it first
77
+ * renders. Each head poll re-upserts the newest window, so those
78
+ * fields stay live without any diffing protocol.
79
+ * - The head window SHIFTS as new items land. Items that slide out of
80
+ * it are not in any loaded older page (older cursors are anchored
81
+ * below the original head), so concatenation would silently drop
82
+ * them; the upsert map keeps everything ever seen.
83
+ *
84
+ * The older cursor is captured from the FIRST head page only: later
85
+ * head refreshes serve the top of the timeline, while the cursor tracks
86
+ * how deep into history the consumer has scrolled — two independent
87
+ * frontiers. Receipt ticks on items deeper than the head window can go
88
+ * stale until the conversation is reopened; accepted for v1 (the T05
89
+ * liveness seam is where per-item freshness lands).
90
+ *
91
+ * Pass empty strings to skip fetching (the `null`-fetchFn convention).
92
+ */
93
+ export function useConversationTimeline(
94
+ agentChannelId: string,
95
+ conversationKey: string,
96
+ options?: UseConversationTimelineOptions,
97
+ ): UseConversationTimelineReturn {
98
+ const pageSize = options?.pageSize ?? 50;
99
+ const refetchIntervalMs =
100
+ options?.refetchIntervalMs ?? CONVERSATION_DETAIL_POLL_INTERVAL_MS;
101
+ const stigmer = useStigmer();
102
+
103
+ const enabled = agentChannelId !== "" && conversationKey !== "";
104
+
105
+ const fetchFn = enabled
106
+ ? async (): Promise<HeadPage> => {
107
+ const result = await stigmer.agentChannel.getTimeline(
108
+ create(GetConversationTimelineInputSchema, {
109
+ agentChannelId,
110
+ conversationKey,
111
+ pageSize,
112
+ }),
113
+ );
114
+ return { items: result.items, nextPageToken: result.nextPageToken };
115
+ }
116
+ : null;
117
+
118
+ const {
119
+ data: head,
120
+ isLoading,
121
+ isRefetching,
122
+ error,
123
+ refetch,
124
+ } = useFetch(fetchFn, [agentChannelId, conversationKey, pageSize, stigmer], EMPTY_HEAD, {
125
+ refetchInterval: refetchIntervalMs,
126
+ // DD-012 D-a: returning to the tab is fresh (the head re-upserts, so
127
+ // a focus refetch can never disturb accumulated history).
128
+ refetchOnWindowFocus: true,
129
+ });
130
+
131
+ // Everything ever seen for this conversation, by item id.
132
+ const [known, setKnown] = useState<ReadonlyMap<string, ConversationTimelineItem>>(
133
+ new Map(),
134
+ );
135
+ // The older-history frontier: null until the first head page answers,
136
+ // "" once history is exhausted, otherwise the next older cursor.
137
+ const [olderCursor, setOlderCursor] = useState<string | null>(null);
138
+ const [isLoadingOlder, setIsLoadingOlder] = useState(false);
139
+ const [loadOlderError, setLoadOlderError] = useState<Error | null>(null);
140
+ const epochRef = useRef(0);
141
+
142
+ useEffect(() => {
143
+ epochRef.current += 1;
144
+ setKnown(new Map());
145
+ setOlderCursor(null);
146
+ setIsLoadingOlder(false);
147
+ setLoadOlderError(null);
148
+ }, [agentChannelId, conversationKey, pageSize, stigmer]);
149
+
150
+ // Fold each head page into the map. `head` is referentially fresh per
151
+ // fetch, so this runs exactly once per answer.
152
+ useEffect(() => {
153
+ if (head === EMPTY_HEAD) return;
154
+ setKnown((current) => upsert(current, head.items));
155
+ setOlderCursor((current) => (current === null ? head.nextPageToken : current));
156
+ }, [head]);
157
+
158
+ const loadOlder = useCallback(() => {
159
+ if (!enabled || isLoadingOlder || !olderCursor) return;
160
+ const epoch = epochRef.current;
161
+ setIsLoadingOlder(true);
162
+ setLoadOlderError(null);
163
+
164
+ stigmer.agentChannel
165
+ .getTimeline(
166
+ create(GetConversationTimelineInputSchema, {
167
+ agentChannelId,
168
+ conversationKey,
169
+ pageSize,
170
+ pageToken: olderCursor,
171
+ }),
172
+ )
173
+ .then(
174
+ (result) => {
175
+ if (epochRef.current !== epoch) return;
176
+ setKnown((current) => upsert(current, result.items));
177
+ setOlderCursor(result.nextPageToken);
178
+ setIsLoadingOlder(false);
179
+ },
180
+ (err) => {
181
+ if (epochRef.current !== epoch) return;
182
+ setLoadOlderError(toError(err));
183
+ setIsLoadingOlder(false);
184
+ },
185
+ );
186
+ }, [enabled, isLoadingOlder, olderCursor, agentChannelId, conversationKey, pageSize, stigmer]);
187
+
188
+ const items = useMemo(
189
+ () =>
190
+ Array.from(known.values())
191
+ .sort(compareTimelineItemsNewestFirst)
192
+ .reverse(),
193
+ [known],
194
+ );
195
+
196
+ const hasOlder = olderCursor !== null && olderCursor !== "";
197
+
198
+ return useMemo(
199
+ () => ({
200
+ items,
201
+ hasOlder,
202
+ loadOlder,
203
+ isLoadingOlder,
204
+ loadOlderError,
205
+ isLoading,
206
+ isRefetching,
207
+ error,
208
+ refetch,
209
+ }),
210
+ [
211
+ items,
212
+ hasOlder,
213
+ loadOlder,
214
+ isLoadingOlder,
215
+ loadOlderError,
216
+ isLoading,
217
+ isRefetching,
218
+ error,
219
+ refetch,
220
+ ],
221
+ );
222
+ }
223
+
224
+ /**
225
+ * Fold a page into the map, preserving references: a poll returns fresh
226
+ * proto objects even when nothing changed, and swapping equal items
227
+ * would defeat `React.memo` on every row every poll tick (DD-010 —
228
+ * reference stability is architectural, not an optimization). An
229
+ * unchanged page returns the SAME map, so the sorted `items` memo does
230
+ * not even re-run.
231
+ */
232
+ function upsert(
233
+ current: ReadonlyMap<string, ConversationTimelineItem>,
234
+ incoming: readonly ConversationTimelineItem[],
235
+ ): ReadonlyMap<string, ConversationTimelineItem> {
236
+ let next: Map<string, ConversationTimelineItem> | null = null;
237
+ for (const item of incoming) {
238
+ const existing = current.get(item.itemId);
239
+ if (existing && equals(ConversationTimelineItemSchema, existing, item)) continue;
240
+ next ??= new Map(current);
241
+ next.set(item.itemId, item);
242
+ }
243
+ return next ?? current;
244
+ }
@@ -0,0 +1,86 @@
1
+ "use client";
2
+
3
+ import { create } from "@bufbuild/protobuf";
4
+ import {
5
+ ChannelConversationListFilter,
6
+ ListChannelConversationsInputSchema,
7
+ } from "@stigmer/protos/ai/stigmer/agentic/agentchannel/v1/conversation_io_pb";
8
+ import { useMemo } from "react";
9
+ import { useStigmer } from "../hooks.js";
10
+ import { useFetch } from "../internal/useFetch.js";
11
+ import { CONVERSATION_BADGE_POLL_INTERVAL_MS } from "./polling.js";
12
+
13
+ /** Options for {@link useConversationsWantsHumanCount}. */
14
+ export interface UseConversationsWantsHumanCountOptions {
15
+ /**
16
+ * Poll interval in milliseconds; `false` disables polling. Defaults to
17
+ * {@link CONVERSATION_BADGE_POLL_INTERVAL_MS} — deliberately the
18
+ * slowest budget on the conversation surface (DD-012 D-b): a badge
19
+ * tolerates staleness an open inbox does not, and it renders on every
20
+ * console page in every tab.
21
+ */
22
+ readonly refetchIntervalMs?: number | false;
23
+ }
24
+
25
+ /** Return value of {@link useConversationsWantsHumanCount}. */
26
+ export interface UseConversationsWantsHumanCountReturn {
27
+ /**
28
+ * Conversations where a human action is wanted:
29
+ * `needs_attention OR (awaiting_reply AND human-held)` — the two ways
30
+ * a conversation can be blocked on a person (the agent asked for one,
31
+ * or a human took over and the customer wrote). `0` until the first
32
+ * answer.
33
+ */
34
+ readonly count: number;
35
+ /** `true` only until the first answer arrives. */
36
+ readonly isLoading: boolean;
37
+ /** Error from the last failed read, or `null`. */
38
+ readonly error: Error | null;
39
+ /** Imperatively re-read the count. */
40
+ readonly refetch: () => void;
41
+ }
42
+
43
+ /**
44
+ * Data hook for the sidebar's Conversations badge (channel-conversations
45
+ * DD-011 D-f): how many conversations want a human right now, org-wide.
46
+ *
47
+ * The count IS the filtered list's `total_count` — one page-size-1 read
48
+ * with `filter_wants_human`, zero dedicated RPCs (DD-011 D-g). Because
49
+ * the badge and the wants-human list filter share one server-side
50
+ * predicate, the number shown and the list it leads to can never
51
+ * disagree.
52
+ *
53
+ * Pass `null` to skip fetching (no active org).
54
+ */
55
+ export function useConversationsWantsHumanCount(
56
+ org: string | null,
57
+ options?: UseConversationsWantsHumanCountOptions,
58
+ ): UseConversationsWantsHumanCountReturn {
59
+ const stigmer = useStigmer();
60
+ const refetchIntervalMs =
61
+ options?.refetchIntervalMs ?? CONVERSATION_BADGE_POLL_INTERVAL_MS;
62
+
63
+ const fetchFn = org
64
+ ? async (): Promise<number> => {
65
+ const result = await stigmer.agentChannel.listConversations(
66
+ create(ListChannelConversationsInputSchema, {
67
+ org,
68
+ filter: ChannelConversationListFilter.filter_wants_human,
69
+ pageInfo: { num: 1, size: 1 },
70
+ }),
71
+ );
72
+ return result.totalCount;
73
+ }
74
+ : null;
75
+
76
+ const { data, isLoading, error, refetch } = useFetch(fetchFn, [org, stigmer], 0, {
77
+ refetchInterval: refetchIntervalMs,
78
+ // DD-012 D-a: returning to the tab is fresh.
79
+ refetchOnWindowFocus: true,
80
+ });
81
+
82
+ return useMemo(
83
+ () => ({ count: data, isLoading, error, refetch }),
84
+ [data, isLoading, error, refetch],
85
+ );
86
+ }
package/src/index.ts CHANGED
@@ -1356,6 +1356,73 @@ export type {
1356
1356
  ChannelTemplatesDialogProps,
1357
1357
  } from "./channel/index.js";
1358
1358
 
1359
+ // Conversation — the channel conversation surface (channel-conversations
1360
+ // T04): the org-wide list, one conversation's row and timeline, the
1361
+ // participation commands (reply / takeOver / handBack / clearAttention),
1362
+ // and the pure render vocabulary shared by every conversation view.
1363
+ export {
1364
+ ConversationsWorkbench,
1365
+ ConversationListPane,
1366
+ ConversationTimelineView,
1367
+ ConversationControlBanner,
1368
+ ConversationAttentionBanner,
1369
+ ConversationComposer,
1370
+ useConversation,
1371
+ useConversationList,
1372
+ useConversationTimeline,
1373
+ useConversationParticipation,
1374
+ useConversationsWantsHumanCount,
1375
+ authorKindOf,
1376
+ awaitingIndicatorOf,
1377
+ compareTimelineItemsNewestFirst,
1378
+ conversationContactOf,
1379
+ conversationLabelOf,
1380
+ inboundPlaceholderOf,
1381
+ isInternalItem,
1382
+ receiptOf,
1383
+ sendAttemptOf,
1384
+ serviceWindowOf,
1385
+ CONVERSATION_BADGE_POLL_INTERVAL_MS,
1386
+ CONVERSATION_DETAIL_POLL_INTERVAL_MS,
1387
+ CONVERSATION_LIST_POLL_INTERVAL_MS,
1388
+ } from "./conversation/index.js";
1389
+ export type {
1390
+ ConversationsWorkbenchProps,
1391
+ ConversationHeaderContext,
1392
+ ConversationIdentity,
1393
+ ConversationListPaneProps,
1394
+ ConversationTimelineViewProps,
1395
+ ConversationControlBannerProps,
1396
+ ConversationAttentionBannerProps,
1397
+ ConversationComposerProps,
1398
+ UseConversationOptions,
1399
+ UseConversationReturn,
1400
+ UseConversationListOptions,
1401
+ UseConversationListReturn,
1402
+ UseConversationTimelineOptions,
1403
+ UseConversationTimelineReturn,
1404
+ ConversationCommand,
1405
+ UseConversationParticipationOptions,
1406
+ UseConversationParticipationReturn,
1407
+ UseConversationsWantsHumanCountOptions,
1408
+ UseConversationsWantsHumanCountReturn,
1409
+ AwaitingIndicator,
1410
+ ConversationAuthorKind,
1411
+ ReceiptKind,
1412
+ SendAttemptKind,
1413
+ ServiceWindowState,
1414
+ } from "./conversation/index.js";
1415
+ // Wire types the conversation hooks answer with (DD-007: generated types
1416
+ // are the source of truth — re-exported for consumer convenience).
1417
+ export {
1418
+ ChannelConversationListFilter,
1419
+ ConversationControl,
1420
+ } from "@stigmer/protos/ai/stigmer/agentic/agentchannel/v1/conversation_io_pb";
1421
+ export type {
1422
+ ChannelConversation,
1423
+ ConversationTimelineItem,
1424
+ } from "@stigmer/protos/ai/stigmer/agentic/agentchannel/v1/conversation_io_pb";
1425
+
1359
1426
  // Error — structured error display with classification, retry, and contextual guidance
1360
1427
  export { ErrorMessage, SecretFlowErrorGuide, isSecretFlowError } from "./error/index.js";
1361
1428
  export type { ErrorMessageProps, SecretFlowErrorGuideProps } from "./error/index.js";
@@ -0,0 +1,29 @@
1
+ import { act } from "@testing-library/react";
2
+ import { vi } from "vitest";
3
+
4
+ /**
5
+ * Advance fake time in small slices with an `act` boundary per slice.
6
+ *
7
+ * A single long `advanceTimersByTimeAsync` inside one `act` coalesces
8
+ * every React commit to the END of the block: no re-render lands
9
+ * between timer callbacks, and state updates queued by multiple timer
10
+ * ticks collapse into one commit. Any test about how timers and renders
11
+ * INTERLEAVE (poll phase stability, render-pressure starvation, data
12
+ * arriving "on the next poll tick") silently measures nothing under a
13
+ * single long advance. Slicing lets React commit between timer steps,
14
+ * the way real time does in production.
15
+ *
16
+ * Not a `.test` file and inside `__tests__` deliberately: vitest does
17
+ * not collect it, and the build/typedoc excludes keep it out of the
18
+ * published package.
19
+ */
20
+ export async function advanceInSlices(
21
+ totalMs: number,
22
+ sliceMs = 100,
23
+ ): Promise<void> {
24
+ for (let elapsed = 0; elapsed < totalMs; elapsed += sliceMs) {
25
+ await act(async () => {
26
+ await vi.advanceTimersByTimeAsync(sliceMs);
27
+ });
28
+ }
29
+ }