@athenaintel/react 0.53.1 → 0.55.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 (196) hide show
  1. package/README.md +37 -1
  2. package/dist/agent-runtime/src/call-recap.cjs +2 -3
  3. package/dist/agent-runtime/src/call-recap.cjs.map +1 -1
  4. package/dist/agent-runtime/src/call-recap.d.ts +1 -2
  5. package/dist/agent-runtime/src/call-recap.js +1 -2
  6. package/dist/agent-runtime/src/call-recap.js.map +1 -1
  7. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +7 -3
  8. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
  9. package/dist/agent-runtime/src/deep-agent-transport-recipe.d.ts +10 -2
  10. package/dist/agent-runtime/src/deep-agent-transport-recipe.js +8 -4
  11. package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
  12. package/dist/agent-runtime/src/dictation-session.d.ts +158 -0
  13. package/dist/agent-runtime/src/edit-command.cjs +15 -3
  14. package/dist/agent-runtime/src/edit-command.cjs.map +1 -1
  15. package/dist/agent-runtime/src/edit-command.d.ts +8 -0
  16. package/dist/agent-runtime/src/edit-command.js +15 -3
  17. package/dist/agent-runtime/src/edit-command.js.map +1 -1
  18. package/dist/agent-runtime/src/generated/runconfig-contract.cjs +10 -0
  19. package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
  20. package/dist/agent-runtime/src/generated/runconfig-contract.d.ts +25 -1
  21. package/dist/agent-runtime/src/generated/runconfig-contract.js +10 -0
  22. package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
  23. package/dist/agent-runtime/src/history-pages.cjs +279 -0
  24. package/dist/agent-runtime/src/history-pages.cjs.map +1 -0
  25. package/dist/agent-runtime/src/history-pages.d.ts +252 -0
  26. package/dist/agent-runtime/src/history-pages.js +279 -0
  27. package/dist/agent-runtime/src/history-pages.js.map +1 -0
  28. package/dist/agent-runtime/src/index.d.ts +8 -7
  29. package/dist/agent-runtime/src/message-window.cjs +111 -7
  30. package/dist/agent-runtime/src/message-window.cjs.map +1 -1
  31. package/dist/agent-runtime/src/message-window.d.ts +66 -6
  32. package/dist/agent-runtime/src/message-window.js +112 -8
  33. package/dist/agent-runtime/src/message-window.js.map +1 -1
  34. package/dist/agent-runtime/src/offline-status.cjs.map +1 -1
  35. package/dist/agent-runtime/src/offline-status.d.ts +64 -2
  36. package/dist/agent-runtime/src/offline-status.js.map +1 -1
  37. package/dist/agent-runtime/src/runtime.d.ts +4 -3
  38. package/dist/agent-runtime/src/subagent-transcripts.cjs +23 -1
  39. package/dist/agent-runtime/src/subagent-transcripts.cjs.map +1 -1
  40. package/dist/agent-runtime/src/subagent-transcripts.js +25 -3
  41. package/dist/agent-runtime/src/subagent-transcripts.js.map +1 -1
  42. package/dist/agent-runtime/src/subagents.cjs +112 -0
  43. package/dist/agent-runtime/src/subagents.cjs.map +1 -1
  44. package/dist/agent-runtime/src/subagents.d.ts +103 -0
  45. package/dist/agent-runtime/src/subagents.js +113 -1
  46. package/dist/agent-runtime/src/subagents.js.map +1 -1
  47. package/dist/agent-runtime/src/thread-handoff-protocol.d.ts +37 -9
  48. package/dist/agent-runtime/src/thread-handoff.d.ts +1 -1
  49. package/dist/agent-runtime/src/tool-metadata.cjs +8 -0
  50. package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
  51. package/dist/agent-runtime/src/tool-metadata.js +8 -0
  52. package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
  53. package/dist/agent-runtime/src/use-deep-agent-thread.cjs +22 -2
  54. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  55. package/dist/agent-runtime/src/use-deep-agent-thread.d.ts +9 -1
  56. package/dist/agent-runtime/src/use-deep-agent-thread.js +23 -3
  57. package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  58. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs +106 -25
  59. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
  60. package/dist/agent-runtime/src/use-deep-agent-window-sync.d.ts +41 -6
  61. package/dist/agent-runtime/src/use-deep-agent-window-sync.js +109 -28
  62. package/dist/agent-runtime/src/use-deep-agent-window-sync.js.map +1 -1
  63. package/dist/agent-runtime/src/use-thread-handoff-flow.d.ts +5 -9
  64. package/dist/agent-runtime/src/voice-presentation.cjs +34 -0
  65. package/dist/agent-runtime/src/voice-presentation.cjs.map +1 -1
  66. package/dist/agent-runtime/src/voice-presentation.d.ts +35 -0
  67. package/dist/agent-runtime/src/voice-presentation.js +34 -0
  68. package/dist/agent-runtime/src/voice-presentation.js.map +1 -1
  69. package/dist/assets/AthenaAssetEmbed.cjs +4 -2
  70. package/dist/assets/AthenaAssetEmbed.cjs.map +1 -1
  71. package/dist/assets/AthenaAssetEmbed.d.ts +17 -8
  72. package/dist/assets/AthenaAssetEmbed.js +4 -2
  73. package/dist/assets/AthenaAssetEmbed.js.map +1 -1
  74. package/dist/assets/use-asset-embed.cjs.map +1 -1
  75. package/dist/assets/use-asset-embed.d.ts +7 -5
  76. package/dist/assets/use-asset-embed.js.map +1 -1
  77. package/dist/auth/account-identity.cjs +69 -0
  78. package/dist/auth/account-identity.cjs.map +1 -0
  79. package/dist/auth/account-identity.d.ts +57 -0
  80. package/dist/auth/account-identity.js +69 -0
  81. package/dist/auth/account-identity.js.map +1 -0
  82. package/dist/chat/AthenaChat.cjs +1 -1
  83. package/dist/chat/AthenaChat.cjs.map +1 -1
  84. package/dist/chat/AthenaChat.js +1 -1
  85. package/dist/chat/AthenaChat.js.map +1 -1
  86. package/dist/chat/super-grouping/SuperGroupingCard.cjs +51 -43
  87. package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
  88. package/dist/chat/super-grouping/SuperGroupingCard.js +51 -43
  89. package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
  90. package/dist/chat/super-grouping/SuperGroupingTranscript.cjs +9 -4
  91. package/dist/chat/super-grouping/SuperGroupingTranscript.cjs.map +1 -1
  92. package/dist/chat/super-grouping/SuperGroupingTranscript.js +9 -4
  93. package/dist/chat/super-grouping/SuperGroupingTranscript.js.map +1 -1
  94. package/dist/chat/super-grouping/activity-timeline.cjs +7 -4
  95. package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
  96. package/dist/chat/super-grouping/activity-timeline.d.ts +10 -1
  97. package/dist/chat/super-grouping/activity-timeline.js +7 -4
  98. package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
  99. package/dist/chat/super-grouping/earlier-steps-button.cjs +50 -0
  100. package/dist/chat/super-grouping/earlier-steps-button.cjs.map +1 -0
  101. package/dist/chat/super-grouping/earlier-steps-button.d.ts +11 -0
  102. package/dist/chat/super-grouping/earlier-steps-button.js +50 -0
  103. package/dist/chat/super-grouping/earlier-steps-button.js.map +1 -0
  104. package/dist/chat/super-grouping/toolkit-map.cjs +1 -0
  105. package/dist/chat/super-grouping/toolkit-map.cjs.map +1 -1
  106. package/dist/chat/super-grouping/toolkit-map.js +1 -0
  107. package/dist/chat/super-grouping/toolkit-map.js.map +1 -1
  108. package/dist/chat/super-grouping/use-turn-steps.cjs +28 -0
  109. package/dist/chat/super-grouping/use-turn-steps.cjs.map +1 -0
  110. package/dist/chat/super-grouping/use-turn-steps.d.ts +23 -0
  111. package/dist/chat/super-grouping/use-turn-steps.js +28 -0
  112. package/dist/chat/super-grouping/use-turn-steps.js.map +1 -0
  113. package/dist/chat/use-statewire-approval-request.cjs +5 -5
  114. package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
  115. package/dist/chat/use-statewire-approval-request.d.ts +7 -0
  116. package/dist/chat/use-statewire-approval-request.js +5 -5
  117. package/dist/chat/use-statewire-approval-request.js.map +1 -1
  118. package/dist/chat-ui/mentions/use-account-workspace-id.cjs +18 -58
  119. package/dist/chat-ui/mentions/use-account-workspace-id.cjs.map +1 -1
  120. package/dist/chat-ui/mentions/use-account-workspace-id.js +18 -58
  121. package/dist/chat-ui/mentions/use-account-workspace-id.js.map +1 -1
  122. package/dist/chat-ui/messages/voice-delegation-card.cjs +93 -25
  123. package/dist/chat-ui/messages/voice-delegation-card.cjs.map +1 -1
  124. package/dist/chat-ui/messages/voice-delegation-card.d.ts +16 -7
  125. package/dist/chat-ui/messages/voice-delegation-card.js +95 -27
  126. package/dist/chat-ui/messages/voice-delegation-card.js.map +1 -1
  127. package/dist/chat-ui/statewire.cjs +6 -0
  128. package/dist/chat-ui/statewire.cjs.map +1 -1
  129. package/dist/chat-ui/statewire.d.ts +3 -1
  130. package/dist/chat-ui/statewire.js +7 -1
  131. package/dist/chat-ui/statewire.js.map +1 -1
  132. package/dist/chat-ui/thread/handoff-cursor.cjs +2 -2
  133. package/dist/chat-ui/thread/handoff-cursor.cjs.map +1 -1
  134. package/dist/chat-ui/thread/handoff-cursor.js +3 -3
  135. package/dist/chat-ui/thread/handoff-cursor.js.map +1 -1
  136. package/dist/chat-ui/thread/statewire-history-edge.cjs +4 -0
  137. package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
  138. package/dist/chat-ui/thread/statewire-history-edge.d.ts +11 -1
  139. package/dist/chat-ui/thread/statewire-history-edge.js +5 -1
  140. package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
  141. package/dist/collab/client.cjs +134 -7
  142. package/dist/collab/client.cjs.map +1 -1
  143. package/dist/collab/client.d.ts +44 -0
  144. package/dist/collab/client.js +134 -7
  145. package/dist/collab/client.js.map +1 -1
  146. package/dist/collab/index.d.ts +1 -1
  147. package/dist/composer/QuoteContext.cjs +3 -3
  148. package/dist/composer/QuoteContext.cjs.map +1 -1
  149. package/dist/composer/QuoteContext.js +3 -3
  150. package/dist/composer/QuoteContext.js.map +1 -1
  151. package/dist/keryx-http/src/initial-sync.cjs +121 -0
  152. package/dist/keryx-http/src/initial-sync.cjs.map +1 -0
  153. package/dist/keryx-http/src/initial-sync.d.ts +77 -0
  154. package/dist/keryx-http/src/initial-sync.js +104 -0
  155. package/dist/keryx-http/src/initial-sync.js.map +1 -0
  156. package/dist/keryx-http/src/unconfirmed-update-attributions.cjs +8 -0
  157. package/dist/keryx-http/src/unconfirmed-update-attributions.cjs.map +1 -1
  158. package/dist/keryx-http/src/unconfirmed-update-attributions.d.ts +6 -0
  159. package/dist/keryx-http/src/unconfirmed-update-attributions.js +8 -0
  160. package/dist/keryx-http/src/unconfirmed-update-attributions.js.map +1 -1
  161. package/dist/provider/AthenaProvider.cjs +11 -3
  162. package/dist/provider/AthenaProvider.cjs.map +1 -1
  163. package/dist/provider/AthenaProvider.js +12 -4
  164. package/dist/provider/AthenaProvider.js.map +1 -1
  165. package/dist/provider/statewire-window-context.cjs +6 -0
  166. package/dist/provider/statewire-window-context.cjs.map +1 -1
  167. package/dist/provider/statewire-window-context.d.ts +10 -1
  168. package/dist/provider/statewire-window-context.js +6 -0
  169. package/dist/provider/statewire-window-context.js.map +1 -1
  170. package/dist/react/package.json.cjs +1 -1
  171. package/dist/react/package.json.js +1 -1
  172. package/dist/runtime/useAthenaStatewireRuntime.cjs +2 -0
  173. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  174. package/dist/runtime/useAthenaStatewireRuntime.d.ts +7 -1
  175. package/dist/runtime/useAthenaStatewireRuntime.js +2 -0
  176. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  177. package/dist/styles.css +1 -1
  178. package/dist/threads/api.cjs +1 -2
  179. package/dist/threads/api.cjs.map +1 -1
  180. package/dist/threads/api.d.ts +3 -2
  181. package/dist/threads/api.js +1 -2
  182. package/dist/threads/api.js.map +1 -1
  183. package/dist/threads/sessions-query.cjs +2 -0
  184. package/dist/threads/sessions-query.cjs.map +1 -1
  185. package/dist/threads/sessions-query.js +2 -0
  186. package/dist/threads/sessions-query.js.map +1 -1
  187. package/dist/threads/statewire-thread-list.cjs +5 -7
  188. package/dist/threads/statewire-thread-list.cjs.map +1 -1
  189. package/dist/threads/statewire-thread-list.js +7 -9
  190. package/dist/threads/statewire-thread-list.js.map +1 -1
  191. package/dist/tools/subagent-task-tool-ui.cjs +15 -5
  192. package/dist/tools/subagent-task-tool-ui.cjs.map +1 -1
  193. package/dist/tools/subagent-task-tool-ui.d.ts +5 -4
  194. package/dist/tools/subagent-task-tool-ui.js +16 -6
  195. package/dist/tools/subagent-task-tool-ui.js.map +1 -1
  196. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"sessions-query.js","sources":["../../src/threads/sessions-query.ts"],"sourcesContent":["/**\n * The session-list query behind `SessionsPage` and `Inbox`: what the person\n * asked to see, how it maps onto `POST /api/conversations/threads/list`, and\n * what happens on a server that cannot apply part of it.\n *\n * Every filter is applied by the server as a predicate of its one page\n * statement, so a page is exact and `Load more` continues the filtered set.\n * The server ignores request fields it does not know, so a filter an older\n * agora cannot apply comes back unapplied; the list response names the fields\n * the server applies (`supported_filters`). `planSessionsQuery` splits a query\n * into what to send, what to apply to the loaded rows instead (`degraded`:\n * exact per loaded page, but a page may come back short), and what cannot be\n * applied at all on that server (`unavailable`: the UI disables those\n * controls).\n */\nimport type { ConversationSummary } from '@athenaintel/agent-runtime';\nimport type { ThreadListFilterBody } from './api';\n\nexport type AthenaSessionsSort = 'updated' | 'created';\nexport type AthenaSessionsDirection = 'desc' | 'asc';\n\n/** The collab-channel token for an agent's default channel (sessions with no channel stamp). */\nexport const DEFAULT_COLLAB_CHANNEL = 'default';\n\n/** status_v2 run statuses, in the order a status filter offers them. */\nexport const SESSION_RUN_STATUSES = [\n 'needs_input',\n 'running',\n 'queued',\n 'scheduled',\n 'completed',\n 'failed',\n 'canceled',\n] as const;\nexport type SessionRunStatus = (typeof SESSION_RUN_STATUSES)[number];\n\n/** status_v2 session statuses. */\nexport const SESSION_SESSION_STATUSES = ['active', 'needs_input', 'idle', 'error'] as const;\nexport type SessionSessionStatus = (typeof SESSION_SESSION_STATUSES)[number];\n\n/**\n * What a session list shows. Multi-value fields match any of their values;\n * different fields combine (AND). Unset fields do not filter.\n */\nexport interface AthenaSessionsQuery {\n /** Case-insensitive title search. */\n search?: string;\n /** Collab agents the session started as. */\n collabAgentIds?: readonly string[];\n /** Agent channels (modes); `DEFAULT_COLLAB_CHANNEL` is the agent's default channel. Needs `collabAgentIds`. */\n collabChannelIds?: readonly string[];\n /** Channels the session started from (`web`, `github`, `email`, …). */\n startChannels?: readonly string[];\n /** ISO 8601 bounds; `*After` inclusive, `*Before` exclusive. */\n createdAfter?: string;\n createdBefore?: string;\n updatedAfter?: string;\n updatedBefore?: string;\n /** Only sessions the viewer pinned. */\n favoritesOnly?: boolean;\n /** Only sessions the viewer has not read since they last changed. */\n unreadOnly?: boolean;\n /** status_v2 run statuses (`running` excludes runs silent for 12 hours, as every list does). */\n runStatuses?: readonly SessionRunStatus[];\n /** status_v2 session statuses. */\n sessionStatuses?: readonly SessionSessionStatus[];\n /** `true` only sessions that opened a pull request; `false` only those that opened none. */\n hasPullRequests?: boolean;\n /** `true` only the viewer's own sessions; `false` only sessions shared with them. */\n createdByMe?: boolean;\n /** Leave out sessions dismissed from the inbox. */\n excludeDismissed?: boolean;\n /** Hide sessions started by an automation (a schedule, an email, …). */\n excludeTriggered?: boolean;\n /** Sort key (default `updated`). */\n sort?: AthenaSessionsSort;\n /** Sort direction (default `desc`, newest first). */\n direction?: AthenaSessionsDirection;\n}\n\nexport type AthenaSessionsQueryField = keyof AthenaSessionsQuery;\n\n/** The REST field each query field travels as. */\nconst SERVER_FIELD: Record<AthenaSessionsQueryField, string> = {\n search: 'search',\n collabAgentIds: 'collab_agent_ids',\n collabChannelIds: 'collab_channel_ids',\n startChannels: 'start_channels',\n createdAfter: 'created_after',\n createdBefore: 'created_before',\n updatedAfter: 'updated_after',\n updatedBefore: 'updated_before',\n favoritesOnly: 'favorites_only',\n unreadOnly: 'unread_only',\n runStatuses: 'run_statuses',\n sessionStatuses: 'session_statuses',\n hasPullRequests: 'has_pull_requests',\n createdByMe: 'created_by_me',\n excludeDismissed: 'exclude_dismissed',\n excludeTriggered: 'exclude_triggered',\n sort: 'sort',\n direction: 'direction',\n};\n\n/**\n * The fields every thread-list server has applied, including those that\n * predate `supported_filters` — what a response without the list supports.\n */\nexport const LEGACY_THREAD_LIST_FILTERS: ReadonlySet<string> = new Set([\n 'search',\n 'exclude_triggered',\n 'app_id',\n 'start_channel',\n 'created_after',\n 'include_pull_requests',\n]);\n\n/** The query with unset, empty and default-valued fields dropped and arrays canonicalized. */\nexport function normalizeSessionsQuery(query: AthenaSessionsQuery): AthenaSessionsQuery {\n const out: AthenaSessionsQuery = {};\n const search = query.search?.trim();\n if (search) out.search = search;\n const list = <T extends string>(values: readonly T[] | undefined): T[] | undefined => {\n if (!values || values.length === 0) return undefined;\n return [...new Set(values)].sort();\n };\n const collabAgentIds = list(query.collabAgentIds);\n if (collabAgentIds) out.collabAgentIds = collabAgentIds;\n const collabChannelIds = list(query.collabChannelIds);\n if (collabChannelIds && collabAgentIds) out.collabChannelIds = collabChannelIds;\n const startChannels = list(query.startChannels);\n if (startChannels) out.startChannels = startChannels;\n for (const bound of ['createdAfter', 'createdBefore', 'updatedAfter', 'updatedBefore'] as const) {\n const value = query[bound];\n if (value) out[bound] = value;\n }\n if (query.favoritesOnly) out.favoritesOnly = true;\n if (query.unreadOnly) out.unreadOnly = true;\n const runStatuses = list(query.runStatuses);\n if (runStatuses) out.runStatuses = runStatuses;\n const sessionStatuses = list(query.sessionStatuses);\n if (sessionStatuses) out.sessionStatuses = sessionStatuses;\n if (query.hasPullRequests !== undefined) out.hasPullRequests = query.hasPullRequests;\n if (query.createdByMe !== undefined) out.createdByMe = query.createdByMe;\n if (query.excludeDismissed) out.excludeDismissed = true;\n if (query.excludeTriggered) out.excludeTriggered = true;\n if (query.sort && query.sort !== 'updated') out.sort = query.sort;\n if (query.direction && query.direction !== 'desc') out.direction = query.direction;\n return out;\n}\n\n/** A stable cache identity: semantically equal queries share one key. */\nexport function sessionsQueryKey(query: AthenaSessionsQuery): string {\n const normalized = normalizeSessionsQuery(query) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]]),\n );\n}\n\n/** The normalized query a `sessionsQueryKey` stands for. */\nexport function sessionsQueryFromKey(key: string): AthenaSessionsQuery {\n const entries: unknown = JSON.parse(key);\n if (!Array.isArray(entries)) return {};\n const query: Record<string, unknown> = {};\n for (const entry of entries) {\n if (Array.isArray(entry) && typeof entry[0] === 'string') query[entry[0]] = entry[1];\n }\n return normalizeSessionsQuery(query as AthenaSessionsQuery);\n}\n\n/** The fields a query sets (after normalization), in a fixed order. */\nexport function activeSessionsQueryFields(query: AthenaSessionsQuery): AthenaSessionsQueryField[] {\n const normalized = normalizeSessionsQuery(query);\n return (Object.keys(SERVER_FIELD) as AthenaSessionsQueryField[]).filter(\n (field) => normalized[field] !== undefined,\n );\n}\n\n/**\n * Every query field a backend can apply nowhere — what a filter UI disables\n * whatever is selected. `supportedFilters` as for `planSessionsQuery`.\n */\nexport function unavailableSessionsQueryFields(options: {\n supportedFilters: ReadonlySet<string> | null;\n includePullRequests: boolean;\n}): AthenaSessionsQueryField[] {\n const supported = options.supportedFilters ?? LEGACY_THREAD_LIST_FILTERS;\n const testable = {\n includePullRequests: options.includePullRequests,\n rowsCarryCreatedByMe: options.supportedFilters !== null,\n };\n return (Object.keys(SERVER_FIELD) as AthenaSessionsQueryField[]).filter(\n (field) =>\n field !== 'sort' &&\n field !== 'direction' &&\n !supported.has(SERVER_FIELD[field]) &&\n !locallyTestable(field, testable),\n );\n}\n\nexport interface SessionsQueryPlan {\n /** Sent to the server (`search` / `exclude_triggered` and `ThreadListFilterBody`). */\n body: ThreadListFilterBody;\n /** Applied to the loaded rows because the server cannot: exact per page, pages may be short. */\n degraded: AthenaSessionsQueryField[];\n /** Cannot be applied on this server at all (the rows carry nothing to test). */\n unavailable: AthenaSessionsQueryField[];\n /** The part of the query the loaded rows are checked against (`matchesSessionsQuery`). */\n local: AthenaSessionsQuery;\n}\n\n/**\n * Which fields a row can be tested on locally, given what this list fetches:\n * pull-request state only rides rows when the list asked for it, and\n * `createdByMe` only on servers new enough to send it.\n */\nfunction locallyTestable(\n field: AthenaSessionsQueryField,\n options: { includePullRequests: boolean; rowsCarryCreatedByMe: boolean },\n): boolean {\n switch (field) {\n case 'excludeDismissed':\n return false;\n case 'hasPullRequests':\n return options.includePullRequests;\n case 'createdByMe':\n return options.rowsCarryCreatedByMe;\n default:\n return true;\n }\n}\n\n/**\n * Split a query for one server. `supportedFilters` is the server's\n * `supported_filters` (`null` for a server that predates it: only\n * `LEGACY_THREAD_LIST_FILTERS` apply there).\n */\nexport function planSessionsQuery(\n query: AthenaSessionsQuery,\n options: { supportedFilters: ReadonlySet<string> | null; includePullRequests: boolean },\n): SessionsQueryPlan {\n const normalized = normalizeSessionsQuery(query);\n const supported = options.supportedFilters ?? LEGACY_THREAD_LIST_FILTERS;\n // A server that echoes `supported_filters` also sends `created_by_me` on rows.\n const rowsCarryCreatedByMe = options.supportedFilters !== null;\n const body: SessionsQueryPlan['body'] = {};\n const degraded: AthenaSessionsQueryField[] = [];\n const unavailable: AthenaSessionsQueryField[] = [];\n const local: AthenaSessionsQuery = {};\n const assignLocal = <K extends AthenaSessionsQueryField>(field: K) => {\n local[field] = normalized[field];\n };\n for (const field of activeSessionsQueryFields(normalized)) {\n const serverField = SERVER_FIELD[field];\n if (supported.has(serverField)) {\n Object.assign(body, { [serverField]: normalized[field] });\n // Server-applied fields are still checked on the loaded rows, so a row\n // a live push changed (read, unpinned, finished) leaves a view it no\n // longer matches; the server already guaranteed the fetched page. The\n // title search is not: the server matches the stored title, while a\n // row shows a display title that may come from its last message.\n if (\n field !== 'search' &&\n locallyTestable(field, {\n includePullRequests: options.includePullRequests,\n rowsCarryCreatedByMe,\n })\n ) {\n assignLocal(field);\n }\n continue;\n }\n if (field === 'sort' || field === 'direction') {\n // Sorting the loaded rows is always possible; it is degraded only in\n // that older pages arrived in the server's default order.\n degraded.push(field);\n assignLocal(field);\n continue;\n }\n if (\n locallyTestable(field, {\n includePullRequests: options.includePullRequests,\n rowsCarryCreatedByMe,\n })\n ) {\n degraded.push(field);\n assignLocal(field);\n } else {\n unavailable.push(field);\n }\n }\n // Sort/direction also order the loaded rows when the server applied them,\n // so a live update keeps its place.\n if (normalized.sort) local.sort = normalized.sort;\n if (normalized.direction) local.direction = normalized.direction;\n return { body, degraded, unavailable, local };\n}\n\nfunction timestamp(value: string | null | undefined): number | null {\n if (!value) return null;\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\nfunction withinBounds(\n value: string | null | undefined,\n after: string | undefined,\n before: string | undefined,\n): boolean {\n if (after === undefined && before === undefined) return true;\n const at = timestamp(value);\n if (at === null) return false;\n const afterMs = timestamp(after);\n const beforeMs = timestamp(before);\n if (afterMs !== null && at < afterMs) return false;\n if (beforeMs !== null && at >= beforeMs) return false;\n return true;\n}\n\n/** The fields of a row `matchesSessionsQuery` reads. */\nexport type SessionsQueryRow = Pick<\n ConversationSummary,\n | 'title'\n | 'updatedAt'\n | 'createdAt'\n | 'sourceChannel'\n | 'triggerType'\n | 'isUnread'\n | 'isFavorited'\n | 'runStatus'\n | 'sessionStatus'\n | 'collabAgentId'\n | 'collabChannelId'\n | 'pullRequests'\n | 'createdByMe'\n>;\n\n/**\n * Whether a loaded row matches the locally applicable part of a query\n * (`SessionsQueryPlan.local`). Fields the row does not carry pass, so a\n * missing value never hides a row the server returned.\n */\nexport function matchesSessionsQuery(row: SessionsQueryRow, query: AthenaSessionsQuery): boolean {\n if (query.search && !(row.title ?? '').toLowerCase().includes(query.search.toLowerCase())) {\n return false;\n }\n if (query.collabAgentIds && !query.collabAgentIds.includes(row.collabAgentId ?? '')) return false;\n if (query.collabChannelIds) {\n const channel = row.collabChannelId || DEFAULT_COLLAB_CHANNEL;\n if (!query.collabChannelIds.includes(channel)) return false;\n }\n if (query.startChannels && !query.startChannels.includes(row.sourceChannel ?? '')) return false;\n if (!withinBounds(row.createdAt, query.createdAfter, query.createdBefore)) return false;\n if (!withinBounds(row.updatedAt, query.updatedAfter, query.updatedBefore)) return false;\n if (query.favoritesOnly && row.isFavorited !== true) return false;\n if (query.unreadOnly && !row.isUnread) return false;\n if (query.runStatuses && !(query.runStatuses as readonly string[]).includes(row.runStatus ?? '')) {\n return false;\n }\n if (\n query.sessionStatuses &&\n !(query.sessionStatuses as readonly string[]).includes(row.sessionStatus ?? '')\n ) {\n return false;\n }\n if (query.hasPullRequests !== undefined && row.pullRequests !== undefined && row.pullRequests !== null) {\n if (query.hasPullRequests !== row.pullRequests.length > 0) return false;\n }\n if (query.createdByMe !== undefined && row.createdByMe !== undefined) {\n if (query.createdByMe !== row.createdByMe) return false;\n }\n if (query.excludeTriggered) {\n const trigger = row.triggerType?.trim().toLowerCase() ?? '';\n if (trigger && trigger !== 'manual') return false;\n }\n return true;\n}\n\n/** Rows in the query's order (stable; unparseable times last). */\nexport function sortSessions<T extends Pick<ConversationSummary, 'updatedAt' | 'createdAt'>>(\n rows: readonly T[],\n query: Pick<AthenaSessionsQuery, 'sort' | 'direction'>,\n): T[] {\n const key = query.sort === 'created' ? 'createdAt' : 'updatedAt';\n const sign = query.direction === 'asc' ? 1 : -1;\n return rows\n .map((row, index) => ({ row, index, at: timestamp(row[key]) }))\n .sort((a, b) => {\n if (a.at === null || b.at === null) {\n if (a.at === b.at) return a.index - b.index;\n return a.at === null ? 1 : -1;\n }\n return (a.at - b.at) * sign || a.index - b.index;\n })\n .map(({ row }) => row);\n}\n\n/** The server fields a response says it applies, or `null` when it predates the list. */\nexport function supportedFiltersFromResponse(\n supported: readonly string[] | undefined,\n): ReadonlySet<string> | null {\n return Array.isArray(supported) ? new Set(supported) : null;\n}\n"],"names":[],"mappings":"AAsBO,MAAM,yBAAyB;AAG/B,MAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAIO,MAAM,2BAA2B,CAAC,UAAU,eAAe,QAAQ,OAAO;AA8CjF,MAAM,eA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;AAC5B,SAAO,MAAM,QAAQ,SAAS,IAAI,IAAI,IAAI,SAAS,IAAI;AACzD;"}
1
+ {"version":3,"file":"sessions-query.js","sources":["../../src/threads/sessions-query.ts"],"sourcesContent":["/**\n * The session-list query behind `SessionsPage` and `Inbox`: what the person\n * asked to see, how it maps onto `POST /api/conversations/threads/list`, and\n * what happens on a server that cannot apply part of it.\n *\n * Every filter is applied by the server as a predicate of its one page\n * statement, so a page is exact and `Load more` continues the filtered set.\n * The server ignores request fields it does not know, so a filter an older\n * agora cannot apply comes back unapplied; the list response names the fields\n * the server applies (`supported_filters`). `planSessionsQuery` splits a query\n * into what to send, what to apply to the loaded rows instead (`degraded`:\n * exact per loaded page, but a page may come back short), and what cannot be\n * applied at all on that server (`unavailable`: the UI disables those\n * controls).\n */\nimport type { ConversationSummary } from '@athenaintel/agent-runtime';\nimport type { ThreadListFilterBody } from './api';\n\nexport type AthenaSessionsSort = 'updated' | 'created';\nexport type AthenaSessionsDirection = 'desc' | 'asc';\n\n/** The collab-channel token for an agent's default channel (sessions with no channel stamp). */\nexport const DEFAULT_COLLAB_CHANNEL = 'default';\n\n/** status_v2 run statuses, in the order a status filter offers them. */\nexport const SESSION_RUN_STATUSES = [\n 'needs_input',\n 'running',\n 'queued',\n 'scheduled',\n 'completed',\n 'failed',\n 'canceled',\n] as const;\nexport type SessionRunStatus = (typeof SESSION_RUN_STATUSES)[number];\n\n/** status_v2 session statuses. */\nexport const SESSION_SESSION_STATUSES = ['active', 'needs_input', 'idle', 'error'] as const;\nexport type SessionSessionStatus = (typeof SESSION_SESSION_STATUSES)[number];\n\n/**\n * What a session list shows. Multi-value fields match any of their values;\n * different fields combine (AND). Unset fields do not filter.\n */\nexport interface AthenaSessionsQuery {\n /** Case-insensitive title search. */\n search?: string;\n /** Collab agents the session started as. */\n collabAgentIds?: readonly string[];\n /** Agent channels (modes); `DEFAULT_COLLAB_CHANNEL` is the agent's default channel. Needs `collabAgentIds`. */\n collabChannelIds?: readonly string[];\n /** Channels the session started from (`web`, `github`, `email`, …). */\n startChannels?: readonly string[];\n /** ISO 8601 bounds; `*After` inclusive, `*Before` exclusive. */\n createdAfter?: string;\n createdBefore?: string;\n updatedAfter?: string;\n updatedBefore?: string;\n /** Only sessions the viewer pinned. */\n favoritesOnly?: boolean;\n /** Only sessions the viewer has not read since they last changed. */\n unreadOnly?: boolean;\n /** status_v2 run statuses (`running` excludes runs silent for 12 hours, as every list does). */\n runStatuses?: readonly SessionRunStatus[];\n /** status_v2 session statuses. */\n sessionStatuses?: readonly SessionSessionStatus[];\n /** `true` only sessions that opened a pull request; `false` only those that opened none. */\n hasPullRequests?: boolean;\n /** `true` only the viewer's own sessions; `false` only sessions shared with them. */\n createdByMe?: boolean;\n /** Leave out sessions dismissed from the inbox. */\n excludeDismissed?: boolean;\n /** Hide sessions started by an automation (a schedule, an email, …). */\n excludeTriggered?: boolean;\n /** Sort key (default `updated`). */\n sort?: AthenaSessionsSort;\n /** Sort direction (default `desc`, newest first). */\n direction?: AthenaSessionsDirection;\n}\n\nexport type AthenaSessionsQueryField = keyof AthenaSessionsQuery;\n\n/** The REST field each query field travels as. */\nconst SERVER_FIELD: Record<AthenaSessionsQueryField, string> = {\n search: 'search',\n collabAgentIds: 'collab_agent_ids',\n collabChannelIds: 'collab_channel_ids',\n startChannels: 'start_channels',\n createdAfter: 'created_after',\n createdBefore: 'created_before',\n updatedAfter: 'updated_after',\n updatedBefore: 'updated_before',\n favoritesOnly: 'favorites_only',\n unreadOnly: 'unread_only',\n runStatuses: 'run_statuses',\n sessionStatuses: 'session_statuses',\n hasPullRequests: 'has_pull_requests',\n createdByMe: 'created_by_me',\n excludeDismissed: 'exclude_dismissed',\n excludeTriggered: 'exclude_triggered',\n sort: 'sort',\n direction: 'direction',\n};\n\n/**\n * The fields every thread-list server has applied, including those that\n * predate `supported_filters` — what a response without the list supports.\n */\nexport const LEGACY_THREAD_LIST_FILTERS: ReadonlySet<string> = new Set([\n 'search',\n 'exclude_triggered',\n 'app_id',\n 'start_channel',\n 'created_after',\n 'include_pull_requests',\n]);\n\n/** The query with unset, empty and default-valued fields dropped and arrays canonicalized. */\nexport function normalizeSessionsQuery(query: AthenaSessionsQuery): AthenaSessionsQuery {\n const out: AthenaSessionsQuery = {};\n const search = query.search?.trim();\n if (search) out.search = search;\n const list = <T extends string>(values: readonly T[] | undefined): T[] | undefined => {\n if (!values || values.length === 0) return undefined;\n return [...new Set(values)].sort();\n };\n const collabAgentIds = list(query.collabAgentIds);\n if (collabAgentIds) out.collabAgentIds = collabAgentIds;\n const collabChannelIds = list(query.collabChannelIds);\n if (collabChannelIds && collabAgentIds) out.collabChannelIds = collabChannelIds;\n const startChannels = list(query.startChannels);\n if (startChannels) out.startChannels = startChannels;\n for (const bound of ['createdAfter', 'createdBefore', 'updatedAfter', 'updatedBefore'] as const) {\n const value = query[bound];\n if (value) out[bound] = value;\n }\n if (query.favoritesOnly) out.favoritesOnly = true;\n if (query.unreadOnly) out.unreadOnly = true;\n const runStatuses = list(query.runStatuses);\n if (runStatuses) out.runStatuses = runStatuses;\n const sessionStatuses = list(query.sessionStatuses);\n if (sessionStatuses) out.sessionStatuses = sessionStatuses;\n if (query.hasPullRequests !== undefined) out.hasPullRequests = query.hasPullRequests;\n if (query.createdByMe !== undefined) out.createdByMe = query.createdByMe;\n if (query.excludeDismissed) out.excludeDismissed = true;\n if (query.excludeTriggered) out.excludeTriggered = true;\n if (query.sort && query.sort !== 'updated') out.sort = query.sort;\n if (query.direction && query.direction !== 'desc') out.direction = query.direction;\n return out;\n}\n\n/** A stable cache identity: semantically equal queries share one key. */\nexport function sessionsQueryKey(query: AthenaSessionsQuery): string {\n const normalized = normalizeSessionsQuery(query) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]]),\n );\n}\n\n/** The normalized query a `sessionsQueryKey` stands for. */\nexport function sessionsQueryFromKey(key: string): AthenaSessionsQuery {\n const entries: unknown = JSON.parse(key);\n if (!Array.isArray(entries)) return {};\n const query: Record<string, unknown> = {};\n for (const entry of entries) {\n if (Array.isArray(entry) && typeof entry[0] === 'string') query[entry[0]] = entry[1];\n }\n return normalizeSessionsQuery(query as AthenaSessionsQuery);\n}\n\n/** The fields a query sets (after normalization), in a fixed order. */\nexport function activeSessionsQueryFields(query: AthenaSessionsQuery): AthenaSessionsQueryField[] {\n const normalized = normalizeSessionsQuery(query);\n return (Object.keys(SERVER_FIELD) as AthenaSessionsQueryField[]).filter(\n (field) => normalized[field] !== undefined,\n );\n}\n\n/**\n * Every query field a backend can apply nowhere — what a filter UI disables\n * whatever is selected. `supportedFilters` as for `planSessionsQuery`.\n */\nexport function unavailableSessionsQueryFields(options: {\n supportedFilters: ReadonlySet<string> | null;\n includePullRequests: boolean;\n}): AthenaSessionsQueryField[] {\n const supported = options.supportedFilters ?? LEGACY_THREAD_LIST_FILTERS;\n const testable = {\n includePullRequests: options.includePullRequests,\n rowsCarryCreatedByMe: options.supportedFilters !== null,\n };\n return (Object.keys(SERVER_FIELD) as AthenaSessionsQueryField[]).filter(\n (field) =>\n field !== 'sort' &&\n field !== 'direction' &&\n !supported.has(SERVER_FIELD[field]) &&\n !locallyTestable(field, testable),\n );\n}\n\nexport interface SessionsQueryPlan {\n /** Sent to the server (`search` / `exclude_triggered` and `ThreadListFilterBody`). */\n body: ThreadListFilterBody;\n /** Applied to the loaded rows because the server cannot: exact per page, pages may be short. */\n degraded: AthenaSessionsQueryField[];\n /** Cannot be applied on this server at all (the rows carry nothing to test). */\n unavailable: AthenaSessionsQueryField[];\n /** The part of the query the loaded rows are checked against (`matchesSessionsQuery`). */\n local: AthenaSessionsQuery;\n}\n\n/**\n * Which fields a row can be tested on locally, given what this list fetches:\n * pull-request state only rides rows when the list asked for it, and\n * `createdByMe` only on servers new enough to send it.\n */\nfunction locallyTestable(\n field: AthenaSessionsQueryField,\n options: { includePullRequests: boolean; rowsCarryCreatedByMe: boolean },\n): boolean {\n switch (field) {\n case 'excludeDismissed':\n return false;\n case 'hasPullRequests':\n return options.includePullRequests;\n case 'createdByMe':\n return options.rowsCarryCreatedByMe;\n default:\n return true;\n }\n}\n\n/**\n * Split a query for one server. `supportedFilters` is the server's\n * `supported_filters` (`null` for a server that predates it: only\n * `LEGACY_THREAD_LIST_FILTERS` apply there).\n */\nexport function planSessionsQuery(\n query: AthenaSessionsQuery,\n options: { supportedFilters: ReadonlySet<string> | null; includePullRequests: boolean },\n): SessionsQueryPlan {\n const normalized = normalizeSessionsQuery(query);\n const supported = options.supportedFilters ?? LEGACY_THREAD_LIST_FILTERS;\n // A server that echoes `supported_filters` also sends `created_by_me` on rows.\n const rowsCarryCreatedByMe = options.supportedFilters !== null;\n const body: SessionsQueryPlan['body'] = {};\n const degraded: AthenaSessionsQueryField[] = [];\n const unavailable: AthenaSessionsQueryField[] = [];\n const local: AthenaSessionsQuery = {};\n const assignLocal = <K extends AthenaSessionsQueryField>(field: K) => {\n local[field] = normalized[field];\n };\n for (const field of activeSessionsQueryFields(normalized)) {\n const serverField = SERVER_FIELD[field];\n if (supported.has(serverField)) {\n Object.assign(body, { [serverField]: normalized[field] });\n // Server-applied fields are still checked on the loaded rows, so a row\n // a live push changed (read, unpinned, finished) leaves a view it no\n // longer matches; the server already guaranteed the fetched page. The\n // title search is not: the server matches the stored title, while a\n // row shows a display title that may come from its last message.\n if (\n field !== 'search' &&\n locallyTestable(field, {\n includePullRequests: options.includePullRequests,\n rowsCarryCreatedByMe,\n })\n ) {\n assignLocal(field);\n }\n continue;\n }\n if (field === 'sort' || field === 'direction') {\n // Sorting the loaded rows is always possible; it is degraded only in\n // that older pages arrived in the server's default order.\n degraded.push(field);\n assignLocal(field);\n continue;\n }\n if (\n locallyTestable(field, {\n includePullRequests: options.includePullRequests,\n rowsCarryCreatedByMe,\n })\n ) {\n degraded.push(field);\n assignLocal(field);\n } else {\n unavailable.push(field);\n }\n }\n // Sort/direction also order the loaded rows when the server applied them,\n // so a live update keeps its place.\n if (normalized.sort) local.sort = normalized.sort;\n if (normalized.direction) local.direction = normalized.direction;\n return { body, degraded, unavailable, local };\n}\n\nfunction timestamp(value: string | null | undefined): number | null {\n if (!value) return null;\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\nfunction withinBounds(\n value: string | null | undefined,\n after: string | undefined,\n before: string | undefined,\n): boolean {\n if (after === undefined && before === undefined) return true;\n const at = timestamp(value);\n if (at === null) return false;\n const afterMs = timestamp(after);\n const beforeMs = timestamp(before);\n if (afterMs !== null && at < afterMs) return false;\n if (beforeMs !== null && at >= beforeMs) return false;\n return true;\n}\n\n/** `start_channel` of a session an Automation's `agent_run` step started. */\nconst AUTOMATION_START_CHANNEL = 'automation';\n\n/** The fields of a row `matchesSessionsQuery` reads. */\nexport type SessionsQueryRow = Pick<\n ConversationSummary,\n | 'title'\n | 'updatedAt'\n | 'createdAt'\n | 'sourceChannel'\n | 'triggerType'\n | 'isUnread'\n | 'isFavorited'\n | 'runStatus'\n | 'sessionStatus'\n | 'collabAgentId'\n | 'collabChannelId'\n | 'pullRequests'\n | 'createdByMe'\n>;\n\n/**\n * Whether a loaded row matches the locally applicable part of a query\n * (`SessionsQueryPlan.local`). Fields the row does not carry pass, so a\n * missing value never hides a row the server returned.\n */\nexport function matchesSessionsQuery(row: SessionsQueryRow, query: AthenaSessionsQuery): boolean {\n if (query.search && !(row.title ?? '').toLowerCase().includes(query.search.toLowerCase())) {\n return false;\n }\n if (query.collabAgentIds && !query.collabAgentIds.includes(row.collabAgentId ?? '')) return false;\n if (query.collabChannelIds) {\n const channel = row.collabChannelId || DEFAULT_COLLAB_CHANNEL;\n if (!query.collabChannelIds.includes(channel)) return false;\n }\n if (query.startChannels && !query.startChannels.includes(row.sourceChannel ?? '')) return false;\n if (!withinBounds(row.createdAt, query.createdAfter, query.createdBefore)) return false;\n if (!withinBounds(row.updatedAt, query.updatedAfter, query.updatedBefore)) return false;\n if (query.favoritesOnly && row.isFavorited !== true) return false;\n if (query.unreadOnly && !row.isUnread) return false;\n if (query.runStatuses && !(query.runStatuses as readonly string[]).includes(row.runStatus ?? '')) {\n return false;\n }\n if (\n query.sessionStatuses &&\n !(query.sessionStatuses as readonly string[]).includes(row.sessionStatus ?? '')\n ) {\n return false;\n }\n if (query.hasPullRequests !== undefined && row.pullRequests !== undefined && row.pullRequests !== null) {\n if (query.hasPullRequests !== row.pullRequests.length > 0) return false;\n }\n if (query.createdByMe !== undefined && row.createdByMe !== undefined) {\n if (query.createdByMe !== row.createdByMe) return false;\n }\n if (query.excludeTriggered) {\n const trigger = row.triggerType?.trim().toLowerCase() ?? '';\n if (trigger && trigger !== 'manual') return false;\n // An Automation's run carries no trigger type; its start channel marks it,\n // and the server leaves every one out (agora's `sdk_thread_list`).\n if (row.sourceChannel === AUTOMATION_START_CHANNEL) return false;\n }\n return true;\n}\n\n/** Rows in the query's order (stable; unparseable times last). */\nexport function sortSessions<T extends Pick<ConversationSummary, 'updatedAt' | 'createdAt'>>(\n rows: readonly T[],\n query: Pick<AthenaSessionsQuery, 'sort' | 'direction'>,\n): T[] {\n const key = query.sort === 'created' ? 'createdAt' : 'updatedAt';\n const sign = query.direction === 'asc' ? 1 : -1;\n return rows\n .map((row, index) => ({ row, index, at: timestamp(row[key]) }))\n .sort((a, b) => {\n if (a.at === null || b.at === null) {\n if (a.at === b.at) return a.index - b.index;\n return a.at === null ? 1 : -1;\n }\n return (a.at - b.at) * sign || a.index - b.index;\n })\n .map(({ row }) => row);\n}\n\n/** The server fields a response says it applies, or `null` when it predates the list. */\nexport function supportedFiltersFromResponse(\n supported: readonly string[] | undefined,\n): ReadonlySet<string> | null {\n return Array.isArray(supported) ? new Set(supported) : null;\n}\n"],"names":[],"mappings":"AAsBO,MAAM,yBAAyB;AAG/B,MAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAIO,MAAM,2BAA2B,CAAC,UAAU,eAAe,QAAQ,OAAO;AA8Cj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C,EACA,IAAI,CAAC,EAAE,IAAA,MAAU,GAAG;AACzB;AAGO,SAAS,6BACd,WAC4B;AAC5B,SAAO,MAAM,QAAQ,SAAS,IAAI,IAAI,IAAI,SAAS,IAAI;AACzD;"}
@@ -5,6 +5,7 @@ const offlineSessionList = require("./offline-session-list.cjs");
5
5
  const reactQuery = require("@tanstack/react-query");
6
6
  const react = require("@assistant-ui/react");
7
7
  const require$$0 = require("react");
8
+ const accountIdentity = require("../auth/account-identity.cjs");
8
9
  const AthenaAuthContext = require("../auth/AthenaAuthContext.cjs");
9
10
  const statewireAuthHeaders = require("../runtime/statewire-auth-headers.cjs");
10
11
  const api = require("./api.cjs");
@@ -222,13 +223,10 @@ function StatewireThreadListState({
222
223
  }
223
224
  const credentialGeneration = credentialGenerationRef.current;
224
225
  const identityEnabled = syncUrl !== void 0 && principal.length > 0 && hasAuth;
225
- const identity = reactQuery.useQuery({
226
- // Keyed by the non-secret principal and credential generation, never the
227
- // credential itself.
228
- queryKey: ["athena-sdk", "account-identity", backendUrl, principal, credentialGeneration],
229
- queryFn: ({ signal }) => credentialRenewal.withCredentialRenewal(getAuth, (auth) => api.fetchAccountIdentity(backendUrl, auth, { signal })),
230
- enabled: identityEnabled,
231
- staleTime: Number.POSITIVE_INFINITY
226
+ const identity = accountIdentity.useAccountIdentityQuery({
227
+ credential: { backendUrl, principal, apiKey, heldToken: token, tokenGetter: getToken },
228
+ resolveAuth: getAuth,
229
+ enabled: identityEnabled
232
230
  });
233
231
  const indexWorkspaceId = ((_b = identity.data) == null ? void 0 : _b.workspaceId) ?? "";
234
232
  const indexUserId = ((_c = identity.data) == null ? void 0 : _c.userId) ?? "";
@@ -1 +1 @@
1
- {"version":3,"file":"statewire-thread-list.cjs","sources":["../../src/threads/statewire-thread-list.tsx"],"sourcesContent":["import {\n type ConversationAttention,\n type ConversationAttentionSource,\n type ConversationIndexEntry,\n type ConversationListFilter,\n type ConversationPullRequest,\n type ConversationSummary,\n type ConversationWake,\n conversationIndexUrlFromStatewireUrl,\n conversationListFilterKey,\n conversationListQueryKeys,\n type DeepAgentHeadersResolver,\n type DeepAgentThreadSnapshotCache,\n deriveConversationAttention,\n patchConversationListCaches,\n removeConversationFromListCaches,\n summaryFromConversationIndexEntry,\n type ThreadSnapshotMirror,\n useConversationIndex,\n useConversationList,\n} from '@athenaintel/agent-runtime';\nimport { useOfflineSessionList } from './offline-session-list';\nimport { QueryClient, QueryClientProvider, useQuery, useQueryClient } from '@tanstack/react-query';\nimport { useAuiState } from '@assistant-ui/react';\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n resolveStatewireAuthToken,\n} from '../runtime/statewire-auth-headers';\nimport { fetchAccountIdentity, getThreadState } from './api';\nimport { createRestConversationListFetcher } from './conversation-list-fetcher';\nimport { credentialShape, sameCredentialShape } from './credential-shape';\nimport { mintThreadId } from './mint-thread-id';\nimport { useAthenaStatewireThreadId } from './thread-id-context';\nimport { createThreadPrefetcher } from './thread-prefetcher';\nimport { useIndexTriggeredRefresh } from './index-triggered-refresh';\nimport {\n type SessionListTabShare,\n sessionListShareKey,\n useSessionListTabShare,\n} from './session-list-tab-share';\nimport { isSerializedContentPartsTitle, normalizeThreadTitle } from './title';\nimport { useRestartAfterAuthRefusal } from '../runtime/auth-refusal-restart';\nimport { type CredentialResolver, withCredentialRenewal } from '../runtime/credential-renewal';\nimport { useThreadArchive } from './use-thread-archive';\nimport {\n type ThreadFavoriteTarget,\n useThreadFavorite,\n withFavoriteOverride,\n withFavoriteOverrides,\n} from './use-thread-favorite';\nimport {\n type ThreadReadStateTarget,\n useThreadReadState,\n withReadStateOverrides,\n} from './use-thread-read-state';\nimport {\n type ThreadRenameTarget,\n useThreadRename,\n withTitleOverride,\n withTitleOverrides,\n} from './use-thread-rename';\n\n/**\n * One row of the thread list — the fields a Devin-style session list renders\n * (`SessionList`), all read from the shared conversation-list contract. The\n * attention fields are `null` on a server that does not derive them; the\n * pull-request state is `null` until the list has fetched it (or when the\n * provider opted out of it).\n */\nexport interface AthenaStatewireThreadSummary {\n id: string;\n title: string | null;\n /**\n * What the session asks of the viewer: the server-derived state when\n * reported, else the client fallback from the status planes\n * (`deriveConversationAttention`).\n */\n attention: ConversationAttention | null;\n /** One line (≤ 80 chars) of what the viewer should do next, when the server derives one. */\n nextAction: string | null;\n attentionSource: ConversationAttentionSource | null;\n /**\n * Whether the viewer pinned the session. Toggled through\n * `AthenaStatewireThreadListState.setFavorited`; a toggle in flight is\n * reflected here at once and held until the list sources report it.\n */\n isFavorited: boolean;\n isUnread: boolean;\n /** Canonical status_v2 planes, or `null` on an older server. */\n sessionStatus: string | null;\n runStatus: string | null;\n /** Channel the session was started from (e.g. `web`, `github`, `api`). */\n startChannel: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Pull requests the session opened with their live GitHub state. */\n pullRequests: ConversationPullRequest[] | null;\n /** The last wake of a resting session. */\n lastWake: ConversationWake | null;\n /** ISO 8601 timestamp of the last update (the list's sort key). */\n updatedAt: string;\n /** ISO 8601 creation time; `null` when the list did not report it. */\n createdAt?: string | null;\n /** The session's last message, for a preview line (the inbox excerpt). */\n preview?: string | null;\n /** The collab agent the session started as, and its channel (`null`: the default channel). */\n collabAgentId?: string | null;\n collabChannelId?: string | null;\n /** Whether the viewer started the session (`false`: shared with them); `null` when not reported. */\n createdByMe?: boolean | null;\n}\n\n/**\n * Thread-list state. The list is the persisted Agora session list; the ACTIVE\n * thread is a plain id the statewire runtime attaches to — switching threads\n * remounts the statewire session against the new `…/v2/threads/{id}` URL\n * (the same model the mobile app uses).\n */\nexport interface AthenaStatewireThreadListState {\n /** The rows the current `search` lists, newest first. */\n threads: AthenaStatewireThreadSummary[];\n isLoading: boolean;\n /** True while the live first page (or a history page) is being fetched. */\n isFetching: boolean;\n /**\n * True once the live first page has answered at least once for the current\n * search and identity. Until then an empty `threads` means \"not known\n * yet\" (no credential resolved, first page in flight), not \"no sessions\":\n * `SessionList` shows skeleton rows, never the empty state.\n */\n hasResolvedFirstPage: boolean;\n activeThreadId: string;\n /**\n * The active thread's row, independent of what `threads` currently lists:\n * a search that hides the row, or a page that has not fetched it, must not\n * make the active chat's attention disappear. Resolved from the listed row,\n * else the pushed index entry folded over the last row seen, else that\n * last row; `null` for a never-started chat the backend does not know yet.\n */\n activeThread: AthenaStatewireThreadSummary | null;\n /** True while the active thread is a locally-minted chat with no server history. */\n isNewChat: boolean;\n /**\n * Switch to `threadId`; `isNew` for a chat this page minted that never started (it loads as a\n * new chat until the list has it), e.g. one holding messages that wait in the chat outbox.\n */\n selectThread: (threadId: string, options?: { isNew?: boolean }) => void;\n /**\n * Warm the provider's snapshot cache with a thread's REST state ahead of a\n * `selectThread`, so the switch paints the transcript on its first frame\n * instead of the loading scrim while the statewire attach lands.\n * `SessionList` calls it after a 120 ms hover dwell and on row focus.\n * Fetches once per thread per identity, deduplicates requests in flight,\n * runs at most two at a time and ignores failures; a no-op for the active\n * thread, a thread the cache already holds, or a provider without a cache.\n */\n prefetchThread: (threadId: string) => void;\n newThread: () => void;\n refresh: () => void;\n /**\n * Server-side title search (`search` on the REST thread list). An empty\n * string lists everything; the search covers the viewer's whole authorized\n * history, not just the live page.\n */\n search: string;\n setSearch: (search: string) => void;\n /** Whether another page of older sessions can be fetched. */\n hasNextPage: boolean;\n isFetchingNextPage: boolean;\n /** Fetch the next page of older sessions (frozen history pages, never replayed). */\n fetchNextPage: () => void;\n /**\n * Pin or unpin a session (`POST /api/conversations/threads/favorite`). The\n * row flips at once and moves between the `Pinned` and `Recent` groups; the\n * server's answer is written back, and a failure restores the previous\n * state. Writes for one thread are serialized: a toggle while that\n * thread's write is in flight records the value and sends at most one\n * follow-up write once the first has answered.\n */\n setFavorited: (target: ThreadFavoriteTarget) => void;\n /** True while any pin toggle is in flight. */\n favoritePending: boolean;\n /** The sessions whose pin toggle is in flight; `SessionList` disables their pin control. */\n favoritePendingThreadIds: ReadonlySet<string>;\n /**\n * Whether the backend offers the favorite route. `false` once it answered\n * 404 / 405 (an agora that predates the route): `SessionList` then shows\n * the read-only pin and no toggle, and `setFavorited` keeps failing.\n */\n favoriteToggleAvailable: boolean;\n /**\n * Rename a session for every viewer (`POST /api/conversations/threads/rename`).\n * The row shows the new title at once; the server's stored title is\n * written back, and a failure restores the previous one. Same-thread\n * writes are serialized like the pin's.\n */\n renameThread: (target: ThreadRenameTarget) => void;\n /** The sessions whose rename is in flight; `SessionList` keeps their editor closed. */\n renamePendingThreadIds: ReadonlySet<string>;\n /**\n * Whether the backend offers the rename route. `false` once it answered\n * 404 / 405 (an agora that predates the route): `SessionList` then offers\n * no Rename action, and `renameThread` keeps failing.\n */\n renameAvailable: boolean;\n /**\n * Archive a session (`POST /api/conversations/threads/archive`). The row\n * leaves the list at once and stays hidden until both list sources stop\n * reporting it; a failure brings it back. Archiving the active session\n * moves the chat to a new one once the server has confirmed.\n */\n archiveThread: (threadId: string) => void;\n /** The sessions whose archive is in flight. */\n archivePendingThreadIds: ReadonlySet<string>;\n /** True while any archive is in flight. */\n archivePending: boolean;\n /**\n * Whether the backend offers the archive route. `false` once it answered\n * 404 / 405: `SessionList` then offers no Archive action.\n */\n archiveAvailable: boolean;\n /**\n * Mark a session read or unread for the viewer\n * (`POST /api/conversations/threads/read-state`). The row flips at once in\n * every list under the provider (`SessionList`, `SessionsPage`, `Inbox`);\n * the server's answer is written back, and a failure restores the previous\n * state. Same-thread writes are serialized like the pin's.\n */\n setReadState: (target: ThreadReadStateTarget) => void;\n /** The sessions whose read-state write is in flight. */\n readStatePendingThreadIds: ReadonlySet<string>;\n /**\n * Where titles come from. `'index'` once the signed-in user's live\n * conversation index has replicated — titles and newly created threads then\n * arrive as pushed updates; `'poll'` while it has not (no signed-in\n * principal, e.g. API-key mode, or before its snapshot), when a\n * freshly-started thread's title is picked up by the bounded REST poll.\n */\n titleSource: 'index' | 'poll';\n}\n\nexport const AthenaStatewireThreadListContext =\n createContext<AthenaStatewireThreadListState | null>(null);\n\n/** Read the statewire thread-list state, or null outside that mode. */\nexport function useAthenaStatewireThreadList(): AthenaStatewireThreadListState | null {\n return useContext(AthenaStatewireThreadListContext);\n}\n\n/** Trigger a re-fetch of the thread list. `null` outside `enableThreadList` mode. */\nexport function useRefreshThreadList(): (() => void) | null {\n return useAthenaStatewireThreadList()?.refresh ?? null;\n}\n\n/**\n * Start channels of an agent's sessions that the server leaves out when it lists the conversations\n * with a home agent (`home_agent_id`): the agent's tasks and the sessions an orchestrating agent\n * starts.\n */\nconst AGENT_HOME_EXCLUDED_START_CHANNELS: ReadonlySet<string> = new Set([\n 'task',\n 'agent_orchestration',\n]);\n\n/**\n * Whether a pushed index entry is one of the conversations with `homeAgentId`'s agent that the\n * server lists beside the app scope: the agent's, and not one of its tasks or orchestration\n * sessions. An entry from a pod that predates `collab_agent_id` is not.\n */\nfunction isAgentHomeIndexEntry(\n entry: { collab_agent_id?: string | null; start_channel?: string | null },\n homeAgentId: string | undefined,\n): boolean {\n if (!homeAgentId || entry.collab_agent_id !== homeAgentId) return false;\n return !AGENT_HOME_EXCLUDED_START_CHANNELS.has(entry.start_channel ?? '');\n}\n\n/**\n * The threads the conversation index knows that the fetched list does not show yet, and that have\n * not prompted a refresh before: each warrants one refresh of the list. Only threads of the apps\n * the list shows count (its `appId` and `additionalAppIds`); with neither, every app's do. With a\n * `homeAgentId`, the conversations with that agent count too, but only while `homeAgentApplied`\n * (the list's latest first page said the server listed them; absent counts as false): a server\n * that did not widen the list never lists them, so their updates must not refresh it.\n * Exported for tests.\n */\nexport function indexedThreadsToRefreshFor({\n entries,\n listedThreadIds,\n refreshedThreadIds,\n appId,\n additionalAppIds,\n homeAgentId,\n homeAgentApplied = false,\n}: {\n entries: ReadonlyArray<{\n thread_id: string;\n app_id: string | null;\n collab_agent_id?: string | null;\n start_channel?: string | null;\n }>;\n listedThreadIds: ReadonlySet<string>;\n refreshedThreadIds: ReadonlySet<string>;\n appId: string | undefined;\n additionalAppIds: readonly string[];\n homeAgentId?: string;\n homeAgentApplied?: boolean;\n}): string[] {\n const shownAppIds =\n appId || additionalAppIds.length > 0\n ? new Set([...(appId ? [appId] : []), ...additionalAppIds])\n : null;\n const listedAgentId = homeAgentApplied ? homeAgentId : undefined;\n return entries\n .filter(\n (entry) =>\n !shownAppIds ||\n shownAppIds.has(entry.app_id ?? '') ||\n isAgentHomeIndexEntry(entry, listedAgentId),\n )\n .map((entry) => entry.thread_id)\n .filter((threadId) => !listedThreadIds.has(threadId) && !refreshedThreadIds.has(threadId));\n}\n\n/**\n * Project one contract row onto the thread-list row. Exported for hosts (and\n * tests) that build rows from a `ConversationSummary` of their own.\n */\nexport function threadSummaryFromConversation(\n conversation: ConversationSummary,\n): AthenaStatewireThreadSummary {\n return {\n id: conversation.threadId,\n title: normalizeThreadTitle(conversation.title) ?? null,\n attention: deriveConversationAttention(conversation),\n nextAction: conversation.nextAction ?? null,\n attentionSource: conversation.attentionSource ?? null,\n isFavorited: conversation.isFavorited ?? false,\n isUnread: conversation.isUnread,\n sessionStatus: conversation.sessionStatus,\n runStatus: conversation.runStatus,\n startChannel: conversation.sourceChannel,\n appId: conversation.appId,\n triggerType: conversation.triggerType,\n pullRequests: conversation.pullRequests ?? null,\n lastWake: conversation.lastWake ?? null,\n updatedAt: conversation.updatedAt,\n createdAt: conversation.createdAt,\n preview: conversation.preview,\n collabAgentId: conversation.collabAgentId ?? null,\n collabChannelId: conversation.collabChannelId ?? null,\n createdByMe: conversation.createdByMe ?? null,\n };\n}\n\n/**\n * Fold the pushed conversation index into fetched rows: each row with an\n * index entry takes its pushed fields through the shared\n * `summaryFromConversationIndexEntry` (titles, lifecycle, attention), while\n * what the index never carries (pull requests, the last wake, who started\n * it) keeps the fetched value. A pushed title that normalizes to nothing\n * falls back to the fetched one. Exported for tests.\n */\nexport function foldConversationIndex(\n conversations: readonly ConversationSummary[],\n indexByThread: ReadonlyMap<string, ConversationIndexEntry>,\n): ConversationSummary[] {\n return conversations.map((conversation) => {\n const entry = indexByThread.get(conversation.threadId);\n if (!entry) return conversation;\n const merged = summaryFromConversationIndexEntry(entry, conversation);\n return normalizeThreadTitle(merged.title) === undefined\n ? { ...merged, title: conversation.title }\n : merged;\n });\n}\n\n/**\n * The listed rows plus the pinned rows they do not include, appended in the\n * pinned list's own newest-first order. A pinned row the list does not\n * include is older than the list's last row, so appending keeps the merged\n * rows newest-first. A row whose pin was just undone (`isFavorited: false`,\n * patched into every cached list) is not added back. Exported for tests.\n */\nexport function withPinnedConversations({\n conversations,\n pinned,\n}: {\n conversations: readonly ConversationSummary[];\n pinned: readonly ConversationSummary[];\n}): readonly ConversationSummary[] {\n const listed = new Set(conversations.map((conversation) => conversation.threadId));\n const unlisted = pinned.filter(\n (conversation) => conversation.isFavorited !== false && !listed.has(conversation.threadId),\n );\n return unlisted.length === 0 ? conversations : [...conversations, ...unlisted];\n}\n\n/**\n * What the thread-list provider shares with the other lists mounted under it\n * (`SessionsPage`, `Inbox`): the credential, the live conversation index and\n * the optimistic overrides (pin, title, read state, archived rows), so every\n * list folds the same pushes and shows the same in-flight writes. Internal —\n * hosts use `useAthenaSessions`.\n */\nexport interface AthenaSessionsLiveState {\n backendUrl: string;\n getAuth: CredentialResolver<{ apiKey?: string; token?: string | null }>;\n principal: string;\n hasAuth: boolean;\n includePullRequests: boolean;\n /** The provider list's cache scope (backend, principal, auth, PR opt-in). */\n scopeKey: string;\n /**\n * Advances whenever the host's credential changes (a swapped API key or\n * token, a scoped credential for another workspace under the same\n * principal), so caches keyed on it are never read with another credential.\n */\n credentialGeneration: number;\n /** The app scope the provider lists (`appId` / `additionalListAppIds` / `homeAgentId`). */\n baseFilter: ConversationListFilter;\n indexByThread: ReadonlyMap<string, ConversationIndexEntry>;\n /** `null` until the index has replicated (or without one). */\n indexEntries: readonly ConversationIndexEntry[] | null;\n /** Layer the in-flight writes over rows and drop archived ones. */\n applyOverrides: (rows: readonly ConversationSummary[]) => ConversationSummary[];\n /** The user's other open tabs, which share the lists they read. */\n tabShare: SessionListTabShare;\n}\n\nexport const AthenaSessionsLiveContext = createContext<AthenaSessionsLiveState | null>(null);\n\n/**\n * The statewire thread list reads one live page through the shared\n * conversation-list contract; the REST default page size predates the shared\n * pager and is preserved here.\n */\nconst THREAD_LIST_PAGE_SIZE = 50;\nconst EMPTY_THREAD_IDS: ReadonlySet<string> = new Set();\n/** The most pinned pages the sidebar reads: 500 pinned sessions. */\nconst MAX_PINNED_PAGES = 10;\n\nfunction StatewireThreadListState({\n backendUrl,\n syncUrl,\n apiKey,\n token,\n getToken,\n appId,\n additionalListAppIds,\n homeAgentId,\n initialThreadId,\n includePullRequests,\n snapshotCache,\n children,\n}: {\n backendUrl: string;\n syncUrl?: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n appId?: string;\n additionalListAppIds?: readonly string[];\n homeAgentId?: string;\n initialThreadId?: string;\n includePullRequests: boolean;\n snapshotCache?: DeepAgentThreadSnapshotCache;\n children: ReactNode;\n}) {\n const [active, setActive] = useState<{ id: string; isNew: boolean }>(() =>\n initialThreadId\n ? { id: initialThreadId, isNew: false }\n : { id: mintThreadId(), isNew: true },\n );\n const [search, setSearch] = useState('');\n\n const tokenRef = useRef(token);\n tokenRef.current = token;\n const apiKeyRef = useRef(apiKey);\n apiKeyRef.current = apiKey;\n const getTokenRef = useRef(getToken);\n getTokenRef.current = getToken;\n\n // The cache must be keyed by WHO is asking. Keying on `backendUrl`/`appId`\n // alone let a token swap to a different user read the previous user's thread\n // titles out of the cache. The principal is a non-secret user id, so no\n // credential enters the key (or React Query's devtools). The shared pager\n // never serves placeholder rows across keys, so another principal's list is\n // never shown while the new one loads.\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n // A live token getter is a credential too: a `getToken`-only host\n // authenticates its chat, so its list must not stay empty.\n const hasAuth = !!(apiKey || token || getToken);\n\n // Resolved per request with the attach's token semantics (getter first,\n // host-held token as the fallback) so a rotated token is never stale;\n // `force` renews a token the host just refused (`withCredentialRenewal`).\n const getAuth = useCallback(\n async (options?: { force?: boolean }) => ({\n apiKey: apiKeyRef.current,\n token: await resolveStatewireAuthToken(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n { staleAuth: options?.force ?? false },\n ),\n }),\n [],\n );\n const fetchPage = useMemo(\n () => createRestConversationListFetcher({ backendUrl, includePullRequests, getAuth }),\n [backendUrl, includePullRequests, getAuth],\n );\n const trimmedSearch = search.trim();\n // A stable key, so a host passing a fresh array each render does not refetch; JSON keeps each\n // id exact (no separator an id could contain).\n const additionalListAppIdsKey = JSON.stringify(additionalListAppIds ?? []);\n const listedAppIds = useMemo<readonly string[]>(\n () => JSON.parse(additionalListAppIdsKey) as string[],\n [additionalListAppIdsKey],\n );\n // The home agent is part of the filter, so of every cache key the list reads: a page read with\n // the agent's conversations is never served to the list without them, nor the other way round.\n const filter = useMemo<ConversationListFilter>(\n () => ({\n ...(appId ? { appId } : {}),\n ...(listedAppIds.length > 0 ? { appIds: listedAppIds } : {}),\n ...(homeAgentId ? { homeAgentId } : {}),\n ...(trimmedSearch ? { search: trimmedSearch } : {}),\n }),\n [appId, listedAppIds, homeAgentId, trimmedSearch],\n );\n // Pull-request opt-in changes what a cached row holds, so it is part of\n // the cache identity.\n const listScopeKey = `${backendUrl}::${principal}::${hasAuth ? 'auth' : 'anon'}::${\n includePullRequests ? 'prs' : 'no-prs'\n }`;\n const list = useConversationList({\n fetchPage,\n filter,\n pageSize: THREAD_LIST_PAGE_SIZE,\n scopeKey: listScopeKey,\n enabled: hasAuth,\n });\n // The pinned sessions are read on their own: `list` holds the newest\n // sessions only, so a session pinned long ago would leave the Pinned group\n // as soon as that many newer sessions exist. Same filter (app scope,\n // search), so a pinned row shows exactly where a listed one would.\n const fetchPinnedPage = useMemo(\n () =>\n createRestConversationListFetcher({\n backendUrl,\n includePullRequests,\n getAuth,\n extraFilters: { favorites_only: true },\n }),\n [backendUrl, includePullRequests, getAuth],\n );\n const pinnedScopeKey = `${listScopeKey}::pinned`;\n const pinnedList = useConversationList({\n fetchPage: fetchPinnedPage,\n filter,\n pageSize: THREAD_LIST_PAGE_SIZE,\n scopeKey: pinnedScopeKey,\n enabled: hasAuth,\n });\n // Every pin is listed, not only the first page of them: the later pinned\n // pages load one after another. Counting requests rather than rows bounds\n // the read even when a page repeats rows the pager already holds.\n const pinnedPagesRequested = useRef({ key: '', count: 0 });\n const pinnedRequestKey = `${pinnedScopeKey}::${JSON.stringify(filter)}`;\n if (pinnedPagesRequested.current.key !== pinnedRequestKey) {\n pinnedPagesRequested.current = { key: pinnedRequestKey, count: 0 };\n }\n const pinnedHasNextPage = pinnedList.hasNextPage;\n const pinnedIsFetchingNextPage = pinnedList.isFetchingNextPage;\n const pinnedNextPageFailed = pinnedList.isFetchNextPageError;\n const pinnedFetchNextPage = pinnedList.fetchNextPage;\n useEffect(() => {\n if (!pinnedHasNextPage || pinnedIsFetchingNextPage || pinnedNextPageFailed) return;\n if (pinnedPagesRequested.current.count >= MAX_PINNED_PAGES - 1) return;\n pinnedPagesRequested.current.count += 1;\n void pinnedFetchNextPage();\n }, [pinnedHasNextPage, pinnedIsFetchingNextPage, pinnedNextPageFailed, pinnedFetchNextPage]);\n const listedConversations = useMemo(\n () =>\n withPinnedConversations({\n conversations: list.conversations,\n pinned: pinnedList.conversations,\n }),\n [list.conversations, pinnedList.conversations],\n );\n\n // Live rows ride the signed-in user's conversation index — the same push\n // channel the conversation-history panel renders from: the host replicates\n // title, lifecycle, attention and creation changes as ops, so a\n // freshly-started thread's server-generated title (or a session flipping to\n // \"needs you\") lands without polling. The index is one instance per\n // `(workspace, user)` in agora's ids, so the pair is resolved from the\n // backend once a principal is known and the index only attaches once both\n // halves are; API-key-only hosts keep the bounded REST poll\n // (`titleSource: 'poll'`).\n const indexHeaders = useCallback<DeepAgentHeadersResolver>(\n (ctx) =>\n resolveStatewireAuthHeaders(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n ctx,\n ),\n [],\n );\n // The workspace half is the CREDENTIAL's: a scoped credential (sandbox,\n // preview, Office session) pins its own workspace, so swapping one for\n // another under the same principal must re-resolve the pair. The query is\n // therefore keyed by a credential generation — a counter that advances\n // whenever the host's credentials change — so no secret enters the key.\n const credentialsRef = useRef(credentialShape({ apiKey, token, getToken }));\n const credentialGenerationRef = useRef(0);\n const currentCredentials = credentialShape({ apiKey, token, getToken });\n if (!sameCredentialShape(credentialsRef.current, currentCredentials)) {\n credentialsRef.current = currentCredentials;\n credentialGenerationRef.current += 1;\n }\n const credentialGeneration = credentialGenerationRef.current;\n const identityEnabled = syncUrl !== undefined && principal.length > 0 && hasAuth;\n const identity = useQuery({\n // Keyed by the non-secret principal and credential generation, never the\n // credential itself.\n queryKey: ['athena-sdk', 'account-identity', backendUrl, principal, credentialGeneration],\n queryFn: ({ signal }) =>\n withCredentialRenewal(getAuth, (auth) => fetchAccountIdentity(backendUrl, auth, { signal })),\n enabled: identityEnabled,\n staleTime: Number.POSITIVE_INFINITY,\n });\n const indexWorkspaceId = identity.data?.workspaceId ?? '';\n const indexUserId = identity.data?.userId ?? '';\n const indexEnabled = identityEnabled && indexWorkspaceId.length > 0 && indexUserId.length > 0;\n const index = useConversationIndex({\n baseUrl: syncUrl === undefined ? '' : conversationIndexUrlFromStatewireUrl(syncUrl),\n workspaceId: indexWorkspaceId || 'pending-workspace',\n userId: indexUserId || 'pending-user',\n headers: indexHeaders,\n enabled: indexEnabled,\n });\n // The index parks after repeated credential refusals; re-arm it as soon as\n // a new token exists so live rows resume without a reload.\n useRestartAfterAuthRefusal({\n connection: index.connection,\n reconnect: index.connection.reconnect,\n });\n const indexByThread = useMemo(() => {\n const entries = new Map<string, ConversationIndexEntry>();\n for (const entry of index.entries ?? []) entries.set(entry.thread_id, entry);\n return entries;\n }, [index.entries]);\n\n // Each fetched row folds its pushed index entry through the shared\n // `summaryFromConversationIndexEntry`, so titles, lifecycle and attention\n // update live while the fields the index never carries (pull requests,\n // the last wake) keep their fetched values. A pushed title that normalizes\n // to nothing falls back to the fetched one.\n const mergedConversations = useMemo(\n () => foldConversationIndex(listedConversations, indexByThread),\n [listedConversations, indexByThread],\n );\n // The server's answer to a write is patched into EVERY conversation list\n // cached under this provider (its own page, and any `SessionsPage` /\n // `Inbox` view) — the client is the provider's own, so nothing outside it\n // is touched.\n const queryClient = useQueryClient();\n const patchEveryList = useCallback(\n (threadId: string, patch: Partial<ConversationSummary>) =>\n patchConversationListCaches(queryClient, {\n match: (item) => item.threadId === threadId,\n patch,\n }),\n [queryClient],\n );\n // A pin toggle sits over the fold: the row flips at once, and a pushed\n // index entry that predates the write cannot clobber it. The override drops\n // once both sources report the toggled value.\n const pinnedListRefresh = pinnedList.refresh;\n const favorite = useThreadFavorite({\n backendUrl,\n principalId: principal,\n getAuth,\n rows: mergedConversations,\n onServerTruth: ({ threadId, isFavorited }) => {\n patchEveryList(threadId, { isFavorited });\n // A newly pinned session joins the pinned read, so it stays listed\n // once newer sessions push it out of `list`.\n if (isFavorited) void pinnedListRefresh();\n },\n });\n const favoriteOverrides = favorite.overrides;\n // A rename sits over the fold the same way: the row shows the new title\n // at once, and a pushed index entry that predates the write cannot restore\n // the old one. The override drops once both sources report the new title.\n const rename = useThreadRename({\n backendUrl,\n principalId: principal,\n getAuth,\n rows: mergedConversations,\n onServerTruth: ({ threadId, title }) => patchEveryList(threadId, { title }),\n });\n const titleOverrides = rename.overrides;\n // Read state likewise; the read-state route publishes no index update, so\n // the override is what keeps a stale pushed `is_unread` from flipping the\n // row back until the index's next rebuild agrees.\n const readState = useThreadReadState({\n backendUrl,\n principalId: principal,\n getAuth,\n rows: mergedConversations,\n onServerTruth: ({ threadId, isUnread }) => patchEveryList(threadId, { isUnread }),\n });\n const readOverrides = readState.overrides;\n const readCoveredUpdatedAt = readState.coveredUpdatedAt;\n\n // An archive hides the row at once and keeps it hidden until neither list\n // source reports it any more — the cached page is patched on the server's\n // answer, but the pushed index may still carry the row until the publish\n // that follows the commit lands. A failure drops the id and the row comes\n // back from the still-cached page: no refetch needed. Scoping, the\n // one-write-per-thread guard and the route-missing fallback live in the hook.\n const archive = useThreadArchive({\n backendUrl,\n principalId: principal,\n getAuth,\n onArchived: (threadId) => {\n removeConversationFromListCaches(queryClient, { threadId });\n // The archived session cannot stay the active chat: the server no\n // longer lists it, so the chat moves to a fresh one.\n setActive((current) =>\n current.id === threadId ? { id: mintThreadId(), isNew: true } : current,\n );\n },\n });\n const hiddenThreadIds = archive.hiddenThreadIds;\n const archiveRelease = archive.release;\n // A hidden row is released once both sources have forgotten it, so a\n // session archived elsewhere and then restored is never masked here.\n useEffect(() => {\n if (hiddenThreadIds.size === 0) return;\n const forgotten = [...hiddenThreadIds].filter(\n (threadId) =>\n !mergedConversations.some((conversation) => conversation.threadId === threadId) &&\n !indexByThread.has(threadId),\n );\n if (forgotten.length > 0) archiveRelease(forgotten);\n }, [hiddenThreadIds, mergedConversations, indexByThread, archiveRelease]);\n\n const applyOverrides = useCallback(\n (rows: readonly ConversationSummary[]) =>\n withReadStateOverrides(\n withTitleOverrides(withFavoriteOverrides(rows, favoriteOverrides), titleOverrides),\n readOverrides,\n readCoveredUpdatedAt,\n ).filter((conversation) => !hiddenThreadIds.has(conversation.threadId)),\n [favoriteOverrides, titleOverrides, readOverrides, readCoveredUpdatedAt, hiddenThreadIds],\n );\n const data = useMemo(\n () => applyOverrides(mergedConversations).map(threadSummaryFromConversation),\n [applyOverrides, mergedConversations],\n );\n const isLoading = list.isLoading;\n\n // The active thread's row must survive a search that filters it out of\n // the page (the banner above the chat reads it): the listed row when there\n // is one, else the pushed index entry folded over the last row seen for\n // this thread (so pull requests survive the fold), else that last row.\n const lastActiveConversationRef = useRef<ConversationSummary | null>(null);\n const activeConversation = useMemo<ConversationSummary | null>(() => {\n const listed = mergedConversations.find((conversation) => conversation.threadId === active.id);\n if (listed) return listed;\n const remembered =\n lastActiveConversationRef.current?.threadId === active.id\n ? lastActiveConversationRef.current\n : undefined;\n const entry = indexByThread.get(active.id);\n if (entry) return summaryFromConversationIndexEntry(entry, remembered);\n return remembered ?? null;\n }, [mergedConversations, indexByThread, active.id]);\n if (activeConversation !== null) lastActiveConversationRef.current = activeConversation;\n const activeThread = useMemo(\n () =>\n activeConversation\n ? threadSummaryFromConversation(\n withReadStateOverrides(\n [\n withTitleOverride(\n withFavoriteOverride(activeConversation, favoriteOverrides),\n titleOverrides,\n ),\n ],\n readOverrides,\n readCoveredUpdatedAt,\n )[0] ?? activeConversation,\n )\n : null,\n [activeConversation, favoriteOverrides, titleOverrides, readOverrides, readCoveredUpdatedAt],\n );\n\n const listRefresh = list.refresh;\n const pinnedFetchingRef = useRef(pinnedList.isFetching);\n pinnedFetchingRef.current = pinnedList.isFetching;\n const refresh = useCallback(() => {\n void listRefresh();\n // A pinned read still in flight is left to finish: a refresh restarts it, so the title\n // poll's ticks would never let a pinned read slower than their interval answer.\n if (!pinnedFetchingRef.current) void pinnedListRefresh();\n }, [listRefresh, pinnedListRefresh]);\n const listFetchNextPage = list.fetchNextPage;\n const fetchNextPage = useCallback(() => {\n void listFetchNextPage();\n }, [listFetchNextPage]);\n\n // A thread the index knows — created here on first send, or elsewhere —\n // that the REST page does not list yet refreshes the page so the row\n // appears without the user pressing refresh. Rows for apps this list does\n // not show (its `appId` and `additionalListAppIds`) never trigger one; a\n // conversation with the home agent (a Slack thread started while the app is\n // open) does once the page said the server lists them. The refreshes are\n // coalesced, held while the page is already being read, and a refused one\n // is tried again (`useIndexTriggeredRefresh`).\n const listedThreadIds = useMemo(\n () => new Set(list.conversations.map((conversation) => conversation.threadId)),\n [list.conversations],\n );\n const homeAgentApplied = list.homeAgentApplied;\n const unlistedIndexedThreads = useMemo(\n () =>\n index.entries === null\n ? []\n : indexedThreadsToRefreshFor({\n entries: index.entries,\n listedThreadIds,\n refreshedThreadIds: EMPTY_THREAD_IDS,\n appId,\n additionalAppIds: listedAppIds,\n homeAgentId,\n homeAgentApplied,\n }),\n [index.entries, listedThreadIds, appId, listedAppIds, homeAgentId, homeAgentApplied],\n );\n // The user's other open tabs heard the same push: one of them reads the\n // page and shares it with the rest (`session-list-tab-share.ts`).\n const tabShare = useSessionListTabShare({\n queryClient,\n identity:\n indexWorkspaceId && indexUserId\n ? { backendUrl, userId: indexUserId, workspaceId: indexWorkspaceId }\n : null,\n });\n const listShareKey = sessionListShareKey(\n conversationListQueryKeys.firstPage(\n listScopeKey,\n conversationListFilterKey(filter),\n THREAD_LIST_PAGE_SIZE,\n ),\n );\n useIndexTriggeredRefresh({\n pending: unlistedIndexedThreads,\n refresh: listRefresh,\n // Held only while the page is being read (its first read and that read's\n // own retries included). A first page that was refused does not hold it:\n // the index-triggered refresh is then how the list recovers.\n enabled: hasAuth && index.entries !== null && !list.isFetching,\n tabShare,\n shareKey: listShareKey,\n });\n\n const selectThread = useCallback((threadId: string, options?: { isNew?: boolean }) => {\n if (!threadId) return;\n const isNew = options?.isNew === true;\n setActive((current) => (current.id === threadId ? current : { id: threadId, isNew }));\n }, []);\n\n // The hover prefetcher is one per (backend, principal, credential\n // generation): a credential swap clears the provider's snapshot cache, so\n // the attempt ledger resets with it and a late answer from the previous\n // identity is never remembered under the new one.\n const prefetchScope = `${backendUrl}::${principal}::${credentialGeneration}`;\n const prefetchScopeRef = useRef(prefetchScope);\n prefetchScopeRef.current = prefetchScope;\n const prefetcher = useMemo(() => {\n if (!snapshotCache) return null;\n const scope = prefetchScope;\n return createThreadPrefetcher({\n cache: snapshotCache,\n fetchState: async (threadId) =>\n withCredentialRenewal(getAuth, (auth) =>\n getThreadState(backendUrl, auth, threadId, { skipCache: false }),\n ),\n isCurrent: () => prefetchScopeRef.current === scope,\n });\n }, [snapshotCache, prefetchScope, backendUrl, getAuth]);\n const activeIdRef = useRef(active.id);\n activeIdRef.current = active.id;\n const prefetchThread = useCallback(\n (threadId: string) => {\n if (!prefetcher || !threadId || threadId === activeIdRef.current) return;\n prefetcher.prefetch(threadId);\n },\n [prefetcher],\n );\n\n const newThread = useCallback(() => {\n setActive({ id: mintThreadId(), isNew: true });\n }, []);\n\n // A minted thread stops being \"new\" once the backend lists it — on the\n // fetched page or in the pushed index (a search may keep it off the page):\n // until then `useAthenaThreadManager` reports a null id, so URL sync cannot\n // name it.\n const isPersisted =\n data.some((thread) => thread.id === active.id) || indexByThread.has(active.id);\n useEffect(() => {\n if (isPersisted) {\n setActive((current) => (current.isNew ? { ...current, isNew: false } : current));\n }\n }, [isPersisted]);\n\n const titleSource: AthenaStatewireThreadListState['titleSource'] =\n index.entries !== null ? 'index' : 'poll';\n\n const value = useMemo<AthenaStatewireThreadListState>(\n () => ({\n threads: data,\n isLoading,\n isFetching: list.isFetching,\n hasResolvedFirstPage: list.hasResolvedFirstPage,\n activeThreadId: active.id,\n activeThread,\n isNewChat: active.isNew,\n selectThread,\n prefetchThread,\n newThread,\n refresh,\n search,\n setSearch,\n hasNextPage: list.hasNextPage,\n isFetchingNextPage: list.isFetchingNextPage,\n fetchNextPage,\n setFavorited: favorite.setFavorited,\n favoritePending: favorite.isPending,\n favoritePendingThreadIds: favorite.pendingThreadIds,\n favoriteToggleAvailable: favorite.isAvailable,\n renameThread: rename.rename,\n renamePendingThreadIds: rename.pendingThreadIds,\n renameAvailable: rename.isAvailable,\n archiveThread: archive.archive,\n archivePendingThreadIds: archive.pendingThreadIds,\n archivePending: archive.isPending,\n archiveAvailable: archive.isAvailable,\n setReadState: readState.setReadState,\n readStatePendingThreadIds: readState.pendingThreadIds,\n titleSource,\n }),\n [\n data,\n isLoading,\n list.isFetching,\n list.hasResolvedFirstPage,\n active.id,\n activeThread,\n active.isNew,\n selectThread,\n prefetchThread,\n newThread,\n refresh,\n search,\n list.hasNextPage,\n list.isFetchingNextPage,\n fetchNextPage,\n favorite.setFavorited,\n favorite.isPending,\n favorite.pendingThreadIds,\n favorite.isAvailable,\n rename.rename,\n rename.pendingThreadIds,\n rename.isAvailable,\n archive.archive,\n archive.pendingThreadIds,\n archive.isPending,\n archive.isAvailable,\n readState.setReadState,\n readState.pendingThreadIds,\n titleSource,\n ],\n );\n\n const live = useMemo<AthenaSessionsLiveState>(\n () => ({\n backendUrl,\n getAuth,\n principal,\n hasAuth,\n includePullRequests,\n scopeKey: listScopeKey,\n credentialGeneration,\n baseFilter: {\n ...(appId ? { appId } : {}),\n ...(listedAppIds.length > 0 ? { appIds: listedAppIds } : {}),\n ...(homeAgentId ? { homeAgentId } : {}),\n },\n indexByThread,\n indexEntries: index.entries,\n applyOverrides,\n tabShare,\n }),\n [\n backendUrl,\n getAuth,\n principal,\n hasAuth,\n includePullRequests,\n listScopeKey,\n credentialGeneration,\n appId,\n listedAppIds,\n homeAgentId,\n indexByThread,\n index.entries,\n applyOverrides,\n tabShare,\n ],\n );\n\n return (\n <AthenaStatewireThreadListContext.Provider value={value}>\n <AthenaSessionsLiveContext.Provider value={live}>{children}</AthenaSessionsLiveContext.Provider>\n </AthenaStatewireThreadListContext.Provider>\n );\n}\n\n/**\n * Provides the statewire thread-list state, with an SDK-scoped QueryClient so\n * consumers do not need their own QueryClientProvider. `syncUrl` (the\n * `…/v2/threads` mount) locates the conversation index beside it; without it\n * titles fall back to the REST poll. `includePullRequests` (default `true`)\n * asks the list for live pull-request state so `SessionList` can render its\n * chips; a host that never shows them turns it off to spare the server the\n * lookup. `snapshotCache` is the provider's thread snapshot cache — the one\n * the runtime seeds a switched-to thread from — which `prefetchThread` warms;\n * without it prefetching is a no-op.\n */\nexport function AthenaStatewireThreadListProvider({\n backendUrl,\n syncUrl,\n apiKey,\n token,\n getToken,\n appId,\n additionalListAppIds,\n homeAgentId,\n initialThreadId,\n includePullRequests = true,\n snapshotCache,\n offlineList,\n children,\n}: {\n backendUrl: string;\n syncUrl?: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n appId?: string;\n /** Other client apps whose sessions the list shows too (a union with `appId`). */\n additionalListAppIds?: readonly string[];\n /**\n * The collab agent (`asset_<uuid>`) whose home this app is: every list read asks the server to\n * hold the conversations with it too (`home_agent_id`).\n */\n homeAgentId?: string;\n initialThreadId?: string;\n includePullRequests?: boolean;\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /**\n * Keep the list's first pages on this device, sealed (`AthenaProvider`'s `offlineHistory`): they\n * paint at once and read while Athena can't be reached.\n */\n offlineList?: { mirror: ThreadSnapshotMirror; ownerId: string };\n children: ReactNode;\n}) {\n const [queryClient] = useState(() => new QueryClient());\n useOfflineSessionList({ queryClient, offlineList });\n return (\n <QueryClientProvider client={queryClient}>\n <StatewireThreadListState\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n appId={appId}\n additionalListAppIds={additionalListAppIds}\n homeAgentId={homeAgentId}\n initialThreadId={initialThreadId}\n includePullRequests={includePullRequests}\n snapshotCache={snapshotCache}\n >\n {children}\n </StatewireThreadListState>\n </QueryClientProvider>\n );\n}\n\n/** How long after a thread's first message the title poll starts (exported for tests). */\nexport const TITLE_POLL_DELAY_MS = 5000;\nconst TITLE_POLL_INTERVAL_MS = 2000;\nconst TITLE_POLL_MAX_DURATION_MS = 60_000;\n\n/**\n * Fallback for hosts without a live conversation index (`titleSource: 'poll'`,\n * i.e. no signed-in principal): refreshes the thread list until a\n * freshly-started thread's server-generated title appears. Idle while the\n * index carries titles. Mount inside the statewire runtime scope (needs aui\n * state).\n *\n * The thread is read from the statewire scope, not the list: the scope\n * publishes the id together with the client it belongs to, so the messages\n * observed here are always the named thread's (the list's selection moves\n * one commit ahead of the client during a switch).\n */\nexport function StatewireThreadTitlePoller(): null {\n const list = useAthenaStatewireThreadList();\n const activeThreadId = useAthenaStatewireThreadId();\n const hasMessages = useAuiState((s) => (s.optional.thread?.messages.length ?? 0) > 0);\n\n const titleSource = list?.titleSource ?? 'poll';\n const entry = list?.threads.find((thread) => thread.id === activeThreadId);\n const title = entry?.title?.trim() ?? '';\n const hasTitle = title.length > 0 && !isSerializedContentPartsTitle(title);\n\n // The poller stays mounted across thread switches, so the visit is tracked\n // by hand: one poll per visit — no restart when the visited thread's\n // messages or title flip underneath it — and a re-selected thread polls\n // again, as it did when every switch remounted the poller. The record is\n // replaced whenever the attached thread changes, whether or not a poll\n // started for it, so a visit to a thread that needs no poll can never make\n // the next visit to a previous thread look already polled.\n const visitRef = useRef<{ threadId: string; polled: boolean } | null>(null);\n const refreshRef = useRef(list?.refresh);\n refreshRef.current = list?.refresh;\n const fetchingRef = useRef(list?.isFetching ?? false);\n fetchingRef.current = list?.isFetching ?? false;\n\n useEffect(() => {\n if (visitRef.current?.threadId !== activeThreadId) {\n visitRef.current = { threadId: activeThreadId, polled: false };\n }\n const visit = visitRef.current;\n if (!hasMessages || hasTitle || titleSource === 'index') return;\n if (visit.polled) return;\n visit.polled = true;\n\n let intervalId: ReturnType<typeof setInterval> | null = null;\n const startId = setTimeout(() => {\n // A tick while the list's last read is still on its way waits for it: a refresh restarts\n // the read, so against a server slower than the interval no read would ever finish and\n // the new thread would stay unlisted until the poll gives up.\n intervalId = setInterval(() => {\n if (!fetchingRef.current) refreshRef.current?.();\n }, TITLE_POLL_INTERVAL_MS);\n }, TITLE_POLL_DELAY_MS);\n const stopId = setTimeout(() => {\n if (intervalId !== null) clearInterval(intervalId);\n }, TITLE_POLL_MAX_DURATION_MS);\n\n return () => {\n clearTimeout(startId);\n clearTimeout(stopId);\n if (intervalId !== null) clearInterval(intervalId);\n };\n }, [activeThreadId, hasMessages, hasTitle, titleSource]);\n\n return null;\n}\n"],"names":["createContext","useContext","normalizeThreadTitle","deriveConversationAttention","summaryFromConversationIndexEntry","useState","mintThreadId","useRef","AthenaAuthContext","useCallback","resolveStatewireAuthToken","useMemo","createRestConversationListFetcher","useConversationList","useEffect","resolveStatewireAuthHeaders","credentialShape","sameCredentialShape","useQuery","withCredentialRenewal","fetchAccountIdentity","useConversationIndex","conversationIndexUrlFromStatewireUrl","useRestartAfterAuthRefusal","useQueryClient","patchConversationListCaches","useThreadFavorite","useThreadRename","title","useThreadReadState","useThreadArchive","removeConversationFromListCaches","withReadStateOverrides","withTitleOverrides","withFavoriteOverrides","_a","withTitleOverride","withFavoriteOverride","useSessionListTabShare","sessionListShareKey","conversationListQueryKeys","conversationListFilterKey","useIndexTriggeredRefresh","createThreadPrefetcher","getThreadState","jsx","QueryClient","useOfflineSessionList","QueryClientProvider","useAthenaStatewireThreadId","useAuiState","isSerializedContentPartsTitle"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA+PO,MAAM,mCACXA,WAAAA,cAAqD,IAAI;AAGpD,SAAS,+BAAsE;AACpF,SAAOC,WAAAA,WAAW,gCAAgC;AACpD;AAGO,SAAS,uBAA4C;;AAC1D,WAAO,kCAAA,MAAA,mBAAgC,YAAW;AACpD;AAOA,MAAM,yDAA8D,IAAI;AAAA,EACtE;AAAA,EACA;AACF,CAAC;AAOD,SAAS,sBACP,OACA,aACS;AACT,MAAI,CAAC,eAAe,MAAM,oBAAoB,YAAa,QAAO;AAClE,SAAO,CAAC,mCAAmC,IAAI,MAAM,iBAAiB,EAAE;AAC1E;AAWO,SAAS,2BAA2B;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAmB;AACrB,GAaa;AACX,QAAM,cACJ,SAAS,iBAAiB,SAAS,IAC/B,oBAAI,IAAI,CAAC,GAAI,QAAQ,CAAC,KAAK,IAAI,CAAA,GAAK,GAAG,gBAAgB,CAAC,IACxD;AACN,QAAM,gBAAgB,mBAAmB,cAAc;AACvD,SAAO,QACJ;AAAA,IACC,CAAC,UACC,CAAC,eACD,YAAY,IAAI,MAAM,UAAU,EAAE,KAClC,sBAAsB,OAAO,aAAa;AAAA,EAAA,EAE7C,IAAI,CAAC,UAAU,MAAM,SAAS,EAC9B,OAAO,CAAC,aAAa,C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O,aAAAA,UAAU,MAAM;;AACd,UAAIqB,MAAA,SAAS,YAAT,gBAAAA,IAAkB,cAAa,gBAAgB;AACjD,eAAS,UAAU,EAAE,UAAU,gBAAgB,QAAQ,MAAA;AAAA,IACzD;AACA,UAAM,QAAQ,SAAS;AACvB,QAAI,CAAC,eAAe,YAAY,gBAAgB,QAAS;AACzD,QAAI,MAAM,OAAQ;AAClB,UAAM,SAAS;AAEf,QAAI,aAAoD;AACxD,UAAM,UAAU,WAAW,MAAM;AAI/B,mBAAa,YAAY,MAAM;;AAC7B,YAAI,CAAC,YAAY,QAAS,EAAAA,MAAA,WAAW,YAAX,gBAAAA,IAAA;AAAA,MAC5B,GAAG,sBAAsB;AAAA,IAC3B,GAAG,mBAAmB;AACtB,UAAM,SAAS,WAAW,MAAM;AAC9B,UAAI,eAAe,KAAM,eAAc,UAAU;AAAA,IACnD,GAAG,0BAA0B;AAE7B,WAAO,MAAM;AACX,mBAAa,OAAO;AACpB,mBAAa,MAAM;AACnB,UAAI,eAAe,KAAM,eAAc,UAAU;AAAA,IACnD;AAAA,EACF,GAAG,CAAC,gBAAgB,aAAa,UAAU,WAAW,CAAC;AAEvD,SAAO;AACT;;;;;;;;;;;;"}
1
+ {"version":3,"file":"statewire-thread-list.cjs","sources":["../../src/threads/statewire-thread-list.tsx"],"sourcesContent":["import {\n type ConversationAttention,\n type ConversationAttentionSource,\n type ConversationIndexEntry,\n type ConversationListFilter,\n type ConversationPullRequest,\n type ConversationSummary,\n type ConversationWake,\n conversationIndexUrlFromStatewireUrl,\n conversationListFilterKey,\n conversationListQueryKeys,\n type DeepAgentHeadersResolver,\n type DeepAgentThreadSnapshotCache,\n deriveConversationAttention,\n patchConversationListCaches,\n removeConversationFromListCaches,\n summaryFromConversationIndexEntry,\n type ThreadSnapshotMirror,\n useConversationIndex,\n useConversationList,\n} from '@athenaintel/agent-runtime';\nimport { useOfflineSessionList } from './offline-session-list';\nimport { QueryClient, QueryClientProvider, useQueryClient } from '@tanstack/react-query';\nimport { useAuiState } from '@assistant-ui/react';\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport { useAccountIdentityQuery } from '../auth/account-identity';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n resolveStatewireAuthToken,\n} from '../runtime/statewire-auth-headers';\nimport { getThreadState } from './api';\nimport { createRestConversationListFetcher } from './conversation-list-fetcher';\nimport { credentialShape, sameCredentialShape } from './credential-shape';\nimport { mintThreadId } from './mint-thread-id';\nimport { useAthenaStatewireThreadId } from './thread-id-context';\nimport { createThreadPrefetcher } from './thread-prefetcher';\nimport { useIndexTriggeredRefresh } from './index-triggered-refresh';\nimport {\n type SessionListTabShare,\n sessionListShareKey,\n useSessionListTabShare,\n} from './session-list-tab-share';\nimport { isSerializedContentPartsTitle, normalizeThreadTitle } from './title';\nimport { useRestartAfterAuthRefusal } from '../runtime/auth-refusal-restart';\nimport { type CredentialResolver, withCredentialRenewal } from '../runtime/credential-renewal';\nimport { useThreadArchive } from './use-thread-archive';\nimport {\n type ThreadFavoriteTarget,\n useThreadFavorite,\n withFavoriteOverride,\n withFavoriteOverrides,\n} from './use-thread-favorite';\nimport {\n type ThreadReadStateTarget,\n useThreadReadState,\n withReadStateOverrides,\n} from './use-thread-read-state';\nimport {\n type ThreadRenameTarget,\n useThreadRename,\n withTitleOverride,\n withTitleOverrides,\n} from './use-thread-rename';\n\n/**\n * One row of the thread list — the fields a Devin-style session list renders\n * (`SessionList`), all read from the shared conversation-list contract. The\n * attention fields are `null` on a server that does not derive them; the\n * pull-request state is `null` until the list has fetched it (or when the\n * provider opted out of it).\n */\nexport interface AthenaStatewireThreadSummary {\n id: string;\n title: string | null;\n /**\n * What the session asks of the viewer: the server-derived state when\n * reported, else the client fallback from the status planes\n * (`deriveConversationAttention`).\n */\n attention: ConversationAttention | null;\n /** One line (≤ 80 chars) of what the viewer should do next, when the server derives one. */\n nextAction: string | null;\n attentionSource: ConversationAttentionSource | null;\n /**\n * Whether the viewer pinned the session. Toggled through\n * `AthenaStatewireThreadListState.setFavorited`; a toggle in flight is\n * reflected here at once and held until the list sources report it.\n */\n isFavorited: boolean;\n isUnread: boolean;\n /** Canonical status_v2 planes, or `null` on an older server. */\n sessionStatus: string | null;\n runStatus: string | null;\n /** Channel the session was started from (e.g. `web`, `github`, `api`). */\n startChannel: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Pull requests the session opened with their live GitHub state. */\n pullRequests: ConversationPullRequest[] | null;\n /** The last wake of a resting session. */\n lastWake: ConversationWake | null;\n /** ISO 8601 timestamp of the last update (the list's sort key). */\n updatedAt: string;\n /** ISO 8601 creation time; `null` when the list did not report it. */\n createdAt?: string | null;\n /** The session's last message, for a preview line (the inbox excerpt). */\n preview?: string | null;\n /** The collab agent the session started as, and its channel (`null`: the default channel). */\n collabAgentId?: string | null;\n collabChannelId?: string | null;\n /** Whether the viewer started the session (`false`: shared with them); `null` when not reported. */\n createdByMe?: boolean | null;\n}\n\n/**\n * Thread-list state. The list is the persisted Agora session list; the ACTIVE\n * thread is a plain id the statewire runtime attaches to — switching threads\n * remounts the statewire session against the new `…/v2/threads/{id}` URL\n * (the same model the mobile app uses).\n */\nexport interface AthenaStatewireThreadListState {\n /** The rows the current `search` lists, newest first. */\n threads: AthenaStatewireThreadSummary[];\n isLoading: boolean;\n /** True while the live first page (or a history page) is being fetched. */\n isFetching: boolean;\n /**\n * True once the live first page has answered at least once for the current\n * search and identity. Until then an empty `threads` means \"not known\n * yet\" (no credential resolved, first page in flight), not \"no sessions\":\n * `SessionList` shows skeleton rows, never the empty state.\n */\n hasResolvedFirstPage: boolean;\n activeThreadId: string;\n /**\n * The active thread's row, independent of what `threads` currently lists:\n * a search that hides the row, or a page that has not fetched it, must not\n * make the active chat's attention disappear. Resolved from the listed row,\n * else the pushed index entry folded over the last row seen, else that\n * last row; `null` for a never-started chat the backend does not know yet.\n */\n activeThread: AthenaStatewireThreadSummary | null;\n /** True while the active thread is a locally-minted chat with no server history. */\n isNewChat: boolean;\n /**\n * Switch to `threadId`; `isNew` for a chat this page minted that never started (it loads as a\n * new chat until the list has it), e.g. one holding messages that wait in the chat outbox.\n */\n selectThread: (threadId: string, options?: { isNew?: boolean }) => void;\n /**\n * Warm the provider's snapshot cache with a thread's REST state ahead of a\n * `selectThread`, so the switch paints the transcript on its first frame\n * instead of the loading scrim while the statewire attach lands.\n * `SessionList` calls it after a 120 ms hover dwell and on row focus.\n * Fetches once per thread per identity, deduplicates requests in flight,\n * runs at most two at a time and ignores failures; a no-op for the active\n * thread, a thread the cache already holds, or a provider without a cache.\n */\n prefetchThread: (threadId: string) => void;\n newThread: () => void;\n refresh: () => void;\n /**\n * Server-side title search (`search` on the REST thread list). An empty\n * string lists everything; the search covers the viewer's whole authorized\n * history, not just the live page.\n */\n search: string;\n setSearch: (search: string) => void;\n /** Whether another page of older sessions can be fetched. */\n hasNextPage: boolean;\n isFetchingNextPage: boolean;\n /** Fetch the next page of older sessions (frozen history pages, never replayed). */\n fetchNextPage: () => void;\n /**\n * Pin or unpin a session (`POST /api/conversations/threads/favorite`). The\n * row flips at once and moves between the `Pinned` and `Recent` groups; the\n * server's answer is written back, and a failure restores the previous\n * state. Writes for one thread are serialized: a toggle while that\n * thread's write is in flight records the value and sends at most one\n * follow-up write once the first has answered.\n */\n setFavorited: (target: ThreadFavoriteTarget) => void;\n /** True while any pin toggle is in flight. */\n favoritePending: boolean;\n /** The sessions whose pin toggle is in flight; `SessionList` disables their pin control. */\n favoritePendingThreadIds: ReadonlySet<string>;\n /**\n * Whether the backend offers the favorite route. `false` once it answered\n * 404 / 405 (an agora that predates the route): `SessionList` then shows\n * the read-only pin and no toggle, and `setFavorited` keeps failing.\n */\n favoriteToggleAvailable: boolean;\n /**\n * Rename a session for every viewer (`POST /api/conversations/threads/rename`).\n * The row shows the new title at once; the server's stored title is\n * written back, and a failure restores the previous one. Same-thread\n * writes are serialized like the pin's.\n */\n renameThread: (target: ThreadRenameTarget) => void;\n /** The sessions whose rename is in flight; `SessionList` keeps their editor closed. */\n renamePendingThreadIds: ReadonlySet<string>;\n /**\n * Whether the backend offers the rename route. `false` once it answered\n * 404 / 405 (an agora that predates the route): `SessionList` then offers\n * no Rename action, and `renameThread` keeps failing.\n */\n renameAvailable: boolean;\n /**\n * Archive a session (`POST /api/conversations/threads/archive`). The row\n * leaves the list at once and stays hidden until both list sources stop\n * reporting it; a failure brings it back. Archiving the active session\n * moves the chat to a new one once the server has confirmed.\n */\n archiveThread: (threadId: string) => void;\n /** The sessions whose archive is in flight. */\n archivePendingThreadIds: ReadonlySet<string>;\n /** True while any archive is in flight. */\n archivePending: boolean;\n /**\n * Whether the backend offers the archive route. `false` once it answered\n * 404 / 405: `SessionList` then offers no Archive action.\n */\n archiveAvailable: boolean;\n /**\n * Mark a session read or unread for the viewer\n * (`POST /api/conversations/threads/read-state`). The row flips at once in\n * every list under the provider (`SessionList`, `SessionsPage`, `Inbox`);\n * the server's answer is written back, and a failure restores the previous\n * state. Same-thread writes are serialized like the pin's.\n */\n setReadState: (target: ThreadReadStateTarget) => void;\n /** The sessions whose read-state write is in flight. */\n readStatePendingThreadIds: ReadonlySet<string>;\n /**\n * Where titles come from. `'index'` once the signed-in user's live\n * conversation index has replicated — titles and newly created threads then\n * arrive as pushed updates; `'poll'` while it has not (no signed-in\n * principal, e.g. API-key mode, or before its snapshot), when a\n * freshly-started thread's title is picked up by the bounded REST poll.\n */\n titleSource: 'index' | 'poll';\n}\n\nexport const AthenaStatewireThreadListContext =\n createContext<AthenaStatewireThreadListState | null>(null);\n\n/** Read the statewire thread-list state, or null outside that mode. */\nexport function useAthenaStatewireThreadList(): AthenaStatewireThreadListState | null {\n return useContext(AthenaStatewireThreadListContext);\n}\n\n/** Trigger a re-fetch of the thread list. `null` outside `enableThreadList` mode. */\nexport function useRefreshThreadList(): (() => void) | null {\n return useAthenaStatewireThreadList()?.refresh ?? null;\n}\n\n/**\n * Start channels of an agent's sessions that the server leaves out when it lists the conversations\n * with a home agent (`home_agent_id`): the agent's tasks and the sessions an orchestrating agent\n * starts.\n */\nconst AGENT_HOME_EXCLUDED_START_CHANNELS: ReadonlySet<string> = new Set([\n 'task',\n 'agent_orchestration',\n]);\n\n/**\n * Whether a pushed index entry is one of the conversations with `homeAgentId`'s agent that the\n * server lists beside the app scope: the agent's, and not one of its tasks or orchestration\n * sessions. An entry from a pod that predates `collab_agent_id` is not.\n */\nfunction isAgentHomeIndexEntry(\n entry: { collab_agent_id?: string | null; start_channel?: string | null },\n homeAgentId: string | undefined,\n): boolean {\n if (!homeAgentId || entry.collab_agent_id !== homeAgentId) return false;\n return !AGENT_HOME_EXCLUDED_START_CHANNELS.has(entry.start_channel ?? '');\n}\n\n/**\n * The threads the conversation index knows that the fetched list does not show yet, and that have\n * not prompted a refresh before: each warrants one refresh of the list. Only threads of the apps\n * the list shows count (its `appId` and `additionalAppIds`); with neither, every app's do. With a\n * `homeAgentId`, the conversations with that agent count too, but only while `homeAgentApplied`\n * (the list's latest first page said the server listed them; absent counts as false): a server\n * that did not widen the list never lists them, so their updates must not refresh it.\n * Exported for tests.\n */\nexport function indexedThreadsToRefreshFor({\n entries,\n listedThreadIds,\n refreshedThreadIds,\n appId,\n additionalAppIds,\n homeAgentId,\n homeAgentApplied = false,\n}: {\n entries: ReadonlyArray<{\n thread_id: string;\n app_id: string | null;\n collab_agent_id?: string | null;\n start_channel?: string | null;\n }>;\n listedThreadIds: ReadonlySet<string>;\n refreshedThreadIds: ReadonlySet<string>;\n appId: string | undefined;\n additionalAppIds: readonly string[];\n homeAgentId?: string;\n homeAgentApplied?: boolean;\n}): string[] {\n const shownAppIds =\n appId || additionalAppIds.length > 0\n ? new Set([...(appId ? [appId] : []), ...additionalAppIds])\n : null;\n const listedAgentId = homeAgentApplied ? homeAgentId : undefined;\n return entries\n .filter(\n (entry) =>\n !shownAppIds ||\n shownAppIds.has(entry.app_id ?? '') ||\n isAgentHomeIndexEntry(entry, listedAgentId),\n )\n .map((entry) => entry.thread_id)\n .filter((threadId) => !listedThreadIds.has(threadId) && !refreshedThreadIds.has(threadId));\n}\n\n/**\n * Project one contract row onto the thread-list row. Exported for hosts (and\n * tests) that build rows from a `ConversationSummary` of their own.\n */\nexport function threadSummaryFromConversation(\n conversation: ConversationSummary,\n): AthenaStatewireThreadSummary {\n return {\n id: conversation.threadId,\n title: normalizeThreadTitle(conversation.title) ?? null,\n attention: deriveConversationAttention(conversation),\n nextAction: conversation.nextAction ?? null,\n attentionSource: conversation.attentionSource ?? null,\n isFavorited: conversation.isFavorited ?? false,\n isUnread: conversation.isUnread,\n sessionStatus: conversation.sessionStatus,\n runStatus: conversation.runStatus,\n startChannel: conversation.sourceChannel,\n appId: conversation.appId,\n triggerType: conversation.triggerType,\n pullRequests: conversation.pullRequests ?? null,\n lastWake: conversation.lastWake ?? null,\n updatedAt: conversation.updatedAt,\n createdAt: conversation.createdAt,\n preview: conversation.preview,\n collabAgentId: conversation.collabAgentId ?? null,\n collabChannelId: conversation.collabChannelId ?? null,\n createdByMe: conversation.createdByMe ?? null,\n };\n}\n\n/**\n * Fold the pushed conversation index into fetched rows: each row with an\n * index entry takes its pushed fields through the shared\n * `summaryFromConversationIndexEntry` (titles, lifecycle, attention), while\n * what the index never carries (pull requests, the last wake, who started\n * it) keeps the fetched value. A pushed title that normalizes to nothing\n * falls back to the fetched one. Exported for tests.\n */\nexport function foldConversationIndex(\n conversations: readonly ConversationSummary[],\n indexByThread: ReadonlyMap<string, ConversationIndexEntry>,\n): ConversationSummary[] {\n return conversations.map((conversation) => {\n const entry = indexByThread.get(conversation.threadId);\n if (!entry) return conversation;\n const merged = summaryFromConversationIndexEntry(entry, conversation);\n return normalizeThreadTitle(merged.title) === undefined\n ? { ...merged, title: conversation.title }\n : merged;\n });\n}\n\n/**\n * The listed rows plus the pinned rows they do not include, appended in the\n * pinned list's own newest-first order. A pinned row the list does not\n * include is older than the list's last row, so appending keeps the merged\n * rows newest-first. A row whose pin was just undone (`isFavorited: false`,\n * patched into every cached list) is not added back. Exported for tests.\n */\nexport function withPinnedConversations({\n conversations,\n pinned,\n}: {\n conversations: readonly ConversationSummary[];\n pinned: readonly ConversationSummary[];\n}): readonly ConversationSummary[] {\n const listed = new Set(conversations.map((conversation) => conversation.threadId));\n const unlisted = pinned.filter(\n (conversation) => conversation.isFavorited !== false && !listed.has(conversation.threadId),\n );\n return unlisted.length === 0 ? conversations : [...conversations, ...unlisted];\n}\n\n/**\n * What the thread-list provider shares with the other lists mounted under it\n * (`SessionsPage`, `Inbox`): the credential, the live conversation index and\n * the optimistic overrides (pin, title, read state, archived rows), so every\n * list folds the same pushes and shows the same in-flight writes. Internal —\n * hosts use `useAthenaSessions`.\n */\nexport interface AthenaSessionsLiveState {\n backendUrl: string;\n getAuth: CredentialResolver<{ apiKey?: string; token?: string | null }>;\n principal: string;\n hasAuth: boolean;\n includePullRequests: boolean;\n /** The provider list's cache scope (backend, principal, auth, PR opt-in). */\n scopeKey: string;\n /**\n * Advances whenever the host's credential changes (a swapped API key or\n * token, a scoped credential for another workspace under the same\n * principal), so caches keyed on it are never read with another credential.\n */\n credentialGeneration: number;\n /** The app scope the provider lists (`appId` / `additionalListAppIds` / `homeAgentId`). */\n baseFilter: ConversationListFilter;\n indexByThread: ReadonlyMap<string, ConversationIndexEntry>;\n /** `null` until the index has replicated (or without one). */\n indexEntries: readonly ConversationIndexEntry[] | null;\n /** Layer the in-flight writes over rows and drop archived ones. */\n applyOverrides: (rows: readonly ConversationSummary[]) => ConversationSummary[];\n /** The user's other open tabs, which share the lists they read. */\n tabShare: SessionListTabShare;\n}\n\nexport const AthenaSessionsLiveContext = createContext<AthenaSessionsLiveState | null>(null);\n\n/**\n * The statewire thread list reads one live page through the shared\n * conversation-list contract; the REST default page size predates the shared\n * pager and is preserved here.\n */\nconst THREAD_LIST_PAGE_SIZE = 50;\nconst EMPTY_THREAD_IDS: ReadonlySet<string> = new Set();\n/** The most pinned pages the sidebar reads: 500 pinned sessions. */\nconst MAX_PINNED_PAGES = 10;\n\nfunction StatewireThreadListState({\n backendUrl,\n syncUrl,\n apiKey,\n token,\n getToken,\n appId,\n additionalListAppIds,\n homeAgentId,\n initialThreadId,\n includePullRequests,\n snapshotCache,\n children,\n}: {\n backendUrl: string;\n syncUrl?: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n appId?: string;\n additionalListAppIds?: readonly string[];\n homeAgentId?: string;\n initialThreadId?: string;\n includePullRequests: boolean;\n snapshotCache?: DeepAgentThreadSnapshotCache;\n children: ReactNode;\n}) {\n const [active, setActive] = useState<{ id: string; isNew: boolean }>(() =>\n initialThreadId\n ? { id: initialThreadId, isNew: false }\n : { id: mintThreadId(), isNew: true },\n );\n const [search, setSearch] = useState('');\n\n const tokenRef = useRef(token);\n tokenRef.current = token;\n const apiKeyRef = useRef(apiKey);\n apiKeyRef.current = apiKey;\n const getTokenRef = useRef(getToken);\n getTokenRef.current = getToken;\n\n // The cache must be keyed by WHO is asking. Keying on `backendUrl`/`appId`\n // alone let a token swap to a different user read the previous user's thread\n // titles out of the cache. The principal is a non-secret user id, so no\n // credential enters the key (or React Query's devtools). The shared pager\n // never serves placeholder rows across keys, so another principal's list is\n // never shown while the new one loads.\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n // A live token getter is a credential too: a `getToken`-only host\n // authenticates its chat, so its list must not stay empty.\n const hasAuth = !!(apiKey || token || getToken);\n\n // Resolved per request with the attach's token semantics (getter first,\n // host-held token as the fallback) so a rotated token is never stale;\n // `force` renews a token the host just refused (`withCredentialRenewal`).\n const getAuth = useCallback(\n async (options?: { force?: boolean }) => ({\n apiKey: apiKeyRef.current,\n token: await resolveStatewireAuthToken(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n { staleAuth: options?.force ?? false },\n ),\n }),\n [],\n );\n const fetchPage = useMemo(\n () => createRestConversationListFetcher({ backendUrl, includePullRequests, getAuth }),\n [backendUrl, includePullRequests, getAuth],\n );\n const trimmedSearch = search.trim();\n // A stable key, so a host passing a fresh array each render does not refetch; JSON keeps each\n // id exact (no separator an id could contain).\n const additionalListAppIdsKey = JSON.stringify(additionalListAppIds ?? []);\n const listedAppIds = useMemo<readonly string[]>(\n () => JSON.parse(additionalListAppIdsKey) as string[],\n [additionalListAppIdsKey],\n );\n // The home agent is part of the filter, so of every cache key the list reads: a page read with\n // the agent's conversations is never served to the list without them, nor the other way round.\n const filter = useMemo<ConversationListFilter>(\n () => ({\n ...(appId ? { appId } : {}),\n ...(listedAppIds.length > 0 ? { appIds: listedAppIds } : {}),\n ...(homeAgentId ? { homeAgentId } : {}),\n ...(trimmedSearch ? { search: trimmedSearch } : {}),\n }),\n [appId, listedAppIds, homeAgentId, trimmedSearch],\n );\n // Pull-request opt-in changes what a cached row holds, so it is part of\n // the cache identity.\n const listScopeKey = `${backendUrl}::${principal}::${hasAuth ? 'auth' : 'anon'}::${\n includePullRequests ? 'prs' : 'no-prs'\n }`;\n const list = useConversationList({\n fetchPage,\n filter,\n pageSize: THREAD_LIST_PAGE_SIZE,\n scopeKey: listScopeKey,\n enabled: hasAuth,\n });\n // The pinned sessions are read on their own: `list` holds the newest\n // sessions only, so a session pinned long ago would leave the Pinned group\n // as soon as that many newer sessions exist. Same filter (app scope,\n // search), so a pinned row shows exactly where a listed one would.\n const fetchPinnedPage = useMemo(\n () =>\n createRestConversationListFetcher({\n backendUrl,\n includePullRequests,\n getAuth,\n extraFilters: { favorites_only: true },\n }),\n [backendUrl, includePullRequests, getAuth],\n );\n const pinnedScopeKey = `${listScopeKey}::pinned`;\n const pinnedList = useConversationList({\n fetchPage: fetchPinnedPage,\n filter,\n pageSize: THREAD_LIST_PAGE_SIZE,\n scopeKey: pinnedScopeKey,\n enabled: hasAuth,\n });\n // Every pin is listed, not only the first page of them: the later pinned\n // pages load one after another. Counting requests rather than rows bounds\n // the read even when a page repeats rows the pager already holds.\n const pinnedPagesRequested = useRef({ key: '', count: 0 });\n const pinnedRequestKey = `${pinnedScopeKey}::${JSON.stringify(filter)}`;\n if (pinnedPagesRequested.current.key !== pinnedRequestKey) {\n pinnedPagesRequested.current = { key: pinnedRequestKey, count: 0 };\n }\n const pinnedHasNextPage = pinnedList.hasNextPage;\n const pinnedIsFetchingNextPage = pinnedList.isFetchingNextPage;\n const pinnedNextPageFailed = pinnedList.isFetchNextPageError;\n const pinnedFetchNextPage = pinnedList.fetchNextPage;\n useEffect(() => {\n if (!pinnedHasNextPage || pinnedIsFetchingNextPage || pinnedNextPageFailed) return;\n if (pinnedPagesRequested.current.count >= MAX_PINNED_PAGES - 1) return;\n pinnedPagesRequested.current.count += 1;\n void pinnedFetchNextPage();\n }, [pinnedHasNextPage, pinnedIsFetchingNextPage, pinnedNextPageFailed, pinnedFetchNextPage]);\n const listedConversations = useMemo(\n () =>\n withPinnedConversations({\n conversations: list.conversations,\n pinned: pinnedList.conversations,\n }),\n [list.conversations, pinnedList.conversations],\n );\n\n // Live rows ride the signed-in user's conversation index — the same push\n // channel the conversation-history panel renders from: the host replicates\n // title, lifecycle, attention and creation changes as ops, so a\n // freshly-started thread's server-generated title (or a session flipping to\n // \"needs you\") lands without polling. The index is one instance per\n // `(workspace, user)` in agora's ids, so the pair is resolved from the\n // backend once a principal is known and the index only attaches once both\n // halves are; API-key-only hosts keep the bounded REST poll\n // (`titleSource: 'poll'`).\n const indexHeaders = useCallback<DeepAgentHeadersResolver>(\n (ctx) =>\n resolveStatewireAuthHeaders(\n { apiKey: apiKeyRef.current, token: tokenRef.current, getToken: getTokenRef.current },\n ctx,\n ),\n [],\n );\n // A credential generation: a counter that advances whenever the host's\n // credentials change, so caches scoped to a credential (the hover\n // prefetcher, the sessions views) can name it without a secret.\n const credentialsRef = useRef(credentialShape({ apiKey, token, getToken }));\n const credentialGenerationRef = useRef(0);\n const currentCredentials = credentialShape({ apiKey, token, getToken });\n if (!sameCredentialShape(credentialsRef.current, currentCredentials)) {\n credentialsRef.current = currentCredentials;\n credentialGenerationRef.current += 1;\n }\n const credentialGeneration = credentialGenerationRef.current;\n // The workspace half is the CREDENTIAL's: a scoped credential (sandbox,\n // preview, Office session) pins its own workspace, so swapping one for\n // another under the same principal must re-resolve the pair. The read is\n // keyed by the credential it is sent with, never the secret\n // (`accountIdentityQueryKey`), and it is the chat's read too: `AthenaChat`\n // under this provider asks for the same key, so the page sends one `/me`.\n const identityEnabled = syncUrl !== undefined && principal.length > 0 && hasAuth;\n const identity = useAccountIdentityQuery({\n credential: { backendUrl, principal, apiKey, heldToken: token, tokenGetter: getToken },\n resolveAuth: getAuth,\n enabled: identityEnabled,\n });\n const indexWorkspaceId = identity.data?.workspaceId ?? '';\n const indexUserId = identity.data?.userId ?? '';\n const indexEnabled = identityEnabled && indexWorkspaceId.length > 0 && indexUserId.length > 0;\n const index = useConversationIndex({\n baseUrl: syncUrl === undefined ? '' : conversationIndexUrlFromStatewireUrl(syncUrl),\n workspaceId: indexWorkspaceId || 'pending-workspace',\n userId: indexUserId || 'pending-user',\n headers: indexHeaders,\n enabled: indexEnabled,\n });\n // The index parks after repeated credential refusals; re-arm it as soon as\n // a new token exists so live rows resume without a reload.\n useRestartAfterAuthRefusal({\n connection: index.connection,\n reconnect: index.connection.reconnect,\n });\n const indexByThread = useMemo(() => {\n const entries = new Map<string, ConversationIndexEntry>();\n for (const entry of index.entries ?? []) entries.set(entry.thread_id, entry);\n return entries;\n }, [index.entries]);\n\n // Each fetched row folds its pushed index entry through the shared\n // `summaryFromConversationIndexEntry`, so titles, lifecycle and attention\n // update live while the fields the index never carries (pull requests,\n // the last wake) keep their fetched values. A pushed title that normalizes\n // to nothing falls back to the fetched one.\n const mergedConversations = useMemo(\n () => foldConversationIndex(listedConversations, indexByThread),\n [listedConversations, indexByThread],\n );\n // The server's answer to a write is patched into EVERY conversation list\n // cached under this provider (its own page, and any `SessionsPage` /\n // `Inbox` view) — the client is the provider's own, so nothing outside it\n // is touched.\n const queryClient = useQueryClient();\n const patchEveryList = useCallback(\n (threadId: string, patch: Partial<ConversationSummary>) =>\n patchConversationListCaches(queryClient, {\n match: (item) => item.threadId === threadId,\n patch,\n }),\n [queryClient],\n );\n // A pin toggle sits over the fold: the row flips at once, and a pushed\n // index entry that predates the write cannot clobber it. The override drops\n // once both sources report the toggled value.\n const pinnedListRefresh = pinnedList.refresh;\n const favorite = useThreadFavorite({\n backendUrl,\n principalId: principal,\n getAuth,\n rows: mergedConversations,\n onServerTruth: ({ threadId, isFavorited }) => {\n patchEveryList(threadId, { isFavorited });\n // A newly pinned session joins the pinned read, so it stays listed\n // once newer sessions push it out of `list`.\n if (isFavorited) void pinnedListRefresh();\n },\n });\n const favoriteOverrides = favorite.overrides;\n // A rename sits over the fold the same way: the row shows the new title\n // at once, and a pushed index entry that predates the write cannot restore\n // the old one. The override drops once both sources report the new title.\n const rename = useThreadRename({\n backendUrl,\n principalId: principal,\n getAuth,\n rows: mergedConversations,\n onServerTruth: ({ threadId, title }) => patchEveryList(threadId, { title }),\n });\n const titleOverrides = rename.overrides;\n // Read state likewise; the read-state route publishes no index update, so\n // the override is what keeps a stale pushed `is_unread` from flipping the\n // row back until the index's next rebuild agrees.\n const readState = useThreadReadState({\n backendUrl,\n principalId: principal,\n getAuth,\n rows: mergedConversations,\n onServerTruth: ({ threadId, isUnread }) => patchEveryList(threadId, { isUnread }),\n });\n const readOverrides = readState.overrides;\n const readCoveredUpdatedAt = readState.coveredUpdatedAt;\n\n // An archive hides the row at once and keeps it hidden until neither list\n // source reports it any more — the cached page is patched on the server's\n // answer, but the pushed index may still carry the row until the publish\n // that follows the commit lands. A failure drops the id and the row comes\n // back from the still-cached page: no refetch needed. Scoping, the\n // one-write-per-thread guard and the route-missing fallback live in the hook.\n const archive = useThreadArchive({\n backendUrl,\n principalId: principal,\n getAuth,\n onArchived: (threadId) => {\n removeConversationFromListCaches(queryClient, { threadId });\n // The archived session cannot stay the active chat: the server no\n // longer lists it, so the chat moves to a fresh one.\n setActive((current) =>\n current.id === threadId ? { id: mintThreadId(), isNew: true } : current,\n );\n },\n });\n const hiddenThreadIds = archive.hiddenThreadIds;\n const archiveRelease = archive.release;\n // A hidden row is released once both sources have forgotten it, so a\n // session archived elsewhere and then restored is never masked here.\n useEffect(() => {\n if (hiddenThreadIds.size === 0) return;\n const forgotten = [...hiddenThreadIds].filter(\n (threadId) =>\n !mergedConversations.some((conversation) => conversation.threadId === threadId) &&\n !indexByThread.has(threadId),\n );\n if (forgotten.length > 0) archiveRelease(forgotten);\n }, [hiddenThreadIds, mergedConversations, indexByThread, archiveRelease]);\n\n const applyOverrides = useCallback(\n (rows: readonly ConversationSummary[]) =>\n withReadStateOverrides(\n withTitleOverrides(withFavoriteOverrides(rows, favoriteOverrides), titleOverrides),\n readOverrides,\n readCoveredUpdatedAt,\n ).filter((conversation) => !hiddenThreadIds.has(conversation.threadId)),\n [favoriteOverrides, titleOverrides, readOverrides, readCoveredUpdatedAt, hiddenThreadIds],\n );\n const data = useMemo(\n () => applyOverrides(mergedConversations).map(threadSummaryFromConversation),\n [applyOverrides, mergedConversations],\n );\n const isLoading = list.isLoading;\n\n // The active thread's row must survive a search that filters it out of\n // the page (the banner above the chat reads it): the listed row when there\n // is one, else the pushed index entry folded over the last row seen for\n // this thread (so pull requests survive the fold), else that last row.\n const lastActiveConversationRef = useRef<ConversationSummary | null>(null);\n const activeConversation = useMemo<ConversationSummary | null>(() => {\n const listed = mergedConversations.find((conversation) => conversation.threadId === active.id);\n if (listed) return listed;\n const remembered =\n lastActiveConversationRef.current?.threadId === active.id\n ? lastActiveConversationRef.current\n : undefined;\n const entry = indexByThread.get(active.id);\n if (entry) return summaryFromConversationIndexEntry(entry, remembered);\n return remembered ?? null;\n }, [mergedConversations, indexByThread, active.id]);\n if (activeConversation !== null) lastActiveConversationRef.current = activeConversation;\n const activeThread = useMemo(\n () =>\n activeConversation\n ? threadSummaryFromConversation(\n withReadStateOverrides(\n [\n withTitleOverride(\n withFavoriteOverride(activeConversation, favoriteOverrides),\n titleOverrides,\n ),\n ],\n readOverrides,\n readCoveredUpdatedAt,\n )[0] ?? activeConversation,\n )\n : null,\n [activeConversation, favoriteOverrides, titleOverrides, readOverrides, readCoveredUpdatedAt],\n );\n\n const listRefresh = list.refresh;\n const pinnedFetchingRef = useRef(pinnedList.isFetching);\n pinnedFetchingRef.current = pinnedList.isFetching;\n const refresh = useCallback(() => {\n void listRefresh();\n // A pinned read still in flight is left to finish: a refresh restarts it, so the title\n // poll's ticks would never let a pinned read slower than their interval answer.\n if (!pinnedFetchingRef.current) void pinnedListRefresh();\n }, [listRefresh, pinnedListRefresh]);\n const listFetchNextPage = list.fetchNextPage;\n const fetchNextPage = useCallback(() => {\n void listFetchNextPage();\n }, [listFetchNextPage]);\n\n // A thread the index knows — created here on first send, or elsewhere —\n // that the REST page does not list yet refreshes the page so the row\n // appears without the user pressing refresh. Rows for apps this list does\n // not show (its `appId` and `additionalListAppIds`) never trigger one; a\n // conversation with the home agent (a Slack thread started while the app is\n // open) does once the page said the server lists them. The refreshes are\n // coalesced, held while the page is already being read, and a refused one\n // is tried again (`useIndexTriggeredRefresh`).\n const listedThreadIds = useMemo(\n () => new Set(list.conversations.map((conversation) => conversation.threadId)),\n [list.conversations],\n );\n const homeAgentApplied = list.homeAgentApplied;\n const unlistedIndexedThreads = useMemo(\n () =>\n index.entries === null\n ? []\n : indexedThreadsToRefreshFor({\n entries: index.entries,\n listedThreadIds,\n refreshedThreadIds: EMPTY_THREAD_IDS,\n appId,\n additionalAppIds: listedAppIds,\n homeAgentId,\n homeAgentApplied,\n }),\n [index.entries, listedThreadIds, appId, listedAppIds, homeAgentId, homeAgentApplied],\n );\n // The user's other open tabs heard the same push: one of them reads the\n // page and shares it with the rest (`session-list-tab-share.ts`).\n const tabShare = useSessionListTabShare({\n queryClient,\n identity:\n indexWorkspaceId && indexUserId\n ? { backendUrl, userId: indexUserId, workspaceId: indexWorkspaceId }\n : null,\n });\n const listShareKey = sessionListShareKey(\n conversationListQueryKeys.firstPage(\n listScopeKey,\n conversationListFilterKey(filter),\n THREAD_LIST_PAGE_SIZE,\n ),\n );\n useIndexTriggeredRefresh({\n pending: unlistedIndexedThreads,\n refresh: listRefresh,\n // Held only while the page is being read (its first read and that read's\n // own retries included). A first page that was refused does not hold it:\n // the index-triggered refresh is then how the list recovers.\n enabled: hasAuth && index.entries !== null && !list.isFetching,\n tabShare,\n shareKey: listShareKey,\n });\n\n const selectThread = useCallback((threadId: string, options?: { isNew?: boolean }) => {\n if (!threadId) return;\n const isNew = options?.isNew === true;\n setActive((current) => (current.id === threadId ? current : { id: threadId, isNew }));\n }, []);\n\n // The hover prefetcher is one per (backend, principal, credential\n // generation): a credential swap clears the provider's snapshot cache, so\n // the attempt ledger resets with it and a late answer from the previous\n // identity is never remembered under the new one.\n const prefetchScope = `${backendUrl}::${principal}::${credentialGeneration}`;\n const prefetchScopeRef = useRef(prefetchScope);\n prefetchScopeRef.current = prefetchScope;\n const prefetcher = useMemo(() => {\n if (!snapshotCache) return null;\n const scope = prefetchScope;\n return createThreadPrefetcher({\n cache: snapshotCache,\n fetchState: async (threadId) =>\n withCredentialRenewal(getAuth, (auth) =>\n getThreadState(backendUrl, auth, threadId, { skipCache: false }),\n ),\n isCurrent: () => prefetchScopeRef.current === scope,\n });\n }, [snapshotCache, prefetchScope, backendUrl, getAuth]);\n const activeIdRef = useRef(active.id);\n activeIdRef.current = active.id;\n const prefetchThread = useCallback(\n (threadId: string) => {\n if (!prefetcher || !threadId || threadId === activeIdRef.current) return;\n prefetcher.prefetch(threadId);\n },\n [prefetcher],\n );\n\n const newThread = useCallback(() => {\n setActive({ id: mintThreadId(), isNew: true });\n }, []);\n\n // A minted thread stops being \"new\" once the backend lists it — on the\n // fetched page or in the pushed index (a search may keep it off the page):\n // until then `useAthenaThreadManager` reports a null id, so URL sync cannot\n // name it.\n const isPersisted =\n data.some((thread) => thread.id === active.id) || indexByThread.has(active.id);\n useEffect(() => {\n if (isPersisted) {\n setActive((current) => (current.isNew ? { ...current, isNew: false } : current));\n }\n }, [isPersisted]);\n\n const titleSource: AthenaStatewireThreadListState['titleSource'] =\n index.entries !== null ? 'index' : 'poll';\n\n const value = useMemo<AthenaStatewireThreadListState>(\n () => ({\n threads: data,\n isLoading,\n isFetching: list.isFetching,\n hasResolvedFirstPage: list.hasResolvedFirstPage,\n activeThreadId: active.id,\n activeThread,\n isNewChat: active.isNew,\n selectThread,\n prefetchThread,\n newThread,\n refresh,\n search,\n setSearch,\n hasNextPage: list.hasNextPage,\n isFetchingNextPage: list.isFetchingNextPage,\n fetchNextPage,\n setFavorited: favorite.setFavorited,\n favoritePending: favorite.isPending,\n favoritePendingThreadIds: favorite.pendingThreadIds,\n favoriteToggleAvailable: favorite.isAvailable,\n renameThread: rename.rename,\n renamePendingThreadIds: rename.pendingThreadIds,\n renameAvailable: rename.isAvailable,\n archiveThread: archive.archive,\n archivePendingThreadIds: archive.pendingThreadIds,\n archivePending: archive.isPending,\n archiveAvailable: archive.isAvailable,\n setReadState: readState.setReadState,\n readStatePendingThreadIds: readState.pendingThreadIds,\n titleSource,\n }),\n [\n data,\n isLoading,\n list.isFetching,\n list.hasResolvedFirstPage,\n active.id,\n activeThread,\n active.isNew,\n selectThread,\n prefetchThread,\n newThread,\n refresh,\n search,\n list.hasNextPage,\n list.isFetchingNextPage,\n fetchNextPage,\n favorite.setFavorited,\n favorite.isPending,\n favorite.pendingThreadIds,\n favorite.isAvailable,\n rename.rename,\n rename.pendingThreadIds,\n rename.isAvailable,\n archive.archive,\n archive.pendingThreadIds,\n archive.isPending,\n archive.isAvailable,\n readState.setReadState,\n readState.pendingThreadIds,\n titleSource,\n ],\n );\n\n const live = useMemo<AthenaSessionsLiveState>(\n () => ({\n backendUrl,\n getAuth,\n principal,\n hasAuth,\n includePullRequests,\n scopeKey: listScopeKey,\n credentialGeneration,\n baseFilter: {\n ...(appId ? { appId } : {}),\n ...(listedAppIds.length > 0 ? { appIds: listedAppIds } : {}),\n ...(homeAgentId ? { homeAgentId } : {}),\n },\n indexByThread,\n indexEntries: index.entries,\n applyOverrides,\n tabShare,\n }),\n [\n backendUrl,\n getAuth,\n principal,\n hasAuth,\n includePullRequests,\n listScopeKey,\n credentialGeneration,\n appId,\n listedAppIds,\n homeAgentId,\n indexByThread,\n index.entries,\n applyOverrides,\n tabShare,\n ],\n );\n\n return (\n <AthenaStatewireThreadListContext.Provider value={value}>\n <AthenaSessionsLiveContext.Provider value={live}>{children}</AthenaSessionsLiveContext.Provider>\n </AthenaStatewireThreadListContext.Provider>\n );\n}\n\n/**\n * Provides the statewire thread-list state, with an SDK-scoped QueryClient so\n * consumers do not need their own QueryClientProvider. `syncUrl` (the\n * `…/v2/threads` mount) locates the conversation index beside it; without it\n * titles fall back to the REST poll. `includePullRequests` (default `true`)\n * asks the list for live pull-request state so `SessionList` can render its\n * chips; a host that never shows them turns it off to spare the server the\n * lookup. `snapshotCache` is the provider's thread snapshot cache — the one\n * the runtime seeds a switched-to thread from — which `prefetchThread` warms;\n * without it prefetching is a no-op.\n */\nexport function AthenaStatewireThreadListProvider({\n backendUrl,\n syncUrl,\n apiKey,\n token,\n getToken,\n appId,\n additionalListAppIds,\n homeAgentId,\n initialThreadId,\n includePullRequests = true,\n snapshotCache,\n offlineList,\n children,\n}: {\n backendUrl: string;\n syncUrl?: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n appId?: string;\n /** Other client apps whose sessions the list shows too (a union with `appId`). */\n additionalListAppIds?: readonly string[];\n /**\n * The collab agent (`asset_<uuid>`) whose home this app is: every list read asks the server to\n * hold the conversations with it too (`home_agent_id`).\n */\n homeAgentId?: string;\n initialThreadId?: string;\n includePullRequests?: boolean;\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /**\n * Keep the list's first pages on this device, sealed (`AthenaProvider`'s `offlineHistory`): they\n * paint at once and read while Athena can't be reached.\n */\n offlineList?: { mirror: ThreadSnapshotMirror; ownerId: string };\n children: ReactNode;\n}) {\n const [queryClient] = useState(() => new QueryClient());\n useOfflineSessionList({ queryClient, offlineList });\n return (\n <QueryClientProvider client={queryClient}>\n <StatewireThreadListState\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n appId={appId}\n additionalListAppIds={additionalListAppIds}\n homeAgentId={homeAgentId}\n initialThreadId={initialThreadId}\n includePullRequests={includePullRequests}\n snapshotCache={snapshotCache}\n >\n {children}\n </StatewireThreadListState>\n </QueryClientProvider>\n );\n}\n\n/** How long after a thread's first message the title poll starts (exported for tests). */\nexport const TITLE_POLL_DELAY_MS = 5000;\nconst TITLE_POLL_INTERVAL_MS = 2000;\nconst TITLE_POLL_MAX_DURATION_MS = 60_000;\n\n/**\n * Fallback for hosts without a live conversation index (`titleSource: 'poll'`,\n * i.e. no signed-in principal): refreshes the thread list until a\n * freshly-started thread's server-generated title appears. Idle while the\n * index carries titles. Mount inside the statewire runtime scope (needs aui\n * state).\n *\n * The thread is read from the statewire scope, not the list: the scope\n * publishes the id together with the client it belongs to, so the messages\n * observed here are always the named thread's (the list's selection moves\n * one commit ahead of the client during a switch).\n */\nexport function StatewireThreadTitlePoller(): null {\n const list = useAthenaStatewireThreadList();\n const activeThreadId = useAthenaStatewireThreadId();\n const hasMessages = useAuiState((s) => (s.optional.thread?.messages.length ?? 0) > 0);\n\n const titleSource = list?.titleSource ?? 'poll';\n const entry = list?.threads.find((thread) => thread.id === activeThreadId);\n const title = entry?.title?.trim() ?? '';\n const hasTitle = title.length > 0 && !isSerializedContentPartsTitle(title);\n\n // The poller stays mounted across thread switches, so the visit is tracked\n // by hand: one poll per visit — no restart when the visited thread's\n // messages or title flip underneath it — and a re-selected thread polls\n // again, as it did when every switch remounted the poller. The record is\n // replaced whenever the attached thread changes, whether or not a poll\n // started for it, so a visit to a thread that needs no poll can never make\n // the next visit to a previous thread look already polled.\n const visitRef = useRef<{ threadId: string; polled: boolean } | null>(null);\n const refreshRef = useRef(list?.refresh);\n refreshRef.current = list?.refresh;\n const fetchingRef = useRef(list?.isFetching ?? false);\n fetchingRef.current = list?.isFetching ?? false;\n\n useEffect(() => {\n if (visitRef.current?.threadId !== activeThreadId) {\n visitRef.current = { threadId: activeThreadId, polled: false };\n }\n const visit = visitRef.current;\n if (!hasMessages || hasTitle || titleSource === 'index') return;\n if (visit.polled) return;\n visit.polled = true;\n\n let intervalId: ReturnType<typeof setInterval> | null = null;\n const startId = setTimeout(() => {\n // A tick while the list's last read is still on its way waits for it: a refresh restarts\n // the read, so against a server slower than the interval no read would ever finish and\n // the new thread would stay unlisted until the poll gives up.\n intervalId = setInterval(() => {\n if (!fetchingRef.current) refreshRef.current?.();\n }, TITLE_POLL_INTERVAL_MS);\n }, TITLE_POLL_DELAY_MS);\n const stopId = setTimeout(() => {\n if (intervalId !== null) clearInterval(intervalId);\n }, TITLE_POLL_MAX_DURATION_MS);\n\n return () => {\n clearTimeout(startId);\n clearTimeout(stopId);\n if (intervalId !== null) clearInterval(intervalId);\n };\n }, [activeThreadId, hasMessages, hasTitle, titleSource]);\n\n return null;\n}\n"],"names":["createContext","useContext","normalizeThreadTitle","deriveConversationAttention","summaryFromConversationIndexEntry","useState","mintThreadId","useRef","AthenaAuthContext","useCallback","resolveStatewireAuthToken","useMemo","createRestConversationListFetcher","useConversationList","useEffect","resolveStatewireAuthHeaders","credentialShape","sameCredentialShape","useAccountIdentityQuery","useConversationIndex","conversationIndexUrlFromStatewireUrl","useRestartAfterAuthRefusal","useQueryClient","patchConversationListCaches","useThreadFavorite","useThreadRename","title","useThreadReadState","useThreadArchive","removeConversationFromListCaches","withReadStateOverrides","withTitleOverrides","withFavoriteOverrides","_a","withTitleOverride","withFavoriteOverride","useSessionListTabShare","sessionListShareKey","conversationListQueryKeys","conversationListFilterKey","useIndexTriggeredRefresh","createThreadPrefetcher","withCredentialRenewal","getThreadState","jsx","QueryClient","useOfflineSessionList","QueryClientProvider","useAthenaStatewireThreadId","useAuiState","isSerializedContentPartsTitle"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgQO,MAAM,mCACXA,WAAAA,cAAqD,IAAI;AAGpD,SAAS,+BAAsE;AACpF,SAAOC,WAAAA,WAAW,gCAAgC;AACpD;AAGO,SAAS,uBAA4C;;AAC1D,WAAO,kCAAA,MAAA,mBAAgC,YAAW;AACpD;AAOA,MAAM,yDAA8D,IAAI;AAAA,EACtE;AAAA,EACA;AACF,CAAC;AAOD,SAAS,sBACP,OACA,aACS;AACT,MAAI,CAAC,eAAe,MAAM,oBAAoB,YAAa,QAAO;AAClE,SAAO,CAAC,mCAAmC,IAAI,MAAM,iBAAiB,EAAE;AAC1E;AAWO,SAAS,2BAA2B;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAmB;AACrB,GAaa;AACX,QAAM,cACJ,SAAS,iBAAiB,SAAS,IAC/B,oBAAI,IAAI,CAAC,GAAI,QAAQ,CAAC,KAAK,IAAI,CAAA,GAAK,GAAG,gBAAgB,CAAC,IACxD;AACN,QAAM,gBAAgB,mBAAmB,cAAc;AACvD,SAAO,QACJ;AAAA,IACC,CAAC,UACC,CAAC,eACD,YAAY,IAAI,MAAM,UAAU,EAAE,KAClC,sBAAsB,OAAO,aAAa;AAAA,EAAA,EAE7C,IAAI,CAAC,UAAU,MAAM,SAAS,EAC9B,OAAO,CAAC,aAAa,CAAC,gBAAgB,IAAI,QAAQ,KAAK,CAAC,mBAAmB,IAAI,QAAQ,CAAC;AAC7F;AAMO,SAAS,8BACd,cAC8B;AAC9B,SAAO;AAAA,IACL,IAAI,aAAa;AAAA,IACjB,OAAOC,MAAAA,qBAAqB,aAAa,KAAK,KAAK;AAAA,IACnD,WAAWC,iBAAAA,4BAA4B,YAAY;AAAA,IACnD,YAAY,aAAa,cAAc;AAAA,IACvC,iBAA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AA,MAC5B,GAAG,sBAAsB;AAAA,IAC3B,GAAG,mBAAmB;AACtB,UAAM,SAAS,WAAW,MAAM;AAC9B,UAAI,eAAe,KAAM,eAAc,UAAU;AAAA,IACnD,GAAG,0BAA0B;AAE7B,WAAO,MAAM;AACX,mBAAa,OAAO;AACpB,mBAAa,MAAM;AACnB,UAAI,eAAe,KAAM,eAAc,UAAU;AAAA,IACnD;AAAA,EACF,GAAG,CAAC,gBAAgB,aAAa,UAAU,WAAW,CAAC;AAEvD,SAAO;AACT;;;;;;;;;;;;"}
@@ -1,11 +1,12 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
2
  import { useOfflineSessionList } from "./offline-session-list.js";
3
- import { QueryClient, QueryClientProvider, useQuery, useQueryClient } from "@tanstack/react-query";
3
+ import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
4
4
  import { useAuiState } from "@assistant-ui/react";
5
5
  import { useContext, createContext, useState, useRef, useCallback, useMemo, useEffect } from "react";
6
+ import { useAccountIdentityQuery } from "../auth/account-identity.js";
6
7
  import { AthenaAuthContext } from "../auth/AthenaAuthContext.js";
7
8
  import { resolveStatewireAuthToken, resolveStatewireAuthHeaders } from "../runtime/statewire-auth-headers.js";
8
- import { fetchAccountIdentity, getThreadState } from "./api.js";
9
+ import { getThreadState } from "./api.js";
9
10
  import { createRestConversationListFetcher } from "./conversation-list-fetcher.js";
10
11
  import { credentialShape, sameCredentialShape } from "./credential-shape.js";
11
12
  import { mintThreadId } from "./mint-thread-id.js";
@@ -220,13 +221,10 @@ function StatewireThreadListState({
220
221
  }
221
222
  const credentialGeneration = credentialGenerationRef.current;
222
223
  const identityEnabled = syncUrl !== void 0 && principal.length > 0 && hasAuth;
223
- const identity = useQuery({
224
- // Keyed by the non-secret principal and credential generation, never the
225
- // credential itself.
226
- queryKey: ["athena-sdk", "account-identity", backendUrl, principal, credentialGeneration],
227
- queryFn: ({ signal }) => withCredentialRenewal(getAuth, (auth) => fetchAccountIdentity(backendUrl, auth, { signal })),
228
- enabled: identityEnabled,
229
- staleTime: Number.POSITIVE_INFINITY
224
+ const identity = useAccountIdentityQuery({
225
+ credential: { backendUrl, principal, apiKey, heldToken: token, tokenGetter: getToken },
226
+ resolveAuth: getAuth,
227
+ enabled: identityEnabled
230
228
  });
231
229
  const indexWorkspaceId = ((_b = identity.data) == null ? void 0 : _b.workspaceId) ?? "";
232
230
  const indexUserId = ((_c = identity.data) == null ? void 0 : _c.userId) ?? "";