@athenaintel/react 0.53.1 → 0.54.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.
- package/README.md +18 -1
- package/dist/agent-runtime/src/call-recap.cjs +2 -3
- package/dist/agent-runtime/src/call-recap.cjs.map +1 -1
- package/dist/agent-runtime/src/call-recap.d.ts +1 -2
- package/dist/agent-runtime/src/call-recap.js +1 -2
- package/dist/agent-runtime/src/call-recap.js.map +1 -1
- package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +7 -3
- package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
- package/dist/agent-runtime/src/deep-agent-transport-recipe.d.ts +10 -2
- package/dist/agent-runtime/src/deep-agent-transport-recipe.js +8 -4
- package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
- package/dist/agent-runtime/src/dictation-session.d.ts +158 -0
- package/dist/agent-runtime/src/edit-command.cjs +6 -0
- package/dist/agent-runtime/src/edit-command.cjs.map +1 -1
- package/dist/agent-runtime/src/edit-command.d.ts +8 -0
- package/dist/agent-runtime/src/edit-command.js +6 -0
- package/dist/agent-runtime/src/edit-command.js.map +1 -1
- package/dist/agent-runtime/src/generated/runconfig-contract.cjs +6 -0
- package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
- package/dist/agent-runtime/src/generated/runconfig-contract.d.ts +13 -0
- package/dist/agent-runtime/src/generated/runconfig-contract.js +6 -0
- package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
- package/dist/agent-runtime/src/index.d.ts +6 -6
- package/dist/agent-runtime/src/message-window.cjs +111 -7
- package/dist/agent-runtime/src/message-window.cjs.map +1 -1
- package/dist/agent-runtime/src/message-window.d.ts +66 -6
- package/dist/agent-runtime/src/message-window.js +112 -8
- package/dist/agent-runtime/src/message-window.js.map +1 -1
- package/dist/agent-runtime/src/offline-status.cjs.map +1 -1
- package/dist/agent-runtime/src/offline-status.d.ts +33 -0
- package/dist/agent-runtime/src/offline-status.js.map +1 -1
- package/dist/agent-runtime/src/runtime.d.ts +4 -3
- package/dist/agent-runtime/src/subagent-transcripts.cjs +23 -1
- package/dist/agent-runtime/src/subagent-transcripts.cjs.map +1 -1
- package/dist/agent-runtime/src/subagent-transcripts.js +25 -3
- package/dist/agent-runtime/src/subagent-transcripts.js.map +1 -1
- package/dist/agent-runtime/src/subagents.cjs +112 -0
- package/dist/agent-runtime/src/subagents.cjs.map +1 -1
- package/dist/agent-runtime/src/subagents.d.ts +103 -0
- package/dist/agent-runtime/src/subagents.js +113 -1
- package/dist/agent-runtime/src/subagents.js.map +1 -1
- package/dist/agent-runtime/src/thread-handoff-protocol.d.ts +37 -9
- package/dist/agent-runtime/src/thread-handoff.d.ts +1 -1
- package/dist/agent-runtime/src/tool-metadata.cjs +8 -0
- package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
- package/dist/agent-runtime/src/tool-metadata.js +8 -0
- package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-thread.cjs +6 -0
- package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-thread.js +7 -1
- package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs +39 -10
- package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-window-sync.d.ts +14 -4
- package/dist/agent-runtime/src/use-deep-agent-window-sync.js +41 -12
- package/dist/agent-runtime/src/use-deep-agent-window-sync.js.map +1 -1
- package/dist/agent-runtime/src/use-thread-handoff-flow.d.ts +5 -9
- package/dist/agent-runtime/src/voice-presentation.cjs +34 -0
- package/dist/agent-runtime/src/voice-presentation.cjs.map +1 -1
- package/dist/agent-runtime/src/voice-presentation.d.ts +35 -0
- package/dist/agent-runtime/src/voice-presentation.js +34 -0
- package/dist/agent-runtime/src/voice-presentation.js.map +1 -1
- package/dist/assets/AthenaAssetEmbed.cjs +4 -2
- package/dist/assets/AthenaAssetEmbed.cjs.map +1 -1
- package/dist/assets/AthenaAssetEmbed.d.ts +17 -8
- package/dist/assets/AthenaAssetEmbed.js +4 -2
- package/dist/assets/AthenaAssetEmbed.js.map +1 -1
- package/dist/assets/use-asset-embed.cjs.map +1 -1
- package/dist/assets/use-asset-embed.d.ts +7 -5
- package/dist/assets/use-asset-embed.js.map +1 -1
- package/dist/auth/account-identity.cjs +69 -0
- package/dist/auth/account-identity.cjs.map +1 -0
- package/dist/auth/account-identity.d.ts +57 -0
- package/dist/auth/account-identity.js +69 -0
- package/dist/auth/account-identity.js.map +1 -0
- package/dist/chat/AthenaChat.cjs +1 -1
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.js +1 -1
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/super-grouping/toolkit-map.cjs +1 -0
- package/dist/chat/super-grouping/toolkit-map.cjs.map +1 -1
- package/dist/chat/super-grouping/toolkit-map.js +1 -0
- package/dist/chat/super-grouping/toolkit-map.js.map +1 -1
- package/dist/chat/use-statewire-approval-request.cjs +5 -5
- package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
- package/dist/chat/use-statewire-approval-request.d.ts +7 -0
- package/dist/chat/use-statewire-approval-request.js +5 -5
- package/dist/chat/use-statewire-approval-request.js.map +1 -1
- package/dist/chat-ui/mentions/use-account-workspace-id.cjs +18 -58
- package/dist/chat-ui/mentions/use-account-workspace-id.cjs.map +1 -1
- package/dist/chat-ui/mentions/use-account-workspace-id.js +18 -58
- package/dist/chat-ui/mentions/use-account-workspace-id.js.map +1 -1
- package/dist/chat-ui/messages/voice-delegation-card.cjs +93 -25
- package/dist/chat-ui/messages/voice-delegation-card.cjs.map +1 -1
- package/dist/chat-ui/messages/voice-delegation-card.d.ts +16 -7
- package/dist/chat-ui/messages/voice-delegation-card.js +95 -27
- package/dist/chat-ui/messages/voice-delegation-card.js.map +1 -1
- package/dist/chat-ui/thread/handoff-cursor.cjs +2 -2
- package/dist/chat-ui/thread/handoff-cursor.cjs.map +1 -1
- package/dist/chat-ui/thread/handoff-cursor.js +3 -3
- package/dist/chat-ui/thread/handoff-cursor.js.map +1 -1
- package/dist/collab/client.cjs +94 -6
- package/dist/collab/client.cjs.map +1 -1
- package/dist/collab/client.d.ts +27 -0
- package/dist/collab/client.js +94 -6
- package/dist/collab/client.js.map +1 -1
- package/dist/collab/index.d.ts +1 -1
- package/dist/keryx-http/src/initial-sync.cjs +121 -0
- package/dist/keryx-http/src/initial-sync.cjs.map +1 -0
- package/dist/keryx-http/src/initial-sync.d.ts +77 -0
- package/dist/keryx-http/src/initial-sync.js +104 -0
- package/dist/keryx-http/src/initial-sync.js.map +1 -0
- package/dist/keryx-http/src/unconfirmed-update-attributions.cjs +8 -0
- package/dist/keryx-http/src/unconfirmed-update-attributions.cjs.map +1 -1
- package/dist/keryx-http/src/unconfirmed-update-attributions.d.ts +6 -0
- package/dist/keryx-http/src/unconfirmed-update-attributions.js +8 -0
- package/dist/keryx-http/src/unconfirmed-update-attributions.js.map +1 -1
- package/dist/react/package.json.cjs +1 -1
- package/dist/react/package.json.js +1 -1
- package/dist/styles.css +1 -1
- package/dist/threads/api.cjs +1 -2
- package/dist/threads/api.cjs.map +1 -1
- package/dist/threads/api.d.ts +3 -2
- package/dist/threads/api.js +1 -2
- package/dist/threads/api.js.map +1 -1
- package/dist/threads/statewire-thread-list.cjs +5 -7
- package/dist/threads/statewire-thread-list.cjs.map +1 -1
- package/dist/threads/statewire-thread-list.js +7 -9
- package/dist/threads/statewire-thread-list.js.map +1 -1
- package/dist/tools/subagent-task-tool-ui.cjs +15 -5
- package/dist/tools/subagent-task-tool-ui.cjs.map +1 -1
- package/dist/tools/subagent-task-tool-ui.d.ts +5 -4
- package/dist/tools/subagent-task-tool-ui.js +16 -6
- package/dist/tools/subagent-task-tool-ui.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"statewire-thread-list.js","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"],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,YAAU,MAAM;;AACd,UAAIA,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.js","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":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgQO,MAAM,mCACX,cAAqD,IAAI;AAGpD,SAAS,+BAAsE;AACpF,SAAO,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,EAC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,UAAI,eAAe,KAAM,eAAc,UAAU;AAAA,IACnD;AAAA,EACF,GAAG,CAAC,gBAAgB,aAAa,UAAU,WAAW,CAAC;AAEvD,SAAO;AACT;"}
|
|
@@ -24,10 +24,11 @@ const subagentTranscripts = require("../agent-runtime/src/subagent-transcripts.c
|
|
|
24
24
|
const messages = require("../agent-runtime/src/messages.cjs");
|
|
25
25
|
const cnfast = require("cnfast");
|
|
26
26
|
const NO_LANE_STEPS = [];
|
|
27
|
+
const NOT_AWAITING_APPROVAL = { awaitingApproval: false, gatedCall: void 0 };
|
|
27
28
|
const NO_MESSAGES = [];
|
|
28
29
|
const SUBAGENT_LANE_PHASE_LABELS = {
|
|
29
30
|
queued: "Queued",
|
|
30
|
-
approval:
|
|
31
|
+
approval: subagents.SUBAGENT_AWAITING_APPROVAL_LABEL,
|
|
31
32
|
waiting: "Waiting for you",
|
|
32
33
|
running: "Running",
|
|
33
34
|
complete: "Done",
|
|
@@ -330,9 +331,18 @@ function SubagentTaskCard({ toolCallId, args, status, artifact, messages: messag
|
|
|
330
331
|
() => readLane ?? laneFromArgs(toolCallId, args),
|
|
331
332
|
[readLane, toolCallId, args]
|
|
332
333
|
);
|
|
333
|
-
const { toolCallIds: waitingToolCallIds } = useStatewireApprovalRequest.useApprovalWaitInScope();
|
|
334
|
-
const
|
|
335
|
-
const
|
|
334
|
+
const { toolCallIds: waitingToolCallIds, actionRequests } = useStatewireApprovalRequest.useApprovalWaitInScope();
|
|
335
|
+
const waitingTurn = react.useAuiState((s) => waitingToolCallIds.size === 0 ? null : s.message);
|
|
336
|
+
const approvalWait = require$$0.useMemo(
|
|
337
|
+
() => waitingTurn === null ? NOT_AWAITING_APPROVAL : subagents.turnLaneApprovalWait({
|
|
338
|
+
message: waitingTurn,
|
|
339
|
+
toolCallId,
|
|
340
|
+
toolCallIds: waitingToolCallIds,
|
|
341
|
+
actionRequests
|
|
342
|
+
}),
|
|
343
|
+
[waitingTurn, toolCallId, waitingToolCallIds, actionRequests]
|
|
344
|
+
);
|
|
345
|
+
const { awaitingApproval, gatedCall } = approvalWait;
|
|
336
346
|
const phase = subagentLanePhase({ status: lane.status, partStatus: status, awaitingApproval });
|
|
337
347
|
const running = phase === "running";
|
|
338
348
|
const delegatedAt = react.useAuiState(
|
|
@@ -386,7 +396,7 @@ function SubagentTaskCard({ toolCallId, args, status, artifact, messages: messag
|
|
|
386
396
|
"data-slot": "subagent-approval",
|
|
387
397
|
className: "flex min-w-0 items-baseline gap-1 text-xs text-muted-foreground",
|
|
388
398
|
children: [
|
|
389
|
-
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "shrink-0 text-amber-700", children:
|
|
399
|
+
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "shrink-0 text-amber-700", children: subagents.subagentApprovalNoteLabel(approvalWait) }),
|
|
390
400
|
gatedCall ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
391
401
|
/* @__PURE__ */ jsxRuntime.jsx("code", { className: "shrink-0 rounded bg-foreground/[0.06] px-1 py-px font-mono text-[11px] text-foreground/85", children: gatedCall.name }),
|
|
392
402
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "min-w-0 truncate", children: toolNames.salientToolCallDetail(gatedCall) })
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-task-tool-ui.cjs","sources":["../../src/tools/subagent-task-tool-ui.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * The subagent card: one `task` call the deep agent delegated, shown the way\n * Olympus shows a subagent lane.\n *\n * - On the card: where the lane is (queued, running, done, failed, stopped),\n * how many tool calls it made (the wire's cut marker counts a lane whose\n * card carries only its newest steps), how long it has run, and while it\n * runs, its newest step; a finished lane's report, or why it failed, under\n * it, clamped.\n * - Behind its disclosure: the lane's steps, live while it runs, ending on\n * what the lane ended on, whole (a failure, or a report no step carries),\n * so a lane with no steps still opens to its full result. The lane is\n * assistant-ui's native nested thread: the `task` part's `messages`, which\n * the SDK runtime's opt-in conversion fills\n * (`createSubagentTranscriptConversionCache`), rendered read-only under\n * `ReadonlyThreadProvider` with the chat's own tool UIs. A cut lane (a\n * running card always; a finished one when the provider declares the\n * lane-cut contract, `subagentLaneHistory`) says how many of its steps it\n * shows, and \"Load earlier steps\" reads the rest with `history/lane`\n * (`useDeepAgentLaneHistory`), a read under the thread's own attach.\n *\n * A read-only nested thread has no statewire thread behind it: a `task` call\n * inside a subagent's own steps renders as a static row, and the steps are\n * their own error boundary, so a tool UI that throws there never takes the\n * chat down with it.\n */\nimport {\n getExternalStoreMessages,\n MessagePrimitive,\n ReadonlyThreadProvider,\n type ThreadMessage,\n ThreadPrimitive,\n type ToolCallMessagePartComponent,\n type ToolCallMessagePartProps,\n type ToolCallMessagePartStatus,\n useAuiState,\n} from \"@assistant-ui/react\";\nimport type { LangChainMessage } from \"@assistant-ui/react-langgraph\";\nimport {\n createSubagentLaneConversion,\n deepAgentRowKey,\n hasStatewireThreadExtras,\n salientToolCallDetail,\n type SubagentDiscoverySnapshot,\n type SubagentStatus,\n subagentAwaitingApproval,\n subagentToolCallAwaitingApproval,\n taskSubagentsOfTurn,\n useDeepAgentLaneHistory,\n withLaneReport,\n} from \"@athenaintel/agent-runtime\";\nimport { QueryClientProvider } from \"@tanstack/react-query\";\nimport {\n AlertCircleIcon,\n BotIcon,\n CheckIcon,\n ChevronDownIcon,\n CircleDashedIcon,\n LoaderIcon,\n ShieldAlertIcon,\n XCircleIcon,\n} from \"lucide-react\";\nimport {\n Component,\n createContext,\n type ErrorInfo,\n type FC,\n memo,\n type ReactNode,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport { useApprovalWaitInScope } from \"../chat/use-statewire-approval-request\";\nimport { MESSAGE_CREATED_AT_KEY } from \"../chat/message-time\";\nimport { formatWorkDuration, readInstantMs } from \"../chat/super-grouping/turn-timing\";\nimport { athenaDiagnostics } from \"../diagnostics/athena-diagnostics\";\nimport { useAthenaQueryClient } from \"../lib/use-athena-rest-query\";\nimport { cn } from \"../lib/utils\";\nimport { CollapsibleTrigger } from \"../ui/collapsible\";\nimport { useNestedPtcComponents } from \"./NestedPtcMessages\";\nimport { StepText } from \"./step-text\";\nimport { useToolAppearance } from \"./tool-appearance\";\nimport { ToolFallback, ToolFallbackContent, ToolFallbackRoot } from \"./tool-fallback\";\nimport { humanizeToolName, summarizeToolCall, type ToolCallSummary } from \"./tool-summary\";\n\nconst NO_LANE_STEPS: readonly LangChainMessage[] = [];\nconst NO_MESSAGES: readonly ThreadMessage[] = [];\n\n// ─── What the card says ──────────────────────────────────────────────\n// Pure: where a lane is, how long it ran, the step it took last, and the\n// note over a cut lane's steps, tested without rendering the card.\n\n/**\n * Where a lane is, as the card shows it: the lane's own status, except that a\n * lane parked on a person's approval is `approval` (its own dispatch, or a call\n * it made, is a gated call nobody has answered), any other call the run waits\n * on an answer for is `waiting`, and one the run stopped before it settled is\n * `stopped`.\n */\nexport type SubagentLanePhase =\n | \"queued\"\n | \"approval\"\n | \"waiting\"\n | \"running\"\n | \"complete\"\n | \"error\"\n | \"stopped\";\n\nexport const SUBAGENT_LANE_PHASE_LABELS: Record<SubagentLanePhase, string> = {\n queued: \"Queued\",\n approval: \"Waiting for approval\",\n waiting: \"Waiting for you\",\n running: \"Running\",\n complete: \"Done\",\n error: \"Failed\",\n stopped: \"Stopped\",\n};\n\n/** The lane's phase from its status, the status assistant-ui gives its part, and the run's approval. */\nexport function subagentLanePhase({\n status,\n partStatus,\n awaitingApproval = false,\n}: {\n status: SubagentStatus;\n partStatus: ToolCallMessagePartStatus | undefined;\n /** The lane waits on a person's approval (agent-runtime's `subagentAwaitingApproval`). */\n awaitingApproval?: boolean;\n}): SubagentLanePhase {\n if (status === \"complete\" || status === \"error\") return status;\n if (awaitingApproval) return \"approval\";\n if (partStatus?.type === \"requires-action\") return \"waiting\";\n if (partStatus?.type === \"incomplete\") {\n return partStatus.reason === \"cancelled\" ? \"stopped\" : \"error\";\n }\n return status;\n}\n\n/** The phases a lane never leaves. */\nexport function isSettledSubagentLanePhase(phase: SubagentLanePhase): boolean {\n return phase === \"complete\" || phase === \"error\" || phase === \"stopped\";\n}\n\n/**\n * What a settled lane ended on, whole: its report, or why it failed. A lane\n * that the run's own failure ended has no result of its own, so the `task`\n * part's status says why (as the generic card shows a failed call). Empty\n * while the lane runs.\n */\nexport function subagentLaneResult({\n output,\n phase,\n partStatus,\n}: {\n /** The lane's own result text (`SubagentDiscoverySnapshot.output`). */\n output: string | undefined;\n phase: SubagentLanePhase;\n partStatus: ToolCallMessagePartStatus | undefined;\n}): string {\n if (!isSettledSubagentLanePhase(phase)) return \"\";\n const own = output?.trim() ?? \"\";\n if (own !== \"\" || phase !== \"error\" || partStatus?.type !== \"incomplete\") return own;\n const { error } = partStatus;\n if (error === undefined || error === null) return \"\";\n return (typeof error === \"string\" ? error : JSON.stringify(error)).trim();\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/**\n * How long a finished lane ran, measured by the server: the `task` result's\n * `_started_at` and `_created_at`, which the deep agent's tool-call timing\n * stamps on every tool result and mirrors onto its artifact (the one field of\n * a tool message the converter hands the tool-call part). `null` when either\n * stamp is missing.\n */\nexport function finishedLaneDurationMs(artifact: unknown): number | null {\n const stamps = record(artifact);\n const startedAt = readInstantMs(stamps?._started_at);\n const finishedAt = readInstantMs(stamps?.[MESSAGE_CREATED_AT_KEY]);\n return startedAt !== null && finishedAt !== null && finishedAt >= startedAt\n ? finishedAt - startedAt\n : null;\n}\n\nconst ASSISTANT_TYPES: ReadonlySet<unknown> = new Set([\"ai\", \"AIMessageChunk\"]);\n\n/**\n * When the agent delegated the call `toolCallId`: the server stamp\n * (`_created_at`) of the assistant message that made it, among the raw\n * messages bound to the turn. A running lane's card carries no stamp of its\n * own, so its clock counts from here, the way the turn header counts from the\n * turn's own stamps. `null` without one.\n */\nexport function laneDelegatedAtMs({\n sources,\n toolCallId,\n}: {\n sources: readonly unknown[];\n toolCallId: string;\n}): number | null {\n for (const source of sources) {\n const message = record(source);\n if (!message || !ASSISTANT_TYPES.has(message.type)) continue;\n const calls = message.tool_calls;\n if (!Array.isArray(calls) || !calls.some((call) => record(call)?.id === toolCallId)) continue;\n const kwargs = record(message.additional_kwargs);\n const metadata = record(kwargs?.metadata);\n return (\n readInstantMs(metadata?.[MESSAGE_CREATED_AT_KEY]) ??\n readInstantMs(kwargs?.[MESSAGE_CREATED_AT_KEY]) ??\n readInstantMs(message[MESSAGE_CREATED_AT_KEY])\n );\n }\n return null;\n}\n\n/**\n * The lane's newest tool step as its summary line (\"Read `routes.ts`\",\n * \"Running `npm test`\"), from the lane's converted steps: the last tool call\n * of its newest assistant turn, worded for whether it has answered. `null`\n * before the lane's first tool call.\n */\nexport function latestLaneStep(messages: readonly ThreadMessage[]): ToolCallSummary | null {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role !== \"assistant\") continue;\n for (let partIndex = message.content.length - 1; partIndex >= 0; partIndex -= 1) {\n const part = message.content[partIndex];\n if (part?.type !== \"tool-call\") continue;\n const answered = part.result !== undefined && part.isPreliminary !== true;\n return summarizeToolCall({\n toolName: part.toolName,\n args: part.args,\n result: answered ? part.result : undefined,\n status: answered ? (part.isError === true ? \"error\" : \"complete\") : \"running\",\n });\n }\n }\n return null;\n}\n\n/**\n * The subagent's type as the card names it: the `task` call's `subagent_type`\n * in words, with the default `general-purpose` agent as \"Subagent\".\n */\nexport function subagentTypeLabel(name: string): string {\n const trimmed = name.trim();\n if (trimmed === \"\" || trimmed === \"subagent\" || trimmed === \"general-purpose\") return \"Subagent\";\n return humanizeToolName(trimmed);\n}\n\n/** \"1 tool call\", \"12 tool calls\". */\nexport function toolCallCountLabel(count: number): string {\n return `${count} tool call${count === 1 ? \"\" : \"s\"}`;\n}\n\n/** \"1 step\", \"12 steps\". */\nfunction stepsLabel(count: number): string {\n return `${count} step${count === 1 ? \"\" : \"s\"}`;\n}\n\n/** What the steps panel says about the steps it shows of a cut lane. */\nexport function laneStepsNote({\n shown,\n total,\n arrivesLater,\n}: {\n /** Steps the panel shows. */\n shown: number;\n /** Steps the lane stores (its cut marker), when the card carries fewer. */\n total: number | undefined;\n /**\n * A running lane on a host that pages no running lane: its card brings the\n * rest once the subagent finishes.\n */\n arrivesLater: boolean;\n}): string | null {\n if (total === undefined || total <= shown) return null;\n const leftOff = total - shown;\n return arrivesLater\n ? `Showing the latest steps. ${leftOff} earlier ${leftOff === 1 ? \"step arrives\" : \"steps arrive\"} when this subagent finishes.`\n : `Showing the latest ${shown} of ${stepsLabel(total)}.`;\n}\n\n/**\n * Whether this card renders inside a read-only nested thread (a subagent's own\n * steps, under `ReadonlyThreadProvider`), whose thread has no statewire\n * extras. Never throws: rendered outside any thread, it is not nested.\n */\nfunction useInReadOnlyThread(): boolean {\n return useAuiState((s) => {\n const thread = s.optional?.thread;\n return thread !== undefined && !hasStatewireThreadExtras(thread.extras);\n });\n}\n\n/** A lane for a call agent-runtime read no lane for: what its arguments say, queued. */\nfunction laneFromArgs(toolCallId: string, args: unknown): SubagentDiscoverySnapshot {\n const record = typeof args === \"object\" && args !== null ? (args as Record<string, unknown>) : {};\n return {\n id: toolCallId,\n name: typeof record.subagent_type === \"string\" ? record.subagent_type : \"subagent\",\n description: typeof record.description === \"string\" ? record.description : \"\",\n status: \"queued\",\n toolCallCount: 0,\n messages: NO_MESSAGES,\n messageCount: 0,\n currentText: \"\",\n };\n}\n\n// ─── Status glyph ────────────────────────────────────────────────────\n\nfunction LaneStatusGlyph({ phase }: { phase: SubagentLanePhase }) {\n const glyph =\n phase === \"running\" ? (\n <LoaderIcon className=\"size-3.5 animate-spin text-muted-foreground motion-reduce:animate-none\" />\n ) : phase === \"complete\" ? (\n <CheckIcon className=\"size-3.5 text-emerald-600\" />\n ) : phase === \"error\" ? (\n <AlertCircleIcon className=\"size-3.5 text-destructive\" />\n ) : phase === \"stopped\" ? (\n <XCircleIcon className=\"size-3.5 text-muted-foreground\" />\n ) : phase === \"waiting\" || phase === \"approval\" ? (\n <ShieldAlertIcon className=\"size-3.5 text-amber-600\" />\n ) : (\n <CircleDashedIcon className=\"size-3.5 text-muted-foreground motion-safe:animate-pulse\" />\n );\n return (\n <span\n data-slot=\"subagent-status\"\n data-phase={phase}\n aria-hidden=\"true\"\n className=\"mt-0.5 flex size-4 shrink-0 items-center justify-center\"\n >\n {glyph}\n </span>\n );\n}\n\n// ─── Clock ───────────────────────────────────────────────────────────\n\n/**\n * How long a running lane has run: since `startMs` (the server's stamp on the\n * delegating message), else since this card saw it running; `null` while it\n * does not run. Ticks once a second off the wall clock.\n */\nfunction useRunningElapsedMs(running: boolean, startMs: number | null): number | null {\n const [clock, setClock] = useState<{ seenAt: number; now: number } | null>(null);\n useEffect(() => {\n if (!running) {\n setClock(null);\n return undefined;\n }\n const seenAt = Date.now();\n setClock({ seenAt, now: seenAt });\n const timer = setInterval(() => setClock({ seenAt, now: Date.now() }), 1000);\n return () => clearInterval(timer);\n }, [running]);\n if (!running || clock === null) return null;\n return Math.max(0, clock.now - (startMs ?? clock.seenAt));\n}\n\n// ─── The lane's steps ────────────────────────────────────────────────\n\ntype NestedPartsComponents = ReturnType<typeof useNestedPtcComponents>;\n\nconst LaneStepComponentsContext = createContext<NestedPartsComponents | null>(null);\n\nconst EmptyStepPart: FC = () => null;\n\n/**\n * One row of the lane: an assistant turn's parts, through the chat's own\n * renderers (`NestedPtcComponentsProvider`, which `AthenaChat` mounts). The\n * subagent's brief (its user message) is the card's own description, so it is\n * not repeated.\n */\nconst LaneStep: FC = () => {\n const role = useAuiState((s) => s.message.role);\n const components = useContext(LaneStepComponentsContext);\n if (role !== \"assistant\") return null;\n return <MessagePrimitive.Parts components={{ Empty: EmptyStepPart, ...components }} />;\n};\n\nconst LANE_ROW_COMPONENTS = { Message: LaneStep };\n\nconst ROW_KEY_SEPARATOR = \"\\u0000\";\n\n/**\n * The nested thread's rows, each under its row key (`deepAgentRowKey`): the\n * lane's turn keeps its row while the card's cut drops its oldest steps and\n * when earlier pages land, so what the person opened in it stays open.\n */\nfunction LaneRows() {\n const joinedKeys = useAuiState((s) =>\n s.thread.messages.map((message) => deepAgentRowKey(message)).join(ROW_KEY_SEPARATOR),\n );\n const rowKeys = useMemo(\n () => (joinedKeys === \"\" ? [] : joinedKeys.split(ROW_KEY_SEPARATOR)),\n [joinedKeys],\n );\n return (\n <>\n {rowKeys.map((key, index) => (\n <ThreadPrimitive.MessageByIndex key={key} index={index} components={LANE_ROW_COMPONENTS} />\n ))}\n </>\n );\n}\n\ninterface LaneStepsBoundaryProps {\n name: string;\n children: ReactNode;\n}\n\n/**\n * The steps' own boundary: they render the chat's tool UIs (a host's own\n * among them) in a nested thread no statewire thread backs, and a card that\n * throws there must not take the chat down. Reported like a chat render\n * crash, with the lane named.\n */\nclass LaneStepsBoundary extends Component<LaneStepsBoundaryProps, { failed: boolean }> {\n constructor(props: LaneStepsBoundaryProps) {\n super(props);\n this.state = { failed: false };\n }\n\n static getDerivedStateFromError(): { failed: boolean } {\n return { failed: true };\n }\n\n componentDidCatch(error: Error, errorInfo: ErrorInfo): void {\n athenaDiagnostics.error(\n \"sdk.error\",\n error,\n {\n code: \"chat_render_crash\",\n message: \"A subagent's steps could not be shown\",\n hint: \"Inspect component_stack: a tool UI that reads the live thread fails inside a subagent's read-only steps.\",\n },\n {\n surface: \"subagent-lane\",\n subagent: this.props.name,\n component_stack: errorInfo.componentStack?.slice(0, 2000) ?? null,\n },\n );\n }\n\n render(): ReactNode {\n if (this.state.failed) {\n return (\n <p role=\"alert\" className=\"px-1 text-xs text-muted-foreground\">\n These steps couldn't be shown. The conversation is not affected.\n </p>\n );\n }\n return this.props.children;\n }\n}\n\n/** The host's `QueryClient` when one is in context, else one of the panel's own (`useAthenaQueryClient`). */\nfunction LaneQueryScope({ children }: { children: ReactNode }) {\n const queryClient = useAthenaQueryClient();\n return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;\n}\n\ninterface LaneStepsProps {\n lane: SubagentDiscoverySnapshot;\n phase: SubagentLanePhase;\n /** What the lane ended on, whole (`subagentLaneResult`); empty while it runs. */\n result: string;\n /** The `task` part's own nested thread, shown if the panel cannot convert the lane itself. */\n partMessages: readonly ThreadMessage[] | undefined;\n}\n\n/**\n * The open card's steps: the lane the card carries, and the earlier steps the\n * person asks for. The panel converts the lane itself, with one conversion\n * memory while it is open (`createSubagentLaneConversion`), so the lane's turn\n * keeps its row key as the cut slides and pages land. It ends on what the lane\n * ended on, whole and selectable: the card clamps it.\n */\nfunction LaneSteps({ lane, phase, result, partMessages }: LaneStepsProps) {\n // The lane's card is its running placeholder, whether it streams or waits on an approval.\n const running = lane.status === \"running\" && (phase === \"running\" || phase === \"approval\");\n const source = lane.source;\n const history = useDeepAgentLaneHistory({\n messageId: source?.messageId,\n lane: source?.lane,\n carried: source?.transcript ?? NO_LANE_STEPS,\n total: source?.truncated?.messages,\n finished: source?.truncated?.finished === true,\n });\n const [convertLane] = useState(() => createSubagentLaneConversion());\n // A `task` lane that finished ends on its report, the card's content, even\n // when its stored transcript does not (`withLaneReport`), as in Olympus's drawer.\n const report =\n lane.status === \"complete\" && source?.messageId !== undefined ? lane.output : undefined;\n const messages =\n (source === undefined\n ? undefined\n : convertLane(withLaneReport(history.steps, report), running)) ??\n partMessages ??\n NO_MESSAGES;\n const components = useNestedPtcComponents(ToolFallback);\n const shown = history.steps.length;\n // A running card on a host that pages no running lane carries the rest once it finishes.\n const arrivesLater = running && source?.messageId !== undefined && !history.available;\n const note = laneStepsNote({ shown, total: history.total, arrivesLater });\n const emptyText =\n phase === \"running\"\n ? \"Starting…\"\n : phase === \"queued\" || phase === \"waiting\" || phase === \"approval\"\n ? \"Not started yet.\"\n : \"No steps were recorded for this subagent.\";\n // Why a lane failed is never one of its steps; a report is the closing\n // step of a lane with steps to close (`withLaneReport`).\n const failed = phase === \"error\";\n const closing = failed || messages.length === 0 ? result : \"\";\n\n return (\n <div data-slot=\"subagent-steps\" className=\"flex min-w-0 flex-col gap-2 px-2.5\">\n {lane.description ? (\n <p\n data-slot=\"subagent-brief\"\n className=\"whitespace-pre-wrap break-words text-xs leading-relaxed text-muted-foreground\"\n >\n {lane.description}\n </p>\n ) : null}\n {note ? (\n <div\n data-slot=\"subagent-steps-note\"\n className=\"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground\"\n >\n <span>{note}</span>\n {history.hasEarlier && !arrivesLater ? (\n <button\n type=\"button\"\n onClick={history.loadEarlier}\n disabled={history.loading}\n className=\"rounded font-medium text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default disabled:no-underline disabled:opacity-60\"\n >\n {history.loading ? \"Loading earlier steps…\" : \"Load earlier steps\"}\n </button>\n ) : null}\n </div>\n ) : null}\n {messages.length > 0 ? (\n <LaneStepsBoundary name={lane.name}>\n <LaneStepComponentsContext.Provider value={components}>\n <ReadonlyThreadProvider messages={messages}>\n <div data-slot=\"subagent-step-rows\" className=\"flex min-w-0 flex-col gap-1\">\n <LaneRows />\n </div>\n </ReadonlyThreadProvider>\n </LaneStepComponentsContext.Provider>\n </LaneStepsBoundary>\n ) : (\n <p className=\"text-xs text-muted-foreground\">{emptyText}</p>\n )}\n {closing ? (\n <div data-slot=\"subagent-result\" className=\"flex min-w-0 flex-col gap-0.5\">\n <p\n className={cn(\n \"text-xs font-medium\",\n failed ? \"text-destructive\" : \"text-muted-foreground\",\n )}\n >\n {failed ? \"Error\" : \"Report\"}\n </p>\n <p\n data-slot=\"subagent-result-text\"\n className={cn(\n \"max-h-72 overflow-auto whitespace-pre-wrap break-words text-xs leading-relaxed\",\n failed ? \"text-destructive/80\" : \"text-foreground/80\",\n )}\n >\n {closing}\n </p>\n </div>\n ) : null}\n </div>\n );\n}\n\n// ─── The card ────────────────────────────────────────────────────────\n\n/** The card's second line: where the lane is, its tool calls, how long it ran. */\nfunction laneMeta({\n phase,\n toolCallCount,\n elapsedMs,\n}: {\n phase: SubagentLanePhase;\n toolCallCount: number;\n elapsedMs: number | null;\n}): string {\n const parts: string[] = [SUBAGENT_LANE_PHASE_LABELS[phase]];\n if (toolCallCount > 0 || isSettledSubagentLanePhase(phase)) {\n parts.push(toolCallCountLabel(toolCallCount));\n }\n if (elapsedMs !== null && (phase !== \"running\" || elapsedMs >= 1000)) {\n parts.push(formatWorkDuration(elapsedMs));\n }\n return parts.join(\" · \");\n}\n\nfunction SubagentTaskCard({ toolCallId, args, status, artifact, messages }: ToolCallMessagePartProps) {\n const appearance = useToolAppearance();\n const isThread = appearance === \"thread\";\n const readLane = useAuiState((s) => taskSubagentsOfTurn(s.message).get(toolCallId));\n const lane = useMemo(\n () => readLane ?? laneFromArgs(toolCallId, args),\n [readLane, toolCallId, args],\n );\n // A lane holding a gated call the run's approval names waits on a person:\n // no live activity, no clock, just what it waits on. Read-only (the approval\n // card answers).\n const { toolCallIds: waitingToolCallIds } = useApprovalWaitInScope();\n const awaitingApproval = subagentAwaitingApproval({ lane, toolCallIds: waitingToolCallIds });\n const gatedCall = awaitingApproval\n ? subagentToolCallAwaitingApproval({ lane, toolCallIds: waitingToolCallIds })\n : undefined;\n const phase = subagentLanePhase({ status: lane.status, partStatus: status, awaitingApproval });\n const running = phase === \"running\";\n // Only a running lane's clock reads it, so a settled card scans nothing.\n const delegatedAt = useAuiState((s) =>\n running\n ? laneDelegatedAtMs({ sources: getExternalStoreMessages<unknown>(s.message), toolCallId })\n : null,\n );\n const runningElapsed = useRunningElapsedMs(running, delegatedAt);\n const elapsedMs = running\n ? runningElapsed\n : isSettledSubagentLanePhase(phase)\n ? finishedLaneDurationMs(artifact)\n : null;\n const step = useMemo(() => (running ? latestLaneStep(lane.messages) : null), [running, lane.messages]);\n const hasSteps = lane.messageCount > 0 || (lane.omittedMessageCount ?? 0) > 0;\n const typeLabel = subagentTypeLabel(lane.name);\n const title = lane.description.trim() || typeLabel;\n const meta = laneMeta({ phase, toolCallCount: lane.toolCallCount, elapsedMs });\n const liveText = step ? null : lane.currentText.trim();\n const report = subagentLaneResult({ output: lane.output, phase, partStatus: status });\n\n const header = (\n <>\n <LaneStatusGlyph phase={phase} />\n <span className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <span className=\"flex min-w-0 items-baseline gap-1.5\">\n <span\n data-slot=\"subagent-title\"\n title={lane.description || undefined}\n className=\"min-w-0 truncate font-medium text-foreground\"\n >\n {title}\n </span>\n {title !== typeLabel ? (\n <span\n data-slot=\"subagent-type\"\n className=\"shrink-0 rounded-full bg-muted px-1.5 py-px text-[10px] font-medium text-muted-foreground\"\n >\n {typeLabel}\n </span>\n ) : null}\n </span>\n <span\n data-slot=\"subagent-meta\"\n className={cn(\n \"text-xs tabular-nums text-muted-foreground\",\n phase === \"error\" && \"text-destructive\",\n )}\n >\n {meta}\n </span>\n {phase === \"approval\" ? (\n <span\n data-slot=\"subagent-approval\"\n className=\"flex min-w-0 items-baseline gap-1 text-xs text-muted-foreground\"\n >\n <span className=\"shrink-0 text-amber-700\">\n {gatedCall ? \"Needs approval to run\" : \"Needs approval to start\"}\n </span>\n {gatedCall ? (\n <>\n <code className=\"shrink-0 rounded bg-foreground/[0.06] px-1 py-px font-mono text-[11px] text-foreground/85\">\n {gatedCall.name}\n </code>\n <span className=\"min-w-0 truncate\">{salientToolCallDetail(gatedCall)}</span>\n </>\n ) : null}\n </span>\n ) : running ? (\n <span data-slot=\"subagent-activity\" className=\"min-w-0 truncate text-xs text-muted-foreground\">\n {step ? (\n <span title={step.detail}>\n <StepText text={step.label} code={step.code} />\n </span>\n ) : (\n liveText || \"Starting…\"\n )}\n </span>\n ) : null}\n </span>\n </>\n );\n\n return (\n <ToolFallbackRoot\n data-testid=\"subagent-task-card\"\n data-phase={phase}\n role=\"group\"\n aria-label={`Subagent: ${title}`}\n className={cn(isThread && phase === \"error\" && \"border-destructive/30 bg-destructive/5\")}\n >\n {/* A report or a failure is behind the disclosure whole, steps or none. */}\n {hasSteps || running || report ? (\n <CollapsibleTrigger\n data-slot=\"subagent-trigger\"\n className={cn(\n \"group/trigger flex w-full min-w-0 items-start gap-2 text-left text-[13px] leading-snug transition-colors hover:bg-muted/40\",\n isThread ? \"rounded-lg px-2.5 py-1.5\" : \"px-3\",\n )}\n >\n {header}\n <ChevronDownIcon\n aria-hidden=\"true\"\n className={cn(\n \"mt-0.5 size-3.5 shrink-0 text-muted-foreground/60\",\n \"transition-transform duration-(--animation-duration) ease-out\",\n \"group-data-[state=closed]/trigger:-rotate-90\",\n )}\n />\n </CollapsibleTrigger>\n ) : (\n <div\n data-slot=\"subagent-trigger\"\n className={cn(\n \"flex w-full min-w-0 items-start gap-2 text-[13px] leading-snug\",\n isThread ? \"px-2.5 py-1.5\" : \"px-3\",\n )}\n >\n {header}\n </div>\n )}\n {report ? (\n <p\n data-slot=\"subagent-report\"\n // Margins, not padding: a clamped block clips at its padding edge,\n // so bottom padding would show the top of the next line.\n className={cn(\n \"mb-1.5 line-clamp-3 whitespace-pre-line break-words text-xs leading-relaxed\",\n isThread ? \"mr-2.5 ml-8\" : \"mx-3 mt-1.5 ml-9\",\n phase === \"error\" ? \"text-destructive\" : \"text-foreground/80\",\n )}\n >\n {report}\n </p>\n ) : null}\n <ToolFallbackContent>\n <LaneQueryScope>\n <LaneSteps lane={lane} phase={phase} result={report} partMessages={messages} />\n </LaneQueryScope>\n </ToolFallbackContent>\n </ToolFallbackRoot>\n );\n}\n\n/**\n * A delegation inside a subagent's own steps: one static row. It is not the\n * run's lane to show; its steps live in the subagent's own transcript.\n */\nfunction SubagentDelegationRow({ args, result, isError, status }: ToolCallMessagePartProps) {\n const settled = result !== undefined && status?.type !== \"running\";\n const summary = summarizeToolCall({\n toolName: \"task\",\n args: typeof args === \"object\" && args !== null ? (args as Record<string, unknown>) : undefined,\n status: !settled ? \"running\" : isError === true ? \"error\" : \"complete\",\n });\n return (\n <div\n data-testid=\"subagent-delegation\"\n className=\"my-1 flex min-w-0 items-center gap-2 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-[13px]\"\n >\n <BotIcon aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-muted-foreground\" />\n <span title={summary.detail} className=\"min-w-0 truncate text-foreground\">\n {summary.label}\n </span>\n </div>\n );\n}\n\nconst SubagentTaskToolUIImpl: ToolCallMessagePartComponent = (props) =>\n useInReadOnlyThread() ? <SubagentDelegationRow {...props} /> : <SubagentTaskCard {...props} />;\n\n/**\n * The `task` tool UI (`TOOL_UI_REGISTRY.task`): the subagent card, or inside\n * a subagent's own steps, a static delegation row.\n */\nexport const SubagentTaskToolUI = memo(\n SubagentTaskToolUIImpl,\n) as unknown as ToolCallMessagePartComponent;\nSubagentTaskToolUI.displayName = \"SubagentTaskToolUI\";\n"],"names":["readInstantMs","MESSAGE_CREATED_AT_KEY","messages","summarizeToolCall","humanizeToolName","useAuiState","hasStatewireThreadExtras","record","LoaderIcon","jsx","CheckIcon","AlertCircleIcon","XCircleIcon","ShieldAlertIcon","CircleDashedIcon","useState","useEffect","createContext","useContext","MessagePrimitive","deepAgentRowKey","useMemo","Fragment","ThreadPrimitive","Component","athenaDiagnostics","useAthenaQueryClient","QueryClientProvider","useDeepAgentLaneHistory","createSubagentLaneConversion","withLaneReport","useNestedPtcComponents","ToolFallback","jsxs","ReadonlyThreadProvider","cn","formatWorkDuration","useToolAppearance","taskSubagentsOfTurn","useApprovalWaitInScope","subagentAwaitingApproval","subagentToolCallAwaitingApproval","getExternalStoreMessages","salientToolCallDetail","StepText","ToolFallbackRoot","CollapsibleTrigger","ChevronDownIcon","ToolFallbackContent","BotIcon","memo"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,MAAM,gBAA6C,CAAA;AACnD,MAAM,cAAwC,CAAA;AAsBvC,MAAM,6BAAgE;AAAA,EAC3E,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AACX;AAGO,SAAS,kBAAkB;A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EAAkB,GAAG,MAAA,CAAO;AAMvF,MAAM,qBAAqByC,WAAAA;AAAAA,EAChC;AACF;AACA,mBAAmB,cAAc;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"subagent-task-tool-ui.cjs","sources":["../../src/tools/subagent-task-tool-ui.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * The subagent card: one `task` call the deep agent delegated, shown the way\n * Olympus shows a subagent lane.\n *\n * - On the card: where the lane is (queued, running, done, failed, stopped),\n * how many tool calls it made (the wire's cut marker counts a lane whose\n * card carries only its newest steps), how long it has run, and while it\n * runs, its newest step; a finished lane's report, or why it failed, under\n * it, clamped.\n * - Behind its disclosure: the lane's steps, live while it runs, ending on\n * what the lane ended on, whole (a failure, or a report no step carries),\n * so a lane with no steps still opens to its full result. The lane is\n * assistant-ui's native nested thread: the `task` part's `messages`, which\n * the SDK runtime's opt-in conversion fills\n * (`createSubagentTranscriptConversionCache`), rendered read-only under\n * `ReadonlyThreadProvider` with the chat's own tool UIs. A cut lane (a\n * running card always; a finished one when the provider declares the\n * lane-cut contract, `subagentLaneHistory`) says how many of its steps it\n * shows, and \"Load earlier steps\" reads the rest with `history/lane`\n * (`useDeepAgentLaneHistory`), a read under the thread's own attach.\n *\n * A read-only nested thread has no statewire thread behind it: a `task` call\n * inside a subagent's own steps renders as a static row, and the steps are\n * their own error boundary, so a tool UI that throws there never takes the\n * chat down with it.\n */\nimport {\n getExternalStoreMessages,\n MessagePrimitive,\n ReadonlyThreadProvider,\n type ThreadMessage,\n ThreadPrimitive,\n type ToolCallMessagePartComponent,\n type ToolCallMessagePartProps,\n type ToolCallMessagePartStatus,\n useAuiState,\n} from \"@assistant-ui/react\";\nimport type { LangChainMessage } from \"@assistant-ui/react-langgraph\";\nimport {\n createSubagentLaneConversion,\n deepAgentRowKey,\n hasStatewireThreadExtras,\n SUBAGENT_AWAITING_APPROVAL_LABEL,\n salientToolCallDetail,\n type SubagentDiscoverySnapshot,\n type SubagentLaneApprovalWait,\n type SubagentStatus,\n subagentApprovalNoteLabel,\n taskSubagentsOfTurn,\n turnLaneApprovalWait,\n useDeepAgentLaneHistory,\n withLaneReport,\n} from \"@athenaintel/agent-runtime\";\nimport { QueryClientProvider } from \"@tanstack/react-query\";\nimport {\n AlertCircleIcon,\n BotIcon,\n CheckIcon,\n ChevronDownIcon,\n CircleDashedIcon,\n LoaderIcon,\n ShieldAlertIcon,\n XCircleIcon,\n} from \"lucide-react\";\nimport {\n Component,\n createContext,\n type ErrorInfo,\n type FC,\n memo,\n type ReactNode,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport { useApprovalWaitInScope } from \"../chat/use-statewire-approval-request\";\nimport { MESSAGE_CREATED_AT_KEY } from \"../chat/message-time\";\nimport { formatWorkDuration, readInstantMs } from \"../chat/super-grouping/turn-timing\";\nimport { athenaDiagnostics } from \"../diagnostics/athena-diagnostics\";\nimport { useAthenaQueryClient } from \"../lib/use-athena-rest-query\";\nimport { cn } from \"../lib/utils\";\nimport { CollapsibleTrigger } from \"../ui/collapsible\";\nimport { useNestedPtcComponents } from \"./NestedPtcMessages\";\nimport { StepText } from \"./step-text\";\nimport { useToolAppearance } from \"./tool-appearance\";\nimport { ToolFallback, ToolFallbackContent, ToolFallbackRoot } from \"./tool-fallback\";\nimport { humanizeToolName, summarizeToolCall, type ToolCallSummary } from \"./tool-summary\";\n\nconst NO_LANE_STEPS: readonly LangChainMessage[] = [];\nconst NOT_AWAITING_APPROVAL: SubagentLaneApprovalWait = { awaitingApproval: false, gatedCall: undefined };\nconst NO_MESSAGES: readonly ThreadMessage[] = [];\n\n// ─── What the card says ──────────────────────────────────────────────\n// Pure: where a lane is, how long it ran, the step it took last, and the\n// note over a cut lane's steps, tested without rendering the card.\n\n/**\n * Where a lane is, as the card shows it: the lane's own status, except that a\n * lane parked on a person's approval is `approval` (its own dispatch, or a call\n * it made, is a gated call nobody has answered; read as Spaces and the phone\n * read it, agent-runtime's `turnLaneApprovalWait`), any other call the run\n * waits on an answer for is `waiting`, and one the run stopped before it\n * settled is `stopped`.\n */\nexport type SubagentLanePhase =\n | \"queued\"\n | \"approval\"\n | \"waiting\"\n | \"running\"\n | \"complete\"\n | \"error\"\n | \"stopped\";\n\nexport const SUBAGENT_LANE_PHASE_LABELS: Record<SubagentLanePhase, string> = {\n queued: \"Queued\",\n approval: SUBAGENT_AWAITING_APPROVAL_LABEL,\n waiting: \"Waiting for you\",\n running: \"Running\",\n complete: \"Done\",\n error: \"Failed\",\n stopped: \"Stopped\",\n};\n\n/** The lane's phase from its status, the status assistant-ui gives its part, and the run's approval. */\nexport function subagentLanePhase({\n status,\n partStatus,\n awaitingApproval = false,\n}: {\n status: SubagentStatus;\n partStatus: ToolCallMessagePartStatus | undefined;\n /** The lane waits on a person's approval (agent-runtime's `turnLaneApprovalWait`). */\n awaitingApproval?: boolean;\n}): SubagentLanePhase {\n if (status === \"complete\" || status === \"error\") return status;\n if (awaitingApproval) return \"approval\";\n if (partStatus?.type === \"requires-action\") return \"waiting\";\n if (partStatus?.type === \"incomplete\") {\n return partStatus.reason === \"cancelled\" ? \"stopped\" : \"error\";\n }\n return status;\n}\n\n/** The phases a lane never leaves. */\nexport function isSettledSubagentLanePhase(phase: SubagentLanePhase): boolean {\n return phase === \"complete\" || phase === \"error\" || phase === \"stopped\";\n}\n\n/**\n * What a settled lane ended on, whole: its report, or why it failed. A lane\n * that the run's own failure ended has no result of its own, so the `task`\n * part's status says why (as the generic card shows a failed call). Empty\n * while the lane runs.\n */\nexport function subagentLaneResult({\n output,\n phase,\n partStatus,\n}: {\n /** The lane's own result text (`SubagentDiscoverySnapshot.output`). */\n output: string | undefined;\n phase: SubagentLanePhase;\n partStatus: ToolCallMessagePartStatus | undefined;\n}): string {\n if (!isSettledSubagentLanePhase(phase)) return \"\";\n const own = output?.trim() ?? \"\";\n if (own !== \"\" || phase !== \"error\" || partStatus?.type !== \"incomplete\") return own;\n const { error } = partStatus;\n if (error === undefined || error === null) return \"\";\n return (typeof error === \"string\" ? error : JSON.stringify(error)).trim();\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/**\n * How long a finished lane ran, measured by the server: the `task` result's\n * `_started_at` and `_created_at`, which the deep agent's tool-call timing\n * stamps on every tool result and mirrors onto its artifact (the one field of\n * a tool message the converter hands the tool-call part). `null` when either\n * stamp is missing.\n */\nexport function finishedLaneDurationMs(artifact: unknown): number | null {\n const stamps = record(artifact);\n const startedAt = readInstantMs(stamps?._started_at);\n const finishedAt = readInstantMs(stamps?.[MESSAGE_CREATED_AT_KEY]);\n return startedAt !== null && finishedAt !== null && finishedAt >= startedAt\n ? finishedAt - startedAt\n : null;\n}\n\nconst ASSISTANT_TYPES: ReadonlySet<unknown> = new Set([\"ai\", \"AIMessageChunk\"]);\n\n/**\n * When the agent delegated the call `toolCallId`: the server stamp\n * (`_created_at`) of the assistant message that made it, among the raw\n * messages bound to the turn. A running lane's card carries no stamp of its\n * own, so its clock counts from here, the way the turn header counts from the\n * turn's own stamps. `null` without one.\n */\nexport function laneDelegatedAtMs({\n sources,\n toolCallId,\n}: {\n sources: readonly unknown[];\n toolCallId: string;\n}): number | null {\n for (const source of sources) {\n const message = record(source);\n if (!message || !ASSISTANT_TYPES.has(message.type)) continue;\n const calls = message.tool_calls;\n if (!Array.isArray(calls) || !calls.some((call) => record(call)?.id === toolCallId)) continue;\n const kwargs = record(message.additional_kwargs);\n const metadata = record(kwargs?.metadata);\n return (\n readInstantMs(metadata?.[MESSAGE_CREATED_AT_KEY]) ??\n readInstantMs(kwargs?.[MESSAGE_CREATED_AT_KEY]) ??\n readInstantMs(message[MESSAGE_CREATED_AT_KEY])\n );\n }\n return null;\n}\n\n/**\n * The lane's newest tool step as its summary line (\"Read `routes.ts`\",\n * \"Running `npm test`\"), from the lane's converted steps: the last tool call\n * of its newest assistant turn, worded for whether it has answered. `null`\n * before the lane's first tool call.\n */\nexport function latestLaneStep(messages: readonly ThreadMessage[]): ToolCallSummary | null {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role !== \"assistant\") continue;\n for (let partIndex = message.content.length - 1; partIndex >= 0; partIndex -= 1) {\n const part = message.content[partIndex];\n if (part?.type !== \"tool-call\") continue;\n const answered = part.result !== undefined && part.isPreliminary !== true;\n return summarizeToolCall({\n toolName: part.toolName,\n args: part.args,\n result: answered ? part.result : undefined,\n status: answered ? (part.isError === true ? \"error\" : \"complete\") : \"running\",\n });\n }\n }\n return null;\n}\n\n/**\n * The subagent's type as the card names it: the `task` call's `subagent_type`\n * in words, with the default `general-purpose` agent as \"Subagent\".\n */\nexport function subagentTypeLabel(name: string): string {\n const trimmed = name.trim();\n if (trimmed === \"\" || trimmed === \"subagent\" || trimmed === \"general-purpose\") return \"Subagent\";\n return humanizeToolName(trimmed);\n}\n\n/** \"1 tool call\", \"12 tool calls\". */\nexport function toolCallCountLabel(count: number): string {\n return `${count} tool call${count === 1 ? \"\" : \"s\"}`;\n}\n\n/** \"1 step\", \"12 steps\". */\nfunction stepsLabel(count: number): string {\n return `${count} step${count === 1 ? \"\" : \"s\"}`;\n}\n\n/** What the steps panel says about the steps it shows of a cut lane. */\nexport function laneStepsNote({\n shown,\n total,\n arrivesLater,\n}: {\n /** Steps the panel shows. */\n shown: number;\n /** Steps the lane stores (its cut marker), when the card carries fewer. */\n total: number | undefined;\n /**\n * A running lane on a host that pages no running lane: its card brings the\n * rest once the subagent finishes.\n */\n arrivesLater: boolean;\n}): string | null {\n if (total === undefined || total <= shown) return null;\n const leftOff = total - shown;\n return arrivesLater\n ? `Showing the latest steps. ${leftOff} earlier ${leftOff === 1 ? \"step arrives\" : \"steps arrive\"} when this subagent finishes.`\n : `Showing the latest ${shown} of ${stepsLabel(total)}.`;\n}\n\n/**\n * Whether this card renders inside a read-only nested thread (a subagent's own\n * steps, under `ReadonlyThreadProvider`), whose thread has no statewire\n * extras. Never throws: rendered outside any thread, it is not nested.\n */\nfunction useInReadOnlyThread(): boolean {\n return useAuiState((s) => {\n const thread = s.optional?.thread;\n return thread !== undefined && !hasStatewireThreadExtras(thread.extras);\n });\n}\n\n/** A lane for a call agent-runtime read no lane for: what its arguments say, queued. */\nfunction laneFromArgs(toolCallId: string, args: unknown): SubagentDiscoverySnapshot {\n const record = typeof args === \"object\" && args !== null ? (args as Record<string, unknown>) : {};\n return {\n id: toolCallId,\n name: typeof record.subagent_type === \"string\" ? record.subagent_type : \"subagent\",\n description: typeof record.description === \"string\" ? record.description : \"\",\n status: \"queued\",\n toolCallCount: 0,\n messages: NO_MESSAGES,\n messageCount: 0,\n currentText: \"\",\n };\n}\n\n// ─── Status glyph ────────────────────────────────────────────────────\n\nfunction LaneStatusGlyph({ phase }: { phase: SubagentLanePhase }) {\n const glyph =\n phase === \"running\" ? (\n <LoaderIcon className=\"size-3.5 animate-spin text-muted-foreground motion-reduce:animate-none\" />\n ) : phase === \"complete\" ? (\n <CheckIcon className=\"size-3.5 text-emerald-600\" />\n ) : phase === \"error\" ? (\n <AlertCircleIcon className=\"size-3.5 text-destructive\" />\n ) : phase === \"stopped\" ? (\n <XCircleIcon className=\"size-3.5 text-muted-foreground\" />\n ) : phase === \"waiting\" || phase === \"approval\" ? (\n <ShieldAlertIcon className=\"size-3.5 text-amber-600\" />\n ) : (\n <CircleDashedIcon className=\"size-3.5 text-muted-foreground motion-safe:animate-pulse\" />\n );\n return (\n <span\n data-slot=\"subagent-status\"\n data-phase={phase}\n aria-hidden=\"true\"\n className=\"mt-0.5 flex size-4 shrink-0 items-center justify-center\"\n >\n {glyph}\n </span>\n );\n}\n\n// ─── Clock ───────────────────────────────────────────────────────────\n\n/**\n * How long a running lane has run: since `startMs` (the server's stamp on the\n * delegating message), else since this card saw it running; `null` while it\n * does not run. Ticks once a second off the wall clock.\n */\nfunction useRunningElapsedMs(running: boolean, startMs: number | null): number | null {\n const [clock, setClock] = useState<{ seenAt: number; now: number } | null>(null);\n useEffect(() => {\n if (!running) {\n setClock(null);\n return undefined;\n }\n const seenAt = Date.now();\n setClock({ seenAt, now: seenAt });\n const timer = setInterval(() => setClock({ seenAt, now: Date.now() }), 1000);\n return () => clearInterval(timer);\n }, [running]);\n if (!running || clock === null) return null;\n return Math.max(0, clock.now - (startMs ?? clock.seenAt));\n}\n\n// ─── The lane's steps ────────────────────────────────────────────────\n\ntype NestedPartsComponents = ReturnType<typeof useNestedPtcComponents>;\n\nconst LaneStepComponentsContext = createContext<NestedPartsComponents | null>(null);\n\nconst EmptyStepPart: FC = () => null;\n\n/**\n * One row of the lane: an assistant turn's parts, through the chat's own\n * renderers (`NestedPtcComponentsProvider`, which `AthenaChat` mounts). The\n * subagent's brief (its user message) is the card's own description, so it is\n * not repeated.\n */\nconst LaneStep: FC = () => {\n const role = useAuiState((s) => s.message.role);\n const components = useContext(LaneStepComponentsContext);\n if (role !== \"assistant\") return null;\n return <MessagePrimitive.Parts components={{ Empty: EmptyStepPart, ...components }} />;\n};\n\nconst LANE_ROW_COMPONENTS = { Message: LaneStep };\n\nconst ROW_KEY_SEPARATOR = \"\\u0000\";\n\n/**\n * The nested thread's rows, each under its row key (`deepAgentRowKey`): the\n * lane's turn keeps its row while the card's cut drops its oldest steps and\n * when earlier pages land, so what the person opened in it stays open.\n */\nfunction LaneRows() {\n const joinedKeys = useAuiState((s) =>\n s.thread.messages.map((message) => deepAgentRowKey(message)).join(ROW_KEY_SEPARATOR),\n );\n const rowKeys = useMemo(\n () => (joinedKeys === \"\" ? [] : joinedKeys.split(ROW_KEY_SEPARATOR)),\n [joinedKeys],\n );\n return (\n <>\n {rowKeys.map((key, index) => (\n <ThreadPrimitive.MessageByIndex key={key} index={index} components={LANE_ROW_COMPONENTS} />\n ))}\n </>\n );\n}\n\ninterface LaneStepsBoundaryProps {\n name: string;\n children: ReactNode;\n}\n\n/**\n * The steps' own boundary: they render the chat's tool UIs (a host's own\n * among them) in a nested thread no statewire thread backs, and a card that\n * throws there must not take the chat down. Reported like a chat render\n * crash, with the lane named.\n */\nclass LaneStepsBoundary extends Component<LaneStepsBoundaryProps, { failed: boolean }> {\n constructor(props: LaneStepsBoundaryProps) {\n super(props);\n this.state = { failed: false };\n }\n\n static getDerivedStateFromError(): { failed: boolean } {\n return { failed: true };\n }\n\n componentDidCatch(error: Error, errorInfo: ErrorInfo): void {\n athenaDiagnostics.error(\n \"sdk.error\",\n error,\n {\n code: \"chat_render_crash\",\n message: \"A subagent's steps could not be shown\",\n hint: \"Inspect component_stack: a tool UI that reads the live thread fails inside a subagent's read-only steps.\",\n },\n {\n surface: \"subagent-lane\",\n subagent: this.props.name,\n component_stack: errorInfo.componentStack?.slice(0, 2000) ?? null,\n },\n );\n }\n\n render(): ReactNode {\n if (this.state.failed) {\n return (\n <p role=\"alert\" className=\"px-1 text-xs text-muted-foreground\">\n These steps couldn't be shown. The conversation is not affected.\n </p>\n );\n }\n return this.props.children;\n }\n}\n\n/** The host's `QueryClient` when one is in context, else one of the panel's own (`useAthenaQueryClient`). */\nfunction LaneQueryScope({ children }: { children: ReactNode }) {\n const queryClient = useAthenaQueryClient();\n return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;\n}\n\ninterface LaneStepsProps {\n lane: SubagentDiscoverySnapshot;\n phase: SubagentLanePhase;\n /** What the lane ended on, whole (`subagentLaneResult`); empty while it runs. */\n result: string;\n /** The `task` part's own nested thread, shown if the panel cannot convert the lane itself. */\n partMessages: readonly ThreadMessage[] | undefined;\n}\n\n/**\n * The open card's steps: the lane the card carries, and the earlier steps the\n * person asks for. The panel converts the lane itself, with one conversion\n * memory while it is open (`createSubagentLaneConversion`), so the lane's turn\n * keeps its row key as the cut slides and pages land. It ends on what the lane\n * ended on, whole and selectable: the card clamps it.\n */\nfunction LaneSteps({ lane, phase, result, partMessages }: LaneStepsProps) {\n // The lane's card is its running placeholder, whether it streams or waits on an approval.\n const running = lane.status === \"running\" && (phase === \"running\" || phase === \"approval\");\n const source = lane.source;\n const history = useDeepAgentLaneHistory({\n messageId: source?.messageId,\n lane: source?.lane,\n carried: source?.transcript ?? NO_LANE_STEPS,\n total: source?.truncated?.messages,\n finished: source?.truncated?.finished === true,\n });\n const [convertLane] = useState(() => createSubagentLaneConversion());\n // A `task` lane that finished ends on its report, the card's content, even\n // when its stored transcript does not (`withLaneReport`), as in Olympus's drawer.\n const report =\n lane.status === \"complete\" && source?.messageId !== undefined ? lane.output : undefined;\n const messages =\n (source === undefined\n ? undefined\n : convertLane(withLaneReport(history.steps, report), running)) ??\n partMessages ??\n NO_MESSAGES;\n const components = useNestedPtcComponents(ToolFallback);\n const shown = history.steps.length;\n // A running card on a host that pages no running lane carries the rest once it finishes.\n const arrivesLater = running && source?.messageId !== undefined && !history.available;\n const note = laneStepsNote({ shown, total: history.total, arrivesLater });\n const emptyText =\n phase === \"running\"\n ? \"Starting…\"\n : phase === \"queued\" || phase === \"waiting\" || phase === \"approval\"\n ? \"Not started yet.\"\n : \"No steps were recorded for this subagent.\";\n // Why a lane failed is never one of its steps; a report is the closing\n // step of a lane with steps to close (`withLaneReport`).\n const failed = phase === \"error\";\n const closing = failed || messages.length === 0 ? result : \"\";\n\n return (\n <div data-slot=\"subagent-steps\" className=\"flex min-w-0 flex-col gap-2 px-2.5\">\n {lane.description ? (\n <p\n data-slot=\"subagent-brief\"\n className=\"whitespace-pre-wrap break-words text-xs leading-relaxed text-muted-foreground\"\n >\n {lane.description}\n </p>\n ) : null}\n {note ? (\n <div\n data-slot=\"subagent-steps-note\"\n className=\"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground\"\n >\n <span>{note}</span>\n {history.hasEarlier && !arrivesLater ? (\n <button\n type=\"button\"\n onClick={history.loadEarlier}\n disabled={history.loading}\n className=\"rounded font-medium text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default disabled:no-underline disabled:opacity-60\"\n >\n {history.loading ? \"Loading earlier steps…\" : \"Load earlier steps\"}\n </button>\n ) : null}\n </div>\n ) : null}\n {messages.length > 0 ? (\n <LaneStepsBoundary name={lane.name}>\n <LaneStepComponentsContext.Provider value={components}>\n <ReadonlyThreadProvider messages={messages}>\n <div data-slot=\"subagent-step-rows\" className=\"flex min-w-0 flex-col gap-1\">\n <LaneRows />\n </div>\n </ReadonlyThreadProvider>\n </LaneStepComponentsContext.Provider>\n </LaneStepsBoundary>\n ) : (\n <p className=\"text-xs text-muted-foreground\">{emptyText}</p>\n )}\n {closing ? (\n <div data-slot=\"subagent-result\" className=\"flex min-w-0 flex-col gap-0.5\">\n <p\n className={cn(\n \"text-xs font-medium\",\n failed ? \"text-destructive\" : \"text-muted-foreground\",\n )}\n >\n {failed ? \"Error\" : \"Report\"}\n </p>\n <p\n data-slot=\"subagent-result-text\"\n className={cn(\n \"max-h-72 overflow-auto whitespace-pre-wrap break-words text-xs leading-relaxed\",\n failed ? \"text-destructive/80\" : \"text-foreground/80\",\n )}\n >\n {closing}\n </p>\n </div>\n ) : null}\n </div>\n );\n}\n\n// ─── The card ────────────────────────────────────────────────────────\n\n/** The card's second line: where the lane is, its tool calls, how long it ran. */\nfunction laneMeta({\n phase,\n toolCallCount,\n elapsedMs,\n}: {\n phase: SubagentLanePhase;\n toolCallCount: number;\n elapsedMs: number | null;\n}): string {\n const parts: string[] = [SUBAGENT_LANE_PHASE_LABELS[phase]];\n if (toolCallCount > 0 || isSettledSubagentLanePhase(phase)) {\n parts.push(toolCallCountLabel(toolCallCount));\n }\n if (elapsedMs !== null && (phase !== \"running\" || elapsedMs >= 1000)) {\n parts.push(formatWorkDuration(elapsedMs));\n }\n return parts.join(\" · \");\n}\n\nfunction SubagentTaskCard({ toolCallId, args, status, artifact, messages }: ToolCallMessagePartProps) {\n const appearance = useToolAppearance();\n const isThread = appearance === \"thread\";\n const readLane = useAuiState((s) => taskSubagentsOfTurn(s.message).get(toolCallId));\n const lane = useMemo(\n () => readLane ?? laneFromArgs(toolCallId, args),\n [readLane, toolCallId, args],\n );\n // A lane holding a gated call the run's approval names waits on a person:\n // no live activity, no clock, just what it waits on. Read-only (the approval\n // card answers). A lane opened after its run parked carries no steps, so the\n // turn's other lanes say whether it holds the call (as Spaces reads it); the\n // turn is read only while something waits.\n const { toolCallIds: waitingToolCallIds, actionRequests } = useApprovalWaitInScope();\n const waitingTurn = useAuiState((s) => (waitingToolCallIds.size === 0 ? null : s.message));\n const approvalWait = useMemo<SubagentLaneApprovalWait>(\n () =>\n waitingTurn === null\n ? NOT_AWAITING_APPROVAL\n : turnLaneApprovalWait({\n message: waitingTurn,\n toolCallId,\n toolCallIds: waitingToolCallIds,\n actionRequests,\n }),\n [waitingTurn, toolCallId, waitingToolCallIds, actionRequests],\n );\n const { awaitingApproval, gatedCall } = approvalWait;\n const phase = subagentLanePhase({ status: lane.status, partStatus: status, awaitingApproval });\n const running = phase === \"running\";\n // Only a running lane's clock reads it, so a settled card scans nothing.\n const delegatedAt = useAuiState((s) =>\n running\n ? laneDelegatedAtMs({ sources: getExternalStoreMessages<unknown>(s.message), toolCallId })\n : null,\n );\n const runningElapsed = useRunningElapsedMs(running, delegatedAt);\n const elapsedMs = running\n ? runningElapsed\n : isSettledSubagentLanePhase(phase)\n ? finishedLaneDurationMs(artifact)\n : null;\n const step = useMemo(() => (running ? latestLaneStep(lane.messages) : null), [running, lane.messages]);\n const hasSteps = lane.messageCount > 0 || (lane.omittedMessageCount ?? 0) > 0;\n const typeLabel = subagentTypeLabel(lane.name);\n const title = lane.description.trim() || typeLabel;\n const meta = laneMeta({ phase, toolCallCount: lane.toolCallCount, elapsedMs });\n const liveText = step ? null : lane.currentText.trim();\n const report = subagentLaneResult({ output: lane.output, phase, partStatus: status });\n\n const header = (\n <>\n <LaneStatusGlyph phase={phase} />\n <span className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <span className=\"flex min-w-0 items-baseline gap-1.5\">\n <span\n data-slot=\"subagent-title\"\n title={lane.description || undefined}\n className=\"min-w-0 truncate font-medium text-foreground\"\n >\n {title}\n </span>\n {title !== typeLabel ? (\n <span\n data-slot=\"subagent-type\"\n className=\"shrink-0 rounded-full bg-muted px-1.5 py-px text-[10px] font-medium text-muted-foreground\"\n >\n {typeLabel}\n </span>\n ) : null}\n </span>\n <span\n data-slot=\"subagent-meta\"\n className={cn(\n \"text-xs tabular-nums text-muted-foreground\",\n phase === \"error\" && \"text-destructive\",\n )}\n >\n {meta}\n </span>\n {phase === \"approval\" ? (\n <span\n data-slot=\"subagent-approval\"\n className=\"flex min-w-0 items-baseline gap-1 text-xs text-muted-foreground\"\n >\n <span className=\"shrink-0 text-amber-700\">{subagentApprovalNoteLabel(approvalWait)}</span>\n {gatedCall ? (\n <>\n <code className=\"shrink-0 rounded bg-foreground/[0.06] px-1 py-px font-mono text-[11px] text-foreground/85\">\n {gatedCall.name}\n </code>\n <span className=\"min-w-0 truncate\">{salientToolCallDetail(gatedCall)}</span>\n </>\n ) : null}\n </span>\n ) : running ? (\n <span data-slot=\"subagent-activity\" className=\"min-w-0 truncate text-xs text-muted-foreground\">\n {step ? (\n <span title={step.detail}>\n <StepText text={step.label} code={step.code} />\n </span>\n ) : (\n liveText || \"Starting…\"\n )}\n </span>\n ) : null}\n </span>\n </>\n );\n\n return (\n <ToolFallbackRoot\n data-testid=\"subagent-task-card\"\n data-phase={phase}\n role=\"group\"\n aria-label={`Subagent: ${title}`}\n className={cn(isThread && phase === \"error\" && \"border-destructive/30 bg-destructive/5\")}\n >\n {/* A report or a failure is behind the disclosure whole, steps or none. */}\n {hasSteps || running || report ? (\n <CollapsibleTrigger\n data-slot=\"subagent-trigger\"\n className={cn(\n \"group/trigger flex w-full min-w-0 items-start gap-2 text-left text-[13px] leading-snug transition-colors hover:bg-muted/40\",\n isThread ? \"rounded-lg px-2.5 py-1.5\" : \"px-3\",\n )}\n >\n {header}\n <ChevronDownIcon\n aria-hidden=\"true\"\n className={cn(\n \"mt-0.5 size-3.5 shrink-0 text-muted-foreground/60\",\n \"transition-transform duration-(--animation-duration) ease-out\",\n \"group-data-[state=closed]/trigger:-rotate-90\",\n )}\n />\n </CollapsibleTrigger>\n ) : (\n <div\n data-slot=\"subagent-trigger\"\n className={cn(\n \"flex w-full min-w-0 items-start gap-2 text-[13px] leading-snug\",\n isThread ? \"px-2.5 py-1.5\" : \"px-3\",\n )}\n >\n {header}\n </div>\n )}\n {report ? (\n <p\n data-slot=\"subagent-report\"\n // Margins, not padding: a clamped block clips at its padding edge,\n // so bottom padding would show the top of the next line.\n className={cn(\n \"mb-1.5 line-clamp-3 whitespace-pre-line break-words text-xs leading-relaxed\",\n isThread ? \"mr-2.5 ml-8\" : \"mx-3 mt-1.5 ml-9\",\n phase === \"error\" ? \"text-destructive\" : \"text-foreground/80\",\n )}\n >\n {report}\n </p>\n ) : null}\n <ToolFallbackContent>\n <LaneQueryScope>\n <LaneSteps lane={lane} phase={phase} result={report} partMessages={messages} />\n </LaneQueryScope>\n </ToolFallbackContent>\n </ToolFallbackRoot>\n );\n}\n\n/**\n * A delegation inside a subagent's own steps: one static row. It is not the\n * run's lane to show; its steps live in the subagent's own transcript.\n */\nfunction SubagentDelegationRow({ args, result, isError, status }: ToolCallMessagePartProps) {\n const settled = result !== undefined && status?.type !== \"running\";\n const summary = summarizeToolCall({\n toolName: \"task\",\n args: typeof args === \"object\" && args !== null ? (args as Record<string, unknown>) : undefined,\n status: !settled ? \"running\" : isError === true ? \"error\" : \"complete\",\n });\n return (\n <div\n data-testid=\"subagent-delegation\"\n className=\"my-1 flex min-w-0 items-center gap-2 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-[13px]\"\n >\n <BotIcon aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-muted-foreground\" />\n <span title={summary.detail} className=\"min-w-0 truncate text-foreground\">\n {summary.label}\n </span>\n </div>\n );\n}\n\nconst SubagentTaskToolUIImpl: ToolCallMessagePartComponent = (props) =>\n useInReadOnlyThread() ? <SubagentDelegationRow {...props} /> : <SubagentTaskCard {...props} />;\n\n/**\n * The `task` tool UI (`TOOL_UI_REGISTRY.task`): the subagent card, or inside\n * a subagent's own steps, a static delegation row.\n */\nexport const SubagentTaskToolUI = memo(\n SubagentTaskToolUIImpl,\n) as unknown as ToolCallMessagePartComponent;\nSubagentTaskToolUI.displayName = \"SubagentTaskToolUI\";\n"],"names":["SUBAGENT_AWAITING_APPROVAL_LABEL","readInstantMs","MESSAGE_CREATED_AT_KEY","messages","summarizeToolCall","humanizeToolName","useAuiState","hasStatewireThreadExtras","record","LoaderIcon","jsx","CheckIcon","AlertCircleIcon","XCircleIcon","ShieldAlertIcon","CircleDashedIcon","useState","useEffect","createContext","useContext","MessagePrimitive","deepAgentRowKey","useMemo","Fragment","ThreadPrimitive","Component","athenaDiagnostics","useAthenaQueryClient","QueryClientProvider","useDeepAgentLaneHistory","createSubagentLaneConversion","withLaneReport","useNestedPtcComponents","ToolFallback","jsxs","ReadonlyThreadProvider","cn","formatWorkDuration","useToolAppearance","taskSubagentsOfTurn","useApprovalWaitInScope","turnLaneApprovalWait","getExternalStoreMessages","subagentApprovalNoteLabel","salientToolCallDetail","StepText","ToolFallbackRoot","CollapsibleTrigger","ChevronDownIcon","ToolFallbackContent","BotIcon","memo"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2FA,MAAM,gBAA6C,CAAA;AACnD,MAAM,wBAAkD,EAAE,kBAAkB,OAAO,WAAW,OAAA;AAC9F,MAAM,cAAwC,CAAA;AAuBvC,MAAM,6BAAgE;AAAA,EAC3E,QAAQ;AAAA,EACR,UAAUA,UAAAA;AAAAA,EACV,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AACX;AAGO,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA;AAAA,EACA,mBAAmB;AACrB,GAKsB;AACpB,MAAI,WAAW,cAAc,WAAW,QAAS,QAAO;AACxD,MAAI,iBAAkB,QAAO;AAC7B,OAAI,yCAAY,UAAS,kBAAmB,QAAO;AACnD,OAAI,yCAAY,UAAS,cAAc;AACrC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