@arbidocs/react 0.5.165 → 0.5.167
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/dist/ai/MessageArtifactCard.js +16 -0
- package/dist/ai/MessageArtifactCard.js.map +2 -2
- package/dist/artifacts/artifact-kind.js +12 -1
- package/dist/artifacts/artifact-kind.js.map +2 -2
- package/dist/artifacts/index.cjs +58 -47
- package/dist/artifacts/index.cjs.map +1 -1
- package/dist/artifacts/index.d.ts +3 -20
- package/dist/artifacts/index.js +3 -1
- package/dist/artifacts/index.js.map +2 -2
- package/dist/calls/livekit/index.cjs +51 -51
- package/dist/chat/ChatBubble.js +56 -65
- package/dist/chat/ChatBubble.js.map +2 -2
- package/dist/chat/open-document.js +4 -1
- package/dist/chat/open-document.js.map +2 -2
- package/dist/chat/request-agent-status.js +34 -0
- package/dist/chat/request-agent-status.js.map +7 -0
- package/dist/chat/run-finished.js +1 -0
- package/dist/chat/run-finished.js.map +2 -2
- package/dist/chat/useAgentRunControl.js +3 -3
- package/dist/chat/useAgentRunControl.js.map +2 -2
- package/dist/chat/useConnectRunStream.js +4 -0
- package/dist/chat/useConnectRunStream.js.map +2 -2
- package/dist/chat/useConversation.js +13 -10
- package/dist/chat/useConversation.js.map +2 -2
- package/dist/chat/useConversationActions.js +4 -3
- package/dist/chat/useConversationActions.js.map +2 -2
- package/dist/{chunk-XSJNRWLD.cjs → chunk-3DPOR5IR.cjs} +9 -6
- package/dist/chunk-3DPOR5IR.cjs.map +1 -0
- package/dist/{chunk-ZBRJEM25.cjs → chunk-4TWXQFHU.cjs} +70 -70
- package/dist/{chunk-ZBRJEM25.cjs.map → chunk-4TWXQFHU.cjs.map} +1 -1
- package/dist/{chunk-ZZBCZRA5.cjs → chunk-5QOZLKAY.cjs} +5 -2
- package/dist/chunk-5QOZLKAY.cjs.map +1 -0
- package/dist/{chunk-B3W7WDVY.cjs → chunk-BI4SYRLX.cjs} +73 -66
- package/dist/chunk-BI4SYRLX.cjs.map +1 -0
- package/dist/{chunk-ONAYOSSV.cjs → chunk-HRQS27DO.cjs} +39 -39
- package/dist/{chunk-ONAYOSSV.cjs.map → chunk-HRQS27DO.cjs.map} +1 -1
- package/dist/{chunk-DQODLWFX.cjs → chunk-KULS4YWP.cjs} +3 -3
- package/dist/{chunk-DQODLWFX.cjs.map → chunk-KULS4YWP.cjs.map} +1 -1
- package/dist/{chunk-V5WCKJEH.cjs → chunk-Q7BGWKHP.cjs} +44 -44
- package/dist/{chunk-V5WCKJEH.cjs.map → chunk-Q7BGWKHP.cjs.map} +1 -1
- package/dist/{chunk-352P2C4E.cjs → chunk-TX7UCN73.cjs} +14 -14
- package/dist/{chunk-352P2C4E.cjs.map → chunk-TX7UCN73.cjs.map} +1 -1
- package/dist/{chunk-WJIRX5MS.cjs → chunk-W4W75MSO.cjs} +134 -25
- package/dist/chunk-W4W75MSO.cjs.map +1 -0
- package/dist/chunk-WABJGKVA.cjs +246 -0
- package/dist/chunk-WABJGKVA.cjs.map +1 -0
- package/dist/databases.js.map +2 -2
- package/dist/directmessages/DmComposer.js +26 -10
- package/dist/directmessages/DmComposer.js.map +2 -2
- package/dist/directmessages/index.js +2 -0
- package/dist/directmessages/index.js.map +2 -2
- package/dist/directmessages/useChats.js +11 -0
- package/dist/directmessages/useChats.js.map +2 -2
- package/dist/document-tools/core.cjs +102 -102
- package/dist/document-tools/core.d.ts +2 -2
- package/dist/document-tools/index.cjs +104 -104
- package/dist/document-tools/index.d.ts +2 -2
- package/dist/entities/DocumentEntity.js +8 -3
- package/dist/entities/DocumentEntity.js.map +2 -2
- package/dist/entities/EntityActionsMenu.js +53 -0
- package/dist/entities/EntityActionsMenu.js.map +7 -0
- package/dist/entities/EntityPill.js +50 -16
- package/dist/entities/EntityPill.js.map +2 -2
- package/dist/entities/ProjectEntity.js +4 -0
- package/dist/entities/ProjectEntity.js.map +2 -2
- package/dist/entities/TagEntity.js +1 -0
- package/dist/entities/TagEntity.js.map +2 -2
- package/dist/entities/UserEntity.js +25 -3
- package/dist/entities/UserEntity.js.map +2 -2
- package/dist/entities/links.js +9 -0
- package/dist/entities/links.js.map +7 -0
- package/dist/entities/reference-data.js +56 -0
- package/dist/entities/reference-data.js.map +7 -0
- package/dist/{file-shares.d-Bwy9k3Db.d.ts → file-shares.d-Dlt7pKRi.d.ts} +3 -0
- package/dist/host/config.js.map +2 -2
- package/dist/index.cjs +2654 -2529
- package/dist/index.cjs.map +1 -1
- package/dist/{index.d-Dy_Pz6Vl.d.ts → index.d-BaZUctD1.d.ts} +34 -10
- package/dist/index.d.ts +164 -20
- package/dist/index.js +5 -0
- package/dist/index.js.map +2 -2
- package/dist/query-keys.js +3 -0
- package/dist/query-keys.js.map +2 -2
- package/dist/session/conversation-panels.js +5 -3
- package/dist/session/conversation-panels.js.map +2 -2
- package/dist/session/layout.js +5 -0
- package/dist/session/layout.js.map +2 -2
- package/dist/shell/index.cjs +40 -40
- package/dist/{stored-markdown.d-Bp18vrbr.d.ts → stored-markdown.d-BLQPny3e.d.ts} +21 -1
- package/dist/ui/index.cjs +168 -164
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +2 -0
- package/dist/ui/index.js.map +2 -2
- package/dist/viewers/AudioViewer.js +13 -3
- package/dist/viewers/AudioViewer.js.map +2 -2
- package/dist/viewers/MediaTranscriptPlayer.js +171 -0
- package/dist/viewers/MediaTranscriptPlayer.js.map +7 -0
- package/dist/viewers/VideoViewer.js +4 -11
- package/dist/viewers/VideoViewer.js.map +2 -2
- package/dist/viewers/index.cjs +16 -12
- package/dist/viewers/index.d.ts +17 -3
- package/dist/viewers/index.js +2 -0
- package/dist/viewers/index.js.map +2 -2
- package/package.json +3 -3
- package/dist/chunk-B3W7WDVY.cjs.map +0 -1
- package/dist/chunk-TMPDW7J5.cjs +0 -79
- package/dist/chunk-TMPDW7J5.cjs.map +0 -1
- package/dist/chunk-WJIRX5MS.cjs.map +0 -1
- package/dist/chunk-XSJNRWLD.cjs.map +0 -1
- package/dist/chunk-ZZBCZRA5.cjs.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/chat/useConversationActions.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The chat engine's actions on a conversation: send (a turn, or a comment to the people in a\n * thread), branch, retry, stop, and the run-control commands typed while a turn runs. A turn goes\n * through `arbi.assistant.ask`, its frames through the stream handlers, and its state lives in the\n * session (`ArbiSessionState`) and the conversation cache.\n */\n\nimport { flushDocumentForTurn } from './turn-flush'\nimport { pendingChatModelSave } from '../config/config-hooks'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { useQueryClient, type QueryClient } from '@tanstack/react-query'\nimport {\n ArbiApiError,\n STOP_REPEAT_WINDOW_MS,\n getRunToCancel,\n quotaFromStreamError,\n type ConversationResponse as Conversation,\n type ThreadsResponse,\n} from '@arbidocs/sdk/browser'\nimport type { components } from '@arbidocs/client'\nimport { notify } from '../shell'\nimport { arbiQueryKeys } from '../hooks'\nimport { useArbi } from '../useArbi'\nimport { useArbiHost } from '../host/config'\nimport { selectDraft, useArbiSessionStore } from '../session'\nimport type { ArbiSessionStore } from '../session/store'\nimport {\n invalidateConversationLists,\n isConversationShared,\n patchConversation,\n patchConversationList,\n removeConversationFromLists,\n} from '../conversation-list'\nimport {\n allConversationThreads,\n clearLoadingState,\n flushStreamingTokens,\n getThreadsQueryKey,\n isConversationEmpty,\n updateUserMessageStateInCache,\n} from './conversation-cache'\nimport {\n assistantLabels,\n cachedAssistantMode,\n cachedMentionCandidates,\n isCommentToPeople,\n} from './conversation-mentions'\nimport { useAssistantName } from '../host/assistant-copy'\nimport { hasMessageBody, toMessageMentions, extractMentions } from './mentions'\nimport { takeDocumentForTurn } from './open-document'\nimport { agentChatOwnerOf, creatorOf } from './agent-chat-owner'\nimport { bindThreadDocument, boundDocumentOf } from './thread-binding'\nimport { resolveReplyTarget } from './reply-target'\nimport {\n confirmConversationWorkspace,\n conversationWorkspaceOf,\n watchConversationWorkspaces,\n} from './conversation-workspace'\nimport { useStreamHandlers, type StreamState } from './stream-handlers'\nimport {\n AGENT_CONTROL_COMMANDS,\n cachedQuotaUsedUp,\n disconnectAttachedRun,\n refuseChatWhenOffline,\n waitForResponseId,\n} from './turn-control'\n\ntype MessageInput = components['schemas']['MessageInput']\ntype MessageMention = components['schemas']['MessageMention']\n\n/** How long a dropped turn holds its generating state while the thread is re-read. */\nconst RECONCILE_TIMEOUT_MS = 5000\n\nexport interface SendMessageOptions {\n /** An explicit edit/fork, rather than appending a human message to the shared thread. */\n branch?: boolean\n queuedContinuation?: boolean\n queueOwnerAssistantId?: string\n queuedClientId?: string\n /**\n * Bypasses the normal single-pinned-document tools computation (the chat's documents and its\n * pin, see `buildTurnRequest`) for this one send.\n * The app's general \"pin a document\" feature is deliberately one-at-a-time\n * (`selectFullContextDocument`) \u2014 a pinned TEXT doc's full content goes\n * straight into the AGENT's chat prompt, so more than one at a time risks\n * blowing that context window. Generate image is a different resource\n * entirely: reference images never touch the agent's chat context \u2014 they go\n * to the separate ImageGen model in its own request \u2014 so multiple\n * references (e.g. \"combine these two logos\") don't compound against that\n * budget, even though they still cost real tokens against ImageGen's own\n * call. This lets that caller build its own tools object with every\n * selected reference doc instead of touching the single global pin.\n */\n toolsOverride?: MessageInput['tools']\n /**\n * Send in this conversation and workspace rather than the open ones: a follow-up captured when\n * its turn started (a deferred interjection), sent after the view may have moved on.\n */\n target?: TurnTarget\n}\n\n/** The conversation and workspace a turn belongs to, captured when it starts. */\nexport interface TurnTarget {\n workspaceId: string\n conversationId: string\n}\n\n/**\n * The draft a send leaves behind. A shared chat addresses ARBI again, except after a comment to\n * people: then the box is left empty, which a shared chat reads as a comment to the thread.\n */\nfunction draftAfterSend(\n queryClient: QueryClient,\n session: ArbiSessionStore,\n wasComment: boolean,\n assistantName: string\n): string {\n const shared = isConversationShared(queryClient, session.getState().conversationId)\n return shared && !wasComment ? `@${assistantName} ` : ''\n}\n\n/**\n * A queued follow-up the backend refused before its turn started: mark its bubble failed and\n * take it out of the queue, so it does not sit there as if it were still waiting.\n */\nfunction failQueuedContinuation(\n queryClient: QueryClient,\n session: ArbiSessionStore,\n streamState: {\n conversationId: string\n queuedUserMessageId: string | null\n queueOwnerAssistantId: string | null\n queuedClientId: string | null\n }\n): void {\n if (streamState.queuedUserMessageId) {\n updateUserMessageStateInCache(\n queryClient,\n streamState.conversationId,\n streamState.queuedUserMessageId,\n 'failed',\n false\n )\n }\n if (streamState.queuedClientId) {\n session.removeQueuedMessage(streamState.queuedClientId)\n }\n notify.error('Queued message failed to send')\n}\n\n/** The signed-in user's id, or null before the session is known. */\nfunction signedInUserId(arbi: { user: { identity: () => { externalId: string } | null } }) {\n try {\n return arbi.user.identity()?.externalId ?? null\n } catch {\n return null\n }\n}\n\n/** What the actions act on: the open workspace and conversation, as the session holds them. */\nexport interface ConversationActionsInput {\n selectedWorkspaceId: string | null\n /** The cursor when the view rendered (the stream handlers place a branch against it). */\n parentMessageId: string | null\n /** The open conversation's key (`new` for a new chat). */\n conversationKey: string\n isGenerating: boolean\n lastFailedMessage: string | null\n}\n\n/** The actions on the open conversation. */\nexport function useConversationActions({\n selectedWorkspaceId,\n parentMessageId,\n conversationKey,\n isGenerating,\n lastFailedMessage,\n}: ConversationActionsInput) {\n const queryClient = useQueryClient()\n const session = useArbiSessionStore()\n const currentConversationId = conversationKey === 'new' ? null : conversationKey\n const invalidateUserWorkspaces = useCallback(\n () => void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() }),\n [queryClient]\n )\n\n const arbi = useArbi()\n // Each conversation stays in the workspace it was opened in, though the surface switches.\n useState(() => watchConversationWorkspaces(queryClient, session))\n const createHandlers = useStreamHandlers()\n const chatHost = useArbiHost().chat\n const assistantName = useAssistantName()\n const mentionCandidates = useCallback(\n () =>\n cachedMentionCandidates(\n queryClient,\n session.getState().workspaceId,\n signedInUserId(arbi),\n assistantName\n ),\n [queryClient, session, arbi, assistantName]\n )\n // The local stream a Stop is closing. Stop cancels the run on the server before it aborts the\n // stream, so the connection can drop first with a network error that is not an abort.\n const stoppedStreamRef = useRef<AbortController | null>(null)\n // True while a Stop's server cancel is in flight, so a second press does not cancel again.\n const stopInFlightRef = useRef(false)\n // When the last Stop was pressed. A press within STOP_REPEAT_WINDOW_MS of it is a double tap.\n const lastStopAtRef = useRef(0)\n // True while a Retry deletes and resends, so a second press does not do it again.\n const retryInFlightRef = useRef(false)\n // Lets sendMessage resubmit a deferred interjection as a new turn without a\n // self-reference (it is a useCallback that would otherwise close over a stale\n // or not-yet-defined copy of itself). Kept current just below its definition.\n const sendMessageRef = useRef<\n | ((content: string, parentId?: string | null, options?: SendMessageOptions) => Promise<void>)\n | null\n >(null)\n\n /**\n * Shared posts, and posts in a `mentioned` thread, run ARBI only when addressed; posts in an\n * ordinary solo chat address it implicitly.\n */\n const routeMessage = useCallback(\n (content: string, conversationId?: string | null) => {\n const state = session.getState()\n const convId = conversationId === undefined ? state.conversationId : conversationId\n const { newConversationAssistantMode } = state\n const candidates = mentionCandidates()\n const mentioned = extractMentions(content, candidates)\n const assistantMode = cachedAssistantMode(queryClient, convId, newConversationAssistantMode)\n const isComment = isCommentToPeople(queryClient, convId, content, candidates)\n const mentions = toMessageMentions(mentioned) as MessageMention[]\n // A message not taken as a comment addresses ARBI. In an existing `mentioned` thread that is\n // only one that @mentions it; what is left is the first message of a thread not created\n // yet, whose turn creates it in `mentioned` mode.\n if (\n !isComment &&\n assistantMode === 'mentioned' &&\n !mentions.some((m) => m.type === 'assistant')\n ) {\n mentions.push({ type: 'assistant' })\n }\n return {\n mentions,\n assistantMode,\n isComment,\n }\n },\n [queryClient, session, mentionCandidates]\n )\n\n /** Post a comment (no assistant run) and land the thread on it. */\n const postComment = useCallback(\n async (\n content: string,\n parentId: string | null,\n mentions: MessageMention[],\n branch = false\n ) => {\n const convId = session.getState().conversationId\n try {\n const saved = await arbi.conversations.postMessage({\n content,\n mentions,\n // Only an explicit edit creates a branch. Ordinary comments append to the\n // server's latest message, so simultaneous sends stay visible together. Else\n // (nothing yet) start a thread. The mode only applies to a conversation it creates.\n ...(branch && parentId\n ? { previous_message_ext_id: parentId }\n : convId\n ? { conversation_ext_id: convId }\n : {}),\n assistant_mode: 'mentioned',\n })\n const conversationId = saved.conversation_ext_id\n const nowIso = new Date().toISOString()\n if (!convId) {\n // A comment starts the thread without a turn to carry its binding: bind it right after.\n const bindTo = session.getState().newChatDocumentId\n session.moveConversation('new', conversationId)\n if (bindTo) session.setNewChatDocumentId(null)\n patchConversationList(queryClient, session.getState().workspaceId, (old) => [\n {\n external_id: conversationId,\n title: content.slice(0, 40),\n created_by_ext_id: saved.created_by_ext_id,\n updated_by_ext_id: null,\n created_at: nowIso,\n updated_at: nowIso,\n // A mention of someone who cannot see it yet shares it server-side: refetched below.\n is_shared: false,\n message_count: 1,\n last_message_status: 'completed',\n assistant_mode: 'mentioned',\n } as Conversation,\n ...old,\n ])\n if (bindTo)\n bindThreadDocument(arbi, queryClient, conversationId, bindTo).catch(() =>\n notify.error('Could not attach the document to this thread')\n )\n invalidateUserWorkspaces()\n } else {\n patchConversation(queryClient, conversationId, (c) => ({\n ...c,\n message_count: c.message_count + 1,\n updated_at: nowIso,\n }))\n }\n // Mentioning someone shares the conversation on the server, which this cache cannot know.\n if (mentions.some((m) => m.type === 'user')) {\n await invalidateConversationLists(queryClient)\n }\n await queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n session.setCursor(saved.external_id)\n } catch (error) {\n notify.error(\n (error instanceof ArbiApiError && error.detail) || 'Failed to post the message'\n )\n // Give the text back rather than lose it.\n if (!selectDraft(session.getState())) session.setDraft(content)\n }\n },\n [arbi, session, queryClient, invalidateUserWorkspaces]\n )\n\n const sendMessage = useCallback(\n async (content: string, requestedParentId?: string | null, options?: SendMessageOptions) => {\n // Never reply to a failed or deleted message: the server refuses it, so every Retry and every\n // new message would fail again. A queued follow-up names the running turn on purpose. With\n // nothing above to reply to, the parent stays: only a fresh conversation could take it.\n const target = options?.target\n const parentId =\n options?.queuedContinuation || !requestedParentId\n ? requestedParentId\n : (resolveReplyTarget(\n queryClient,\n (target ? target.conversationId : session.getState().conversationId) || 'new',\n requestedParentId\n ) ?? requestedParentId)\n const route = routeMessage(content, target?.conversationId)\n if (route.isComment && !options?.queuedContinuation && !target) {\n await postComment(content, parentId ?? null, route.mentions, options?.branch)\n return\n }\n // A model picked just now is still being saved: the turn runs on it, not on the config before.\n const modelSave = pendingChatModelSave(session)\n if (modelSave) await modelSave.catch(() => undefined)\n const state = session.getState()\n const convId = target ? target.conversationId : state.conversationId\n const convKey = convId || 'new'\n // The turn's workspace, captured now: the conversation's own (a docked or scoped chat keeps\n // its conversation across a switch), else the surface's for a new conversation. Named on the\n // request, so neither a switch nor the session's open workspace can move it.\n const turnWorkspaceId =\n target?.workspaceId ?? conversationWorkspaceOf(queryClient, convId) ?? selectedWorkspaceId\n const agentChat = state.newAgentChat\n // An existing conversation's agent: as recorded, else its creator when that is one of the\n // person's own agents (an agent chat runs under the agent's session; the record does not\n // survive a sign-out, or another device).\n let agentExtId = convId\n ? state.agentChatOwners[convId]\n : agentChat?.workspaceId === turnWorkspaceId\n ? agentChat.agentId\n : undefined\n // Only a conversation an agent created is looked up (an ordinary send never waits on it).\n if (convId && !agentExtId && creatorOf(queryClient, convId)?.startsWith('agt-')) {\n agentExtId = await agentChatOwnerOf(queryClient, () => arbi.agents.list(), convId)\n if (agentExtId) session.setAgentChatOwner(convId, agentExtId)\n }\n const queuedContinuation = options?.queuedContinuation === true\n // First message of a brand-new conversation bumps the workspace's\n // conversation_count \u2014 used to tick the \"Ask ARBI\" onboarding step.\n const isNewConversation = !convId\n\n const documentIds = (state.conversationDocuments[convKey] || []).map((doc) => doc.docId)\n // The chat's facts ride every message of it (snapshot semantics, like its documents).\n const factIds = [...(state.conversationFacts[convKey] || [])]\n\n const newConfigId = state.chatModel\n\n // Frontend is the single source of truth for which config a request\n // uses (Option B): send the same config the model selector resolves &\n // displays (see useConversationSettings) \u2014 explicit per-conversation\n // choice (`newConfigId`) wins, otherwise the user's persisted\n // `last_config`, so a selected config (e.g. one with ARTIFACTS_ENABLED)\n // actually drives the chat instead of being silently dropped to an\n // empty config. `newConfigId` alone is insufficient \u2014 it is transient\n // and cleared on every new conversation. Read `last_config` from the\n // shared settings cache by partial key match: openapi-react-query\n // suffixes the query key with request options and the settings hook is\n // token-gated, so the hook value can momentarily be undefined here even\n // though the data is cached app-wide.\n const cachedSettings = queryClient\n .getQueriesData<{ last_config?: string }>({ queryKey: arbiQueryKeys.userSettings() })\n .map(([, data]) => data)\n .find((data) => data?.last_config)\n const lastConfigId = cachedSettings?.last_config\n const resolvedConfigId = newConfigId || (agentExtId ? undefined : lastConfigId)\n\n // PA mode delegates the turn to the personal agent (`buildTurnRequest` prefixes `/pa ` so\n // the backend routes it straight to the delegation stream).\n const isPaMode = !agentExtId && state.paMode\n\n // Drafting mode: the thread's own document is named (a reference, never its content): the one\n // the thread is bound to (started from it, or attached in it), else one made in this thread\n // and open. A document merely open beside a chat is not: a new chat starts unbound. While an\n // earlier version of it is on screen the viewer returns to the live document. For a Word\n // document the server binds the live document: the assistant reads what it needs on demand\n // and edits it as tracked changes. For an html/react artifact it gets the source and a\n // targeted edit tool. PA-mode turns are delegated to a separate agent and never touch\n // artifacts.\n const threadDocumentId = boundDocumentOf(queryClient, { ...state, conversationId: convId })\n const activeArtifactExtId = isPaMode\n ? null\n : takeDocumentForTurn({\n boundDocumentId: threadDocumentId,\n conversationId: convId,\n workspaceId: turnWorkspaceId,\n })\n\n // An editor holding unsaved changes to that document saves them first: ARBI works on what\n // the person sees.\n const flushing = flushDocumentForTurn(activeArtifactExtId)\n if (flushing) await flushing\n\n // A workflow launch can leave structured tools for its one send; consume them here.\n const pendingTools = state.pendingTools\n if (pendingTools) session.setPendingTools(null)\n const toolsOverride = options?.toolsOverride ?? pendingTools ?? undefined\n\n const request = {\n question: content,\n workspaceId: turnWorkspaceId!,\n docIds: documentIds,\n pinnedDocumentId: state.pinnedDocumentId,\n factIds,\n tools: toolsOverride,\n personalAgent: isPaMode,\n activeArtifactExtId,\n // A new chat about a document is bound by its first turn, on the server (every device).\n ...(!convId && threadDocumentId ? { bindDocumentId: threadDocumentId } : {}),\n previousResponseId: parentId,\n // The first turn of an existing conversation with no message yet (a task's thread) runs in\n // it: without its id the server starts a new conversation for the turn.\n ...(convId && !parentId && !options?.branch && isConversationEmpty(queryClient, convId)\n ? { conversationId: convId }\n : {}),\n agentId: agentExtId,\n model: resolvedConfigId,\n mentions: route.mentions,\n // A brand-new conversation starts in the mode picked in the composer.\n ...(!convId && route.assistantMode === 'mentioned'\n ? { assistantMode: 'mentioned' as const }\n : {}),\n }\n\n const abortController = new AbortController()\n if (!queuedContinuation) {\n session.setConversationGenerating(convKey, true, abortController)\n }\n\n // Optimistically mark this conversation in-progress the instant we start a\n // turn. Without this, Conversation's \"reconcile stale isGenerating\" effect\n // runs on the setConversationGenerating(true) above, sees the conversation\n // list's last_message_status still 'completed' from the PREVIOUS turn (the\n // stream_start patch below only lands ~50ms later), and immediately clears\n // isGenerating \u2014 which race-hid the live status bar on every follow-up\n // turn (first turns were exempt: the new conversation isn't in the list\n // yet). Patching here closes that window. No-op for a brand-new\n // conversation (convKey === 'new' isn't in the list).\n if (!queuedContinuation) {\n patchConversation(queryClient, convKey, { last_message_status: 'in_progress' })\n }\n\n // Mutable stream state \u2014 shared by all SSE handlers via closure\n const streamState: StreamState = {\n conversationId: convKey,\n workspaceId: turnWorkspaceId,\n assistantId: null,\n // 0 = nothing narrated yet, so nothing is owed a reading window.\n lastNarrationSettledAt: 0,\n // True once the model has pivoted to a tool call and not yet resumed\n // prose. Prose arriving while this is set opens a NEW narration, so the\n // one before it closes: paragraph break, and everything above becomes\n // superseded. Item boundaries alone cannot say this \u2014 the backend splits\n // a single sentence across several items.\n pivotedSinceProse: false,\n // Steering that landed too late to steer this turn; resubmitted as a new\n // turn once this one completes (see after the ask below).\n deferredInterjections: [],\n queuedContinuation,\n queuedUserMessageId: null,\n hasStreamStarted: false,\n queuedFailed: false,\n abortController,\n isStopped: () => stoppedStreamRef.current === abortController,\n queueOwnerAssistantId: options?.queueOwnerAssistantId ?? null,\n queuedClientId: options?.queuedClientId ?? null,\n // Set when a create_fact / label_facts tool runs this turn, so the Facts\n // table + label vocabulary refresh on completion (see handleComplete).\n factsTouched: false,\n threadDocumentId,\n // Set by the handlers: the server stored the question / reported its own failure.\n userMessageId: null,\n serverError: null,\n }\n\n // A follow-up sent for another conversation than the one on screen places itself under its own\n // parent, not under the screen's cursor.\n const handlers = createHandlers({\n streamState,\n parentMessageId: target ? (parentId ?? null) : parentMessageId,\n parentId,\n })\n // The server's word on the turn's workspace binds the conversation to it.\n const confirmTurnWorkspace = () => {\n if (streamState.workspaceId)\n confirmConversationWorkspace(\n queryClient,\n streamState.conversationId,\n streamState.workspaceId\n )\n }\n const onUserMessageInWorkspace = handlers.onUserMessage\n handlers.onUserMessage = (message) => {\n onUserMessageInWorkspace(message)\n confirmTurnWorkspace()\n }\n if (agentExtId) {\n const onUserMessage = handlers.onUserMessage\n handlers.onUserMessage = (message) => {\n if (message.conversation_ext_id) {\n session.setAgentChatOwner(message.conversation_ext_id, agentExtId)\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.agentChats(agentExtId) })\n }\n onUserMessage(message)\n }\n }\n\n const ownsActiveGeneration = () => {\n const activeGeneration = session.getState().generating[streamState.conversationId]\n return (\n activeGeneration?.abortController === abortController ||\n (!!streamState.assistantId &&\n activeGeneration?.streamingAssistantId === streamState.assistantId)\n )\n }\n\n try {\n performance.mark('arbi:send-message:start')\n await arbi.assistant.ask(request, {\n signal: abortController.signal,\n onMessageQueued: handlers.onMessageQueued,\n onUserMessage: handlers.onUserMessage,\n onStreamStart: handlers.onStreamStart,\n onToken: handlers.onToken,\n onMetadata: handlers.onMetadata,\n onError: handlers.onError,\n onComplete: handlers.onComplete,\n // `response.output_item.added` is deliberately NOT consumed: an item\n // opening told us only that SOME block had started, which is exactly the\n // guess this design gave up. Text arrives via onOutputTextDelta and\n // settles via onOutputItemDone.\n onOutputItemDone: handlers.onOutputItemDone,\n onOutputTextDelta: handlers.onOutputTextDelta,\n onUserInputRequest: handlers.onUserInputRequest,\n onProbeAnswer: handlers.onProbeAnswer,\n onDeferredInterjection: handlers.onDeferredInterjection,\n onAgentControlState: handlers.onAgentControlState,\n onArtifact: handlers.onArtifact,\n onMailDraft: handlers.onMailDraft,\n onElapsedTime: handlers.onElapsedTime,\n onContextUpdate: handlers.onContextUpdate,\n onQuotaExceeded: (quota) => chatHost?.onQuotaExceeded?.(quota),\n onWorkspace: (workspaceId) => {\n streamState.workspaceId = workspaceId\n confirmTurnWorkspace()\n },\n })\n // The stream is over: commit the text still waiting for a frame now, while the message is\n // the streamed one. Left buffered, it lands after the thread is re-read and is appended\n // to the answer the server stored.\n flushStreamingTokens(queryClient)\n\n // A steering response has no assistant stream of its own. The backend\n // accepted the queued user message into the active tool loop. Keep it\n // visibly queued until the parent stream emits its interjection step at\n // the actual tool boundary; that event settles the cache entry.\n if (queuedContinuation && !streamState.hasStreamStarted) {\n if (streamState.queuedFailed) failQueuedContinuation(queryClient, session, streamState)\n return\n }\n\n // The server refused the turn before storing anything (a parent that is gone, a model\n // that is down): say the send failed and offer Retry with the question, instead of letting\n // it vanish with nothing in the thread. Re-read the thread in case the server did store it.\n if (\n streamState.serverError &&\n !streamState.userMessageId &&\n !streamState.assistantId &&\n !queuedContinuation\n ) {\n if (ownsActiveGeneration()) {\n session.setConversationError(\n streamState.conversationId,\n streamState.serverError,\n content\n )\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n // Undo the optimistic 'in_progress' set when the send started.\n void invalidateConversationLists(queryClient)\n }\n return\n }\n\n const ownsGeneration = ownsActiveGeneration()\n if (ownsGeneration) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n }\n\n // The user's own generation just consumed AI usage \u2014 refresh the\n // \"\u00A3 used today\" indicator now instead of polling for it.\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.userUsageToday() })\n\n // Steering that reached the agent too late to steer this turn was\n // deferred by the backend rather than allowed to derail the answer.\n // Now that the turn is done, submit it as a new turn \u2014 threaded off the\n // assistant message that just finished, exactly as if the user had sent\n // it a moment later. Sent as one turn so a burst reads as a single\n // follow-up. Fire-and-forget via the ref so we don't block this turn's\n // completion bookkeeping (and to sidestep the self-reference).\n if (streamState.deferredInterjections.length > 0) {\n const followUp = streamState.deferredInterjections.join('\\n\\n')\n const threadParent = streamState.assistantId\n if (threadParent) {\n session.clearQueuedMessages(threadParent)\n }\n // In the conversation and workspace of the turn it steered, captured now: the view (or\n // the surface's workspace) may have moved on while the turn ran.\n void sendMessageRef.current?.(\n followUp,\n threadParent,\n streamState.workspaceId && streamState.conversationId !== 'new'\n ? {\n target: {\n workspaceId: streamState.workspaceId,\n conversationId: streamState.conversationId,\n },\n }\n : undefined\n )\n }\n\n // The conversations list cache is patched to 'in_progress' on stream\n // start (see the stream handlers). Patch it back to 'completed' here\n // so the Status column / sidebar reflect reality without a refetch.\n if (ownsGeneration) {\n const lastStatus = streamState.serverError ? 'failed' : 'completed'\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: lastStatus,\n })\n }\n\n // A new conversation changes the workspace's conversation_count \u2014 refresh\n // the workspaces list so onboarding's \"Ask ARBI\" step ticks reactively.\n if (isNewConversation && ownsGeneration) invalidateUserWorkspaces()\n\n if (ownsGeneration) {\n clearLoadingState(queryClient, streamState.conversationId)\n }\n } catch (error) {\n flushStreamingTokens(queryClient)\n const isAbort = error instanceof Error && error.name === 'AbortError'\n // The server stored the turn and only the connection dropped: the run is not over.\n const isDroppedConnection = !streamState.serverError && !isAbort && !streamState.isStopped()\n if (queuedContinuation && !streamState.hasStreamStarted) {\n // The server holds this follow-up in its queue already, and runs it in turn.\n if (isDroppedConnection && streamState.queuedUserMessageId) {\n if (streamState.queuedClientId) {\n session.removeQueuedMessage(streamState.queuedClientId)\n }\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n return\n }\n failQueuedContinuation(queryClient, session, streamState)\n return\n }\n\n if (streamState.isStopped() || isAbort) {\n console.debug('Message sending was aborted by user')\n // The stopped stream leaves its assistant message loading with no stream behind it, and\n // a queued follow-up is not the owner so nothing else clears it. Clear it and re-read the\n // thread: a follow-up the server still runs is attached again, a stopped one shows its end.\n clearLoadingState(queryClient, streamState.conversationId)\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n if (ownsActiveGeneration()) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: 'completed',\n })\n }\n return\n }\n\n console.error('Message sending failed:', error)\n if (!ownsActiveGeneration()) return\n\n // A dropped connection after the server stored the question does not end the turn: the\n // run goes on there. Failing it here offered Retry, which deleted the question under the\n // live answer (its answer then landed in the thread with no question) and, if the resend\n // failed too, left the view on the deleted turn. Re-read the thread instead: a running\n // answer is attached again, a failed one shows Retry, a finished one shows its answer.\n // Generation is held until the thread is re-read (or a few seconds pass, offline), so no\n // \"Response Incomplete\" alert offers to delete the question meanwhile.\n if (isDroppedConnection && streamState.userMessageId) {\n let timer: ReturnType<typeof setTimeout> | undefined\n await Promise.race([\n queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n }),\n new Promise((resolve) => {\n timer = setTimeout(resolve, RECONCILE_TIMEOUT_MS)\n }),\n ])\n clearTimeout(timer)\n clearLoadingState(queryClient, streamState.conversationId)\n if (ownsActiveGeneration()) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n }\n void invalidateConversationLists(queryClient)\n return\n }\n\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: 'failed',\n })\n\n // Open the upgrade modal if either (a) the error string carries\n // LiteLLM's ExceededBudget payload directly, or (b) the project's\n // cached AI usage is used up. Either path beats showing only\n // the conversation's generic error.\n const quota =\n quotaFromStreamError(error) ??\n cachedQuotaUsedUp(queryClient, session.getState().workspaceId)\n if (quota) chatHost?.onQuotaExceeded?.(quota)\n\n session.setConversationError(\n streamState.conversationId,\n error instanceof Error ? error.message : String(error),\n content\n )\n }\n },\n [\n selectedWorkspaceId,\n parentMessageId,\n queryClient,\n session,\n createHandlers,\n chatHost,\n arbi,\n invalidateUserWorkspaces,\n routeMessage,\n postComment,\n ]\n )\n\n // Keep the ref pointing at the latest sendMessage so the deferred-interjection\n // resubmit inside sendMessage always calls the current closure.\n sendMessageRef.current = sendMessage\n\n const handleCreateBranch = useCallback(\n async (parentMessageExtId: string | null, newContent: string) => {\n if (!newContent.trim() || !selectedWorkspaceId) return\n await sendMessage(newContent, parentMessageExtId, { branch: true })\n },\n [selectedWorkspaceId, sendMessage]\n )\n\n const handleSendMessage = useCallback(\n async (options?: SendMessageOptions) => {\n const currentMessage = selectDraft(session.getState()).trim()\n // The draft a shared thread starts with (`@<assistant> `) is not a question yet.\n if (!selectedWorkspaceId || !hasMessageBody(currentMessage, assistantLabels(assistantName)))\n return\n\n // A send consumes the suggested follow-up, whether or not it was used \u2014\n // the next turn's metadata brings a fresh one.\n session.setSuggestedQuery(null)\n\n // Chat runs against the server-side AI \u2014 there's nothing to queue offline.\n // Don't fire a mutation that would just pause and hang; tell the user.\n if (refuseChatWhenOffline()) return\n\n // While a turn is active, only true out-of-band controls use /interject.\n // Ordinary text still goes through the typed query endpoint, whose\n // arbi.message_queued event persists and renders it before the response gate\n // opens. The backend then either steers it into the next tool boundary or\n // starts a normal follow-up turn after the current final answer completes.\n if (isGenerating) {\n const convKey = session.getState().conversationId || 'new'\n const genState = session.getState().generating[convKey]\n const streamingAssistantId = genState?.streamingAssistantId\n\n // In a thread, a message that does not @mention the assistant is a comment between\n // people: post it straight away instead of queueing it into the running turn.\n const route = routeMessage(currentMessage)\n if (route.isComment && streamingAssistantId) {\n session.setDraft(draftAfterSend(queryClient, session, route.isComment, assistantName))\n await postComment(currentMessage, streamingAssistantId, route.mentions)\n return\n }\n\n if (streamingAssistantId) {\n const command = currentMessage.toLowerCase()\n const isPause = command === AGENT_CONTROL_COMMANDS.pause\n const isResume = command === AGENT_CONTROL_COMMANDS.resume\n const isReport =\n command === AGENT_CONTROL_COMMANDS.report ||\n command.startsWith(`${AGENT_CONTROL_COMMANDS.report} `)\n\n session.setDraft(draftAfterSend(queryClient, session, route.isComment, assistantName))\n\n if (isPause) {\n session.setAgentControlState(streamingAssistantId, 'pausing')\n } else if (isResume) {\n session.setAgentControlState(streamingAssistantId, 'resuming')\n } else if (isReport) {\n session.setAgentProbePending(streamingAssistantId, true)\n }\n\n if (isPause || isResume || isReport) {\n await arbi.assistant.interject(streamingAssistantId, currentMessage)\n } else {\n const queuedClientId = `queued-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`\n session.addQueuedMessage(streamingAssistantId, {\n clientId: queuedClientId,\n content: currentMessage,\n serverId: null,\n acknowledged: false,\n createdAt: Date.now(),\n })\n await sendMessage(currentMessage, streamingAssistantId, {\n ...options,\n queuedContinuation: true,\n queueOwnerAssistantId: streamingAssistantId,\n queuedClientId,\n })\n }\n return\n }\n // Keep the draft intact during the brief pre-stream window.\n return\n }\n\n const parentId = session.getState().cursor\n\n session.setDraft(\n draftAfterSend(queryClient, session, routeMessage(currentMessage).isComment, assistantName)\n )\n\n await sendMessage(currentMessage, parentId, options)\n },\n [\n selectedWorkspaceId,\n isGenerating,\n session,\n sendMessage,\n arbi,\n routeMessage,\n postComment,\n queryClient,\n assistantName,\n ]\n )\n\n const handleAbortGeneration = useCallback(async () => {\n // A second press (a double-click) must not stop the run again: it would cancel twice, and\n // once the local abort has landed it would clear the stopped-stream marker, so the stream's\n // error would read as a failed answer.\n const stream = session.getState().generating[conversationKey]\n if (stopInFlightRef.current || stream?.isGenerating === false) return\n // A tap right after a Stop must not stop the follow-up the queue started in the meantime.\n if (Date.now() - lastStopAtRef.current < STOP_REPEAT_WINDOW_MS) return\n lastStopAtRef.current = Date.now()\n stopInFlightRef.current = true\n try {\n // Stop the run on the server first; closing the stream alone leaves it running and\n // its answer would arrive later.\n const controller = stream?.abortController ?? null\n stoppedStreamRef.current = controller\n let streamKey = conversationKey\n let responseId = stream?.streamingAssistantId ?? null\n // Pressed before the stream reported its id: the run already exists on the server, so wait\n // for the id instead of only closing the stream. Further presses meanwhile do nothing.\n if (!responseId && controller) {\n const reported = await waitForResponseId(session, controller)\n if (reported) {\n streamKey = reported.conversationKey\n responseId = reported.responseId\n }\n }\n // In a sub-agent's branch this is the run that delegated it.\n const threads =\n queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(streamKey))?.threads ?? []\n const runId = responseId ? getRunToCancel(threads, responseId) : null\n if (runId) {\n try {\n await arbi.assistant.cancel(runId)\n } catch {\n // Still stop here (the run may already have ended); say the server may keep going.\n notify.warning(\n \"Stopped here, but the server didn't confirm: the answer may still appear later.\"\n )\n }\n }\n // The cancel is awaited, and the server starts the next queued follow-up as soon as it lands:\n // that follow-up may already own this conversation's generation state and attach. Only close\n // the stream this Stop belongs to, or the next answer goes silent (\"Working\", no stop square).\n const current = session.getState().generating[streamKey]\n const isStoppedStream = controller\n ? current?.abortController === controller\n : !current?.streamingAssistantId || current.streamingAssistantId === responseId\n if (isStoppedStream) session.abortConversationGeneration(streamKey)\n // A reattached run has no local controller: close its stream too, or it keeps painting. The\n // attach follows this conversation's streaming message (in a sub-agent branch, the branch's\n // reply), not the delegating run that was cancelled, so match it by that id.\n if (responseId) disconnectAttachedRun(streamKey, responseId)\n } finally {\n stopInFlightRef.current = false\n }\n }, [session, arbi, conversationKey, queryClient])\n\n const handleRetryOrphanedMessage = useCallback(\n async (messageContent: string, parentId: string | null, messageExtId: string) => {\n // One retry at a time: the alert's Retry and the composer's retry (or a double click) must\n // not delete and resend twice. Released however the retry ends.\n if (retryInFlightRef.current) return\n // Offline the delete would be paused and the resend refused, leaving neither done.\n if (refuseChatWhenOffline()) return\n retryInFlightRef.current = true\n try {\n // A failed parent (a follow-up the restart sweep failed behind a failed answer) is\n // refused by the server, so the resend goes to the nearest message above it instead.\n const replyTo = currentConversationId\n ? resolveReplyTarget(queryClient, currentConversationId, parentId)\n : parentId\n if (!replyTo && currentConversationId) {\n try {\n await arbi.conversations.delete(currentConversationId)\n removeConversationFromLists(queryClient, currentConversationId)\n session.startNewConversation()\n } catch (error) {\n console.error('Failed to delete conversation with orphaned first message:', error)\n }\n } else if (replyTo) {\n try {\n await arbi.conversations.deleteMessage(messageExtId)\n // The message and its replies are gone from whichever thread held them.\n void queryClient.invalidateQueries(allConversationThreads)\n } catch (error) {\n console.error('Failed to delete orphaned message:', error)\n }\n }\n\n await sendMessage(messageContent, replyTo)\n } finally {\n retryInFlightRef.current = false\n }\n },\n [currentConversationId, arbi, session, sendMessage, queryClient]\n )\n\n const handleRetrySend = useCallback(async () => {\n if (isGenerating || !lastFailedMessage || retryInFlightRef.current) return\n if (refuseChatWhenOffline()) return\n retryInFlightRef.current = true\n try {\n session.clearConversationError(conversationKey)\n // sendMessage replies to the nearest message the server accepts: the view may still point at\n // a turn a Retry deleted, or at a failed answer.\n const parentId = session.getState().cursor\n await sendMessage(lastFailedMessage, parentId)\n } finally {\n retryInFlightRef.current = false\n }\n }, [isGenerating, lastFailedMessage, session, conversationKey, sendMessage])\n\n const clearErrorState = useCallback(() => {\n session.clearConversationError(conversationKey)\n }, [session, conversationKey])\n\n // Clear error state when starting a new conversation\n useEffect(() => {\n if (currentConversationId === null) {\n session.clearConversationError('new')\n }\n }, [currentConversationId, session])\n\n return {\n handleCreateBranch,\n handleSendMessage,\n handleAbortGeneration,\n handleRetrySend,\n handleRetryOrphanedMessage,\n clearErrorState,\n }\n}\n"],
|
|
5
|
-
"mappings": "AAOA,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD,SAAS,sBAAwC;AACjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK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7B;AAAA,EACF,GAAG,CAAC,cAAc,mBAAmB,SAAS,iBAAiB,WAAW,CAAC;AAE3E,QAAM,kBAAkB,YAAY,MAAM;AACxC,YAAQ,uBAAuB,eAAe;AAAA,EAChD,GAAG,CAAC,SAAS,eAAe,CAAC;AAG7B,YAAU,MAAM;AACd,QAAI,0BAA0B,MAAM;AAClC,cAAQ,uBAAuB,KAAK;AAAA,IACtC;AAAA,EACF,GAAG,CAAC,uBAAuB,OAAO,CAAC;AAEnC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["/**\n * The chat engine's actions on a conversation: send (a turn, or a comment to the people in a\n * thread), branch, retry, stop, and the run-control commands typed while a turn runs. A turn goes\n * through `arbi.assistant.ask`, its frames through the stream handlers, and its state lives in the\n * session (`ArbiSessionState`) and the conversation cache.\n */\n\nimport { flushDocumentForTurn } from './turn-flush'\nimport { pendingChatModelSave } from '../config/config-hooks'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { useQueryClient, type QueryClient } from '@tanstack/react-query'\nimport {\n ArbiApiError,\n STOP_REPEAT_WINDOW_MS,\n getRunToCancel,\n quotaFromStreamError,\n type ConversationResponse as Conversation,\n type ThreadsResponse,\n} from '@arbidocs/sdk/browser'\nimport type { components } from '@arbidocs/client'\nimport { notify } from '../shell'\nimport { arbiQueryKeys } from '../hooks'\nimport { useArbi } from '../useArbi'\nimport { requestAgentStatus } from './request-agent-status'\nimport { useArbiHost } from '../host/config'\nimport { selectDraft, useArbiSessionStore } from '../session'\nimport type { ArbiSessionStore } from '../session/store'\nimport {\n invalidateConversationLists,\n isConversationShared,\n patchConversation,\n patchConversationList,\n removeConversationFromLists,\n} from '../conversation-list'\nimport {\n allConversationThreads,\n clearLoadingState,\n flushStreamingTokens,\n getThreadsQueryKey,\n isConversationEmpty,\n updateUserMessageStateInCache,\n} from './conversation-cache'\nimport {\n assistantLabels,\n cachedAssistantMode,\n cachedMentionCandidates,\n isCommentToPeople,\n} from './conversation-mentions'\nimport { useAssistantName } from '../host/assistant-copy'\nimport { hasMessageBody, toMessageMentions, extractMentions } from './mentions'\nimport { takeDocumentForTurn } from './open-document'\nimport { agentChatOwnerOf, creatorOf } from './agent-chat-owner'\nimport { bindThreadDocument, boundDocumentOf } from './thread-binding'\nimport { resolveReplyTarget } from './reply-target'\nimport {\n confirmConversationWorkspace,\n conversationWorkspaceOf,\n watchConversationWorkspaces,\n} from './conversation-workspace'\nimport { useStreamHandlers, type StreamState } from './stream-handlers'\nimport {\n AGENT_CONTROL_COMMANDS,\n cachedQuotaUsedUp,\n disconnectAttachedRun,\n refuseChatWhenOffline,\n waitForResponseId,\n} from './turn-control'\n\ntype MessageInput = components['schemas']['MessageInput']\ntype MessageMention = components['schemas']['MessageMention']\n\n/** How long a dropped turn holds its generating state while the thread is re-read. */\nconst RECONCILE_TIMEOUT_MS = 5000\n\nexport interface SendMessageOptions {\n /** An explicit edit/fork, rather than appending a human message to the shared thread. */\n branch?: boolean\n queuedContinuation?: boolean\n queueOwnerAssistantId?: string\n queuedClientId?: string\n /**\n * Bypasses the normal single-pinned-document tools computation (the chat's documents and its\n * pin, see `buildTurnRequest`) for this one send.\n * The app's general \"pin a document\" feature is deliberately one-at-a-time\n * (`selectFullContextDocument`) \u2014 a pinned TEXT doc's full content goes\n * straight into the AGENT's chat prompt, so more than one at a time risks\n * blowing that context window. Generate image is a different resource\n * entirely: reference images never touch the agent's chat context \u2014 they go\n * to the separate ImageGen model in its own request \u2014 so multiple\n * references (e.g. \"combine these two logos\") don't compound against that\n * budget, even though they still cost real tokens against ImageGen's own\n * call. This lets that caller build its own tools object with every\n * selected reference doc instead of touching the single global pin.\n */\n toolsOverride?: MessageInput['tools']\n /**\n * Send in this conversation and workspace rather than the open ones: a follow-up captured when\n * its turn started (a deferred interjection), sent after the view may have moved on.\n */\n target?: TurnTarget\n}\n\n/** The conversation and workspace a turn belongs to, captured when it starts. */\nexport interface TurnTarget {\n workspaceId: string\n conversationId: string\n}\n\n/**\n * The draft a send leaves behind. A shared chat addresses ARBI again, except after a comment to\n * people: then the box is left empty, which a shared chat reads as a comment to the thread.\n */\nfunction draftAfterSend(\n queryClient: QueryClient,\n session: ArbiSessionStore,\n wasComment: boolean,\n assistantName: string\n): string {\n const shared = isConversationShared(queryClient, session.getState().conversationId)\n return shared && !wasComment ? `@${assistantName} ` : ''\n}\n\n/**\n * A queued follow-up the backend refused before its turn started: mark its bubble failed and\n * take it out of the queue, so it does not sit there as if it were still waiting.\n */\nfunction failQueuedContinuation(\n queryClient: QueryClient,\n session: ArbiSessionStore,\n streamState: {\n conversationId: string\n queuedUserMessageId: string | null\n queueOwnerAssistantId: string | null\n queuedClientId: string | null\n }\n): void {\n if (streamState.queuedUserMessageId) {\n updateUserMessageStateInCache(\n queryClient,\n streamState.conversationId,\n streamState.queuedUserMessageId,\n 'failed',\n false\n )\n }\n if (streamState.queuedClientId) {\n session.removeQueuedMessage(streamState.queuedClientId)\n }\n notify.error('Queued message failed to send')\n}\n\n/** The signed-in user's id, or null before the session is known. */\nfunction signedInUserId(arbi: { user: { identity: () => { externalId: string } | null } }) {\n try {\n return arbi.user.identity()?.externalId ?? null\n } catch {\n return null\n }\n}\n\n/** What the actions act on: the open workspace and conversation, as the session holds them. */\nexport interface ConversationActionsInput {\n selectedWorkspaceId: string | null\n /** The cursor when the view rendered (the stream handlers place a branch against it). */\n parentMessageId: string | null\n /** The open conversation's key (`new` for a new chat). */\n conversationKey: string\n isGenerating: boolean\n lastFailedMessage: string | null\n}\n\n/** The actions on the open conversation. */\nexport function useConversationActions({\n selectedWorkspaceId,\n parentMessageId,\n conversationKey,\n isGenerating,\n lastFailedMessage,\n}: ConversationActionsInput) {\n const queryClient = useQueryClient()\n const session = useArbiSessionStore()\n const currentConversationId = conversationKey === 'new' ? null : conversationKey\n const invalidateUserWorkspaces = useCallback(\n () => void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() }),\n [queryClient]\n )\n\n const arbi = useArbi()\n // Each conversation stays in the workspace it was opened in, though the surface switches.\n useState(() => watchConversationWorkspaces(queryClient, session))\n const createHandlers = useStreamHandlers()\n const chatHost = useArbiHost().chat\n const assistantName = useAssistantName()\n const mentionCandidates = useCallback(\n () =>\n cachedMentionCandidates(\n queryClient,\n session.getState().workspaceId,\n signedInUserId(arbi),\n assistantName\n ),\n [queryClient, session, arbi, assistantName]\n )\n // The local stream a Stop is closing. Stop cancels the run on the server before it aborts the\n // stream, so the connection can drop first with a network error that is not an abort.\n const stoppedStreamRef = useRef<AbortController | null>(null)\n // True while a Stop's server cancel is in flight, so a second press does not cancel again.\n const stopInFlightRef = useRef(false)\n // When the last Stop was pressed. A press within STOP_REPEAT_WINDOW_MS of it is a double tap.\n const lastStopAtRef = useRef(0)\n // True while a Retry deletes and resends, so a second press does not do it again.\n const retryInFlightRef = useRef(false)\n // Lets sendMessage resubmit a deferred interjection as a new turn without a\n // self-reference (it is a useCallback that would otherwise close over a stale\n // or not-yet-defined copy of itself). Kept current just below its definition.\n const sendMessageRef = useRef<\n | ((content: string, parentId?: string | null, options?: SendMessageOptions) => Promise<void>)\n | null\n >(null)\n\n /**\n * Shared posts, and posts in a `mentioned` thread, run ARBI only when addressed; posts in an\n * ordinary solo chat address it implicitly.\n */\n const routeMessage = useCallback(\n (content: string, conversationId?: string | null) => {\n const state = session.getState()\n const convId = conversationId === undefined ? state.conversationId : conversationId\n const { newConversationAssistantMode } = state\n const candidates = mentionCandidates()\n const mentioned = extractMentions(content, candidates)\n const assistantMode = cachedAssistantMode(queryClient, convId, newConversationAssistantMode)\n const isComment = isCommentToPeople(queryClient, convId, content, candidates)\n const mentions = toMessageMentions(mentioned) as MessageMention[]\n // A message not taken as a comment addresses ARBI. In an existing `mentioned` thread that is\n // only one that @mentions it; what is left is the first message of a thread not created\n // yet, whose turn creates it in `mentioned` mode.\n if (\n !isComment &&\n assistantMode === 'mentioned' &&\n !mentions.some((m) => m.type === 'assistant')\n ) {\n mentions.push({ type: 'assistant' })\n }\n return {\n mentions,\n assistantMode,\n isComment,\n }\n },\n [queryClient, session, mentionCandidates]\n )\n\n /** Post a comment (no assistant run) and land the thread on it. */\n const postComment = useCallback(\n async (\n content: string,\n parentId: string | null,\n mentions: MessageMention[],\n branch = false\n ) => {\n const convId = session.getState().conversationId\n try {\n const saved = await arbi.conversations.postMessage({\n content,\n mentions,\n // Only an explicit edit creates a branch. Ordinary comments append to the\n // server's latest message, so simultaneous sends stay visible together. Else\n // (nothing yet) start a thread. The mode only applies to a conversation it creates.\n ...(branch && parentId\n ? { previous_message_ext_id: parentId }\n : convId\n ? { conversation_ext_id: convId }\n : {}),\n assistant_mode: 'mentioned',\n })\n const conversationId = saved.conversation_ext_id\n const nowIso = new Date().toISOString()\n if (!convId) {\n // A comment starts the thread without a turn to carry its binding: bind it right after.\n const bindTo = session.getState().newChatDocumentId\n session.moveConversation('new', conversationId)\n if (bindTo) session.setNewChatDocumentId(null)\n patchConversationList(queryClient, session.getState().workspaceId, (old) => [\n {\n external_id: conversationId,\n title: content.slice(0, 40),\n created_by_ext_id: saved.created_by_ext_id,\n updated_by_ext_id: null,\n created_at: nowIso,\n updated_at: nowIso,\n // A mention of someone who cannot see it yet shares it server-side: refetched below.\n is_shared: false,\n message_count: 1,\n last_message_status: 'completed',\n assistant_mode: 'mentioned',\n } as Conversation,\n ...old,\n ])\n if (bindTo)\n bindThreadDocument(arbi, queryClient, conversationId, bindTo).catch(() =>\n notify.error('Could not attach the document to this thread')\n )\n invalidateUserWorkspaces()\n } else {\n patchConversation(queryClient, conversationId, (c) => ({\n ...c,\n message_count: c.message_count + 1,\n updated_at: nowIso,\n }))\n }\n // Mentioning someone shares the conversation on the server, which this cache cannot know.\n if (mentions.some((m) => m.type === 'user')) {\n await invalidateConversationLists(queryClient)\n }\n await queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n session.setCursor(saved.external_id)\n } catch (error) {\n notify.error(\n (error instanceof ArbiApiError && error.detail) || 'Failed to post the message'\n )\n // Give the text back rather than lose it.\n if (!selectDraft(session.getState())) session.setDraft(content)\n }\n },\n [arbi, session, queryClient, invalidateUserWorkspaces]\n )\n\n const sendMessage = useCallback(\n async (content: string, requestedParentId?: string | null, options?: SendMessageOptions) => {\n // Never reply to a failed or deleted message: the server refuses it, so every Retry and every\n // new message would fail again. A queued follow-up names the running turn on purpose. With\n // nothing above to reply to, the parent stays: only a fresh conversation could take it.\n const target = options?.target\n const parentId =\n options?.queuedContinuation || !requestedParentId\n ? requestedParentId\n : (resolveReplyTarget(\n queryClient,\n (target ? target.conversationId : session.getState().conversationId) || 'new',\n requestedParentId\n ) ?? requestedParentId)\n const route = routeMessage(content, target?.conversationId)\n if (route.isComment && !options?.queuedContinuation && !target) {\n await postComment(content, parentId ?? null, route.mentions, options?.branch)\n return\n }\n // A model picked just now is still being saved: the turn runs on it, not on the config before.\n const modelSave = pendingChatModelSave(session)\n if (modelSave) await modelSave.catch(() => undefined)\n const state = session.getState()\n const convId = target ? target.conversationId : state.conversationId\n const convKey = convId || 'new'\n // The turn's workspace, captured now: the conversation's own (a docked or scoped chat keeps\n // its conversation across a switch), else the surface's for a new conversation. Named on the\n // request, so neither a switch nor the session's open workspace can move it.\n const turnWorkspaceId =\n target?.workspaceId ?? conversationWorkspaceOf(queryClient, convId) ?? selectedWorkspaceId\n const agentChat = state.newAgentChat\n // An existing conversation's agent: as recorded, else its creator when that is one of the\n // person's own agents (an agent chat runs under the agent's session; the record does not\n // survive a sign-out, or another device).\n let agentExtId = convId\n ? state.agentChatOwners[convId]\n : agentChat?.workspaceId === turnWorkspaceId\n ? agentChat.agentId\n : undefined\n // Only a conversation an agent created is looked up (an ordinary send never waits on it).\n if (convId && !agentExtId && creatorOf(queryClient, convId)?.startsWith('agt-')) {\n agentExtId = await agentChatOwnerOf(queryClient, () => arbi.agents.list(), convId)\n if (agentExtId) session.setAgentChatOwner(convId, agentExtId)\n }\n const queuedContinuation = options?.queuedContinuation === true\n // First message of a brand-new conversation bumps the workspace's\n // conversation_count \u2014 used to tick the \"Ask ARBI\" onboarding step.\n const isNewConversation = !convId\n\n const documentIds = (state.conversationDocuments[convKey] || []).map((doc) => doc.docId)\n // The chat's facts ride every message of it (snapshot semantics, like its documents).\n const factIds = [...(state.conversationFacts[convKey] || [])]\n\n const newConfigId = state.chatModel\n\n // Frontend is the single source of truth for which config a request\n // uses (Option B): send the same config the model selector resolves &\n // displays (see useConversationSettings) \u2014 explicit per-conversation\n // choice (`newConfigId`) wins, otherwise the user's persisted\n // `last_config`, so a selected config (e.g. one with ARTIFACTS_ENABLED)\n // actually drives the chat instead of being silently dropped to an\n // empty config. `newConfigId` alone is insufficient \u2014 it is transient\n // and cleared on every new conversation. Read `last_config` from the\n // shared settings cache by partial key match: openapi-react-query\n // suffixes the query key with request options and the settings hook is\n // token-gated, so the hook value can momentarily be undefined here even\n // though the data is cached app-wide.\n const cachedSettings = queryClient\n .getQueriesData<{ last_config?: string }>({ queryKey: arbiQueryKeys.userSettings() })\n .map(([, data]) => data)\n .find((data) => data?.last_config)\n const lastConfigId = cachedSettings?.last_config\n const resolvedConfigId = newConfigId || (agentExtId ? undefined : lastConfigId)\n\n // PA mode delegates the turn to the personal agent (`buildTurnRequest` prefixes `/pa ` so\n // the backend routes it straight to the delegation stream).\n const isPaMode = !agentExtId && state.paMode\n\n // Drafting mode: the thread's own document is named (a reference, never its content): the one\n // the thread is bound to (started from it, or attached in it), else one made in this thread\n // and open. A document merely open beside a chat is not: a new chat starts unbound. While an\n // earlier version of it is on screen the viewer returns to the live document. For a Word\n // document the server binds the live document: the assistant reads what it needs on demand\n // and edits it as tracked changes. For an html/react artifact it gets the source and a\n // targeted edit tool. PA-mode turns are delegated to a separate agent and never touch\n // artifacts.\n const threadDocumentId = boundDocumentOf(queryClient, { ...state, conversationId: convId })\n const activeArtifactExtId = isPaMode\n ? null\n : takeDocumentForTurn({\n boundDocumentId: threadDocumentId,\n conversationId: convId,\n workspaceId: turnWorkspaceId,\n })\n\n // An editor holding unsaved changes to that document saves them first: ARBI works on what\n // the person sees.\n const flushing = flushDocumentForTurn(activeArtifactExtId)\n if (flushing) await flushing\n\n // A workflow launch can leave structured tools for its one send; consume them here.\n const pendingTools = state.pendingTools\n if (pendingTools) session.setPendingTools(null)\n const toolsOverride = options?.toolsOverride ?? pendingTools ?? undefined\n\n const request = {\n question: content,\n workspaceId: turnWorkspaceId!,\n docIds: documentIds,\n pinnedDocumentId: state.pinnedDocumentId,\n factIds,\n tools: toolsOverride,\n personalAgent: isPaMode,\n activeArtifactExtId,\n // A new chat about a document is bound by its first turn, on the server (every device).\n ...(!convId && threadDocumentId ? { bindDocumentId: threadDocumentId } : {}),\n previousResponseId: parentId,\n // The first turn of an existing conversation with no message yet (a task's thread) runs in\n // it: without its id the server starts a new conversation for the turn.\n ...(convId && !parentId && !options?.branch && isConversationEmpty(queryClient, convId)\n ? { conversationId: convId }\n : {}),\n agentId: agentExtId,\n model: resolvedConfigId,\n mentions: route.mentions,\n // A brand-new conversation starts in the mode picked in the composer.\n ...(!convId && route.assistantMode === 'mentioned'\n ? { assistantMode: 'mentioned' as const }\n : {}),\n }\n\n const abortController = new AbortController()\n if (!queuedContinuation) {\n session.setConversationGenerating(convKey, true, abortController)\n }\n\n // Optimistically mark this conversation in-progress the instant we start a\n // turn. Without this, Conversation's \"reconcile stale isGenerating\" effect\n // runs on the setConversationGenerating(true) above, sees the conversation\n // list's last_message_status still 'completed' from the PREVIOUS turn (the\n // stream_start patch below only lands ~50ms later), and immediately clears\n // isGenerating \u2014 which race-hid the live status bar on every follow-up\n // turn (first turns were exempt: the new conversation isn't in the list\n // yet). Patching here closes that window. No-op for a brand-new\n // conversation (convKey === 'new' isn't in the list).\n if (!queuedContinuation) {\n patchConversation(queryClient, convKey, { last_message_status: 'in_progress' })\n }\n\n // Mutable stream state \u2014 shared by all SSE handlers via closure\n const streamState: StreamState = {\n conversationId: convKey,\n workspaceId: turnWorkspaceId,\n assistantId: null,\n // 0 = nothing narrated yet, so nothing is owed a reading window.\n lastNarrationSettledAt: 0,\n // True once the model has pivoted to a tool call and not yet resumed\n // prose. Prose arriving while this is set opens a NEW narration, so the\n // one before it closes: paragraph break, and everything above becomes\n // superseded. Item boundaries alone cannot say this \u2014 the backend splits\n // a single sentence across several items.\n pivotedSinceProse: false,\n // Steering that landed too late to steer this turn; resubmitted as a new\n // turn once this one completes (see after the ask below).\n deferredInterjections: [],\n queuedContinuation,\n queuedUserMessageId: null,\n hasStreamStarted: false,\n queuedFailed: false,\n abortController,\n isStopped: () => stoppedStreamRef.current === abortController,\n queueOwnerAssistantId: options?.queueOwnerAssistantId ?? null,\n queuedClientId: options?.queuedClientId ?? null,\n // Set when a create_fact / label_facts tool runs this turn, so the Facts\n // table + label vocabulary refresh on completion (see handleComplete).\n factsTouched: false,\n threadDocumentId,\n // Set by the handlers: the server stored the question / reported its own failure.\n userMessageId: null,\n serverError: null,\n }\n\n // A follow-up sent for another conversation than the one on screen places itself under its own\n // parent, not under the screen's cursor.\n const handlers = createHandlers({\n streamState,\n parentMessageId: target ? (parentId ?? null) : parentMessageId,\n parentId,\n })\n // The server's word on the turn's workspace binds the conversation to it.\n const confirmTurnWorkspace = () => {\n if (streamState.workspaceId)\n confirmConversationWorkspace(\n queryClient,\n streamState.conversationId,\n streamState.workspaceId\n )\n }\n const onUserMessageInWorkspace = handlers.onUserMessage\n handlers.onUserMessage = (message) => {\n onUserMessageInWorkspace(message)\n confirmTurnWorkspace()\n }\n if (agentExtId) {\n const onUserMessage = handlers.onUserMessage\n handlers.onUserMessage = (message) => {\n if (message.conversation_ext_id) {\n session.setAgentChatOwner(message.conversation_ext_id, agentExtId)\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.agentChats(agentExtId) })\n }\n onUserMessage(message)\n }\n }\n\n const ownsActiveGeneration = () => {\n const activeGeneration = session.getState().generating[streamState.conversationId]\n return (\n activeGeneration?.abortController === abortController ||\n (!!streamState.assistantId &&\n activeGeneration?.streamingAssistantId === streamState.assistantId)\n )\n }\n\n try {\n performance.mark('arbi:send-message:start')\n await arbi.assistant.ask(request, {\n signal: abortController.signal,\n onMessageQueued: handlers.onMessageQueued,\n onUserMessage: handlers.onUserMessage,\n onStreamStart: handlers.onStreamStart,\n onToken: handlers.onToken,\n onMetadata: handlers.onMetadata,\n onError: handlers.onError,\n onComplete: handlers.onComplete,\n // `response.output_item.added` is deliberately NOT consumed: an item\n // opening told us only that SOME block had started, which is exactly the\n // guess this design gave up. Text arrives via onOutputTextDelta and\n // settles via onOutputItemDone.\n onOutputItemDone: handlers.onOutputItemDone,\n onOutputTextDelta: handlers.onOutputTextDelta,\n onUserInputRequest: handlers.onUserInputRequest,\n onProbeAnswer: handlers.onProbeAnswer,\n onDeferredInterjection: handlers.onDeferredInterjection,\n onAgentControlState: handlers.onAgentControlState,\n onArtifact: handlers.onArtifact,\n onMailDraft: handlers.onMailDraft,\n onElapsedTime: handlers.onElapsedTime,\n onContextUpdate: handlers.onContextUpdate,\n onQuotaExceeded: (quota) => chatHost?.onQuotaExceeded?.(quota),\n onWorkspace: (workspaceId) => {\n streamState.workspaceId = workspaceId\n confirmTurnWorkspace()\n },\n })\n // The stream is over: commit the text still waiting for a frame now, while the message is\n // the streamed one. Left buffered, it lands after the thread is re-read and is appended\n // to the answer the server stored.\n flushStreamingTokens(queryClient)\n\n // A steering response has no assistant stream of its own. The backend\n // accepted the queued user message into the active tool loop. Keep it\n // visibly queued until the parent stream emits its interjection step at\n // the actual tool boundary; that event settles the cache entry.\n if (queuedContinuation && !streamState.hasStreamStarted) {\n if (streamState.queuedFailed) failQueuedContinuation(queryClient, session, streamState)\n return\n }\n\n // The server refused the turn before storing anything (a parent that is gone, a model\n // that is down): say the send failed and offer Retry with the question, instead of letting\n // it vanish with nothing in the thread. Re-read the thread in case the server did store it.\n if (\n streamState.serverError &&\n !streamState.userMessageId &&\n !streamState.assistantId &&\n !queuedContinuation\n ) {\n if (ownsActiveGeneration()) {\n session.setConversationError(\n streamState.conversationId,\n streamState.serverError,\n content\n )\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n // Undo the optimistic 'in_progress' set when the send started.\n void invalidateConversationLists(queryClient)\n }\n return\n }\n\n const ownsGeneration = ownsActiveGeneration()\n if (ownsGeneration) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n }\n\n // The user's own generation just consumed AI usage \u2014 refresh the\n // \"\u00A3 used today\" indicator now instead of polling for it.\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.userUsageToday() })\n\n // Steering that reached the agent too late to steer this turn was\n // deferred by the backend rather than allowed to derail the answer.\n // Now that the turn is done, submit it as a new turn \u2014 threaded off the\n // assistant message that just finished, exactly as if the user had sent\n // it a moment later. Sent as one turn so a burst reads as a single\n // follow-up. Fire-and-forget via the ref so we don't block this turn's\n // completion bookkeeping (and to sidestep the self-reference).\n if (streamState.deferredInterjections.length > 0) {\n const followUp = streamState.deferredInterjections.join('\\n\\n')\n const threadParent = streamState.assistantId\n if (threadParent) {\n session.clearQueuedMessages(threadParent)\n }\n // In the conversation and workspace of the turn it steered, captured now: the view (or\n // the surface's workspace) may have moved on while the turn ran.\n void sendMessageRef.current?.(\n followUp,\n threadParent,\n streamState.workspaceId && streamState.conversationId !== 'new'\n ? {\n target: {\n workspaceId: streamState.workspaceId,\n conversationId: streamState.conversationId,\n },\n }\n : undefined\n )\n }\n\n // The conversations list cache is patched to 'in_progress' on stream\n // start (see the stream handlers). Patch it back to 'completed' here\n // so the Status column / sidebar reflect reality without a refetch.\n if (ownsGeneration) {\n const lastStatus = streamState.serverError ? 'failed' : 'completed'\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: lastStatus,\n })\n }\n\n // A new conversation changes the workspace's conversation_count \u2014 refresh\n // the workspaces list so onboarding's \"Ask ARBI\" step ticks reactively.\n if (isNewConversation && ownsGeneration) invalidateUserWorkspaces()\n\n if (ownsGeneration) {\n clearLoadingState(queryClient, streamState.conversationId)\n }\n } catch (error) {\n flushStreamingTokens(queryClient)\n const isAbort = error instanceof Error && error.name === 'AbortError'\n // The server stored the turn and only the connection dropped: the run is not over.\n const isDroppedConnection = !streamState.serverError && !isAbort && !streamState.isStopped()\n if (queuedContinuation && !streamState.hasStreamStarted) {\n // The server holds this follow-up in its queue already, and runs it in turn.\n if (isDroppedConnection && streamState.queuedUserMessageId) {\n if (streamState.queuedClientId) {\n session.removeQueuedMessage(streamState.queuedClientId)\n }\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n return\n }\n failQueuedContinuation(queryClient, session, streamState)\n return\n }\n\n if (streamState.isStopped() || isAbort) {\n console.debug('Message sending was aborted by user')\n // The stopped stream leaves its assistant message loading with no stream behind it, and\n // a queued follow-up is not the owner so nothing else clears it. Clear it and re-read the\n // thread: a follow-up the server still runs is attached again, a stopped one shows its end.\n clearLoadingState(queryClient, streamState.conversationId)\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n if (ownsActiveGeneration()) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: 'completed',\n })\n }\n return\n }\n\n console.error('Message sending failed:', error)\n if (!ownsActiveGeneration()) return\n\n // A dropped connection after the server stored the question does not end the turn: the\n // run goes on there. Failing it here offered Retry, which deleted the question under the\n // live answer (its answer then landed in the thread with no question) and, if the resend\n // failed too, left the view on the deleted turn. Re-read the thread instead: a running\n // answer is attached again, a failed one shows Retry, a finished one shows its answer.\n // Generation is held until the thread is re-read (or a few seconds pass, offline), so no\n // \"Response Incomplete\" alert offers to delete the question meanwhile.\n if (isDroppedConnection && streamState.userMessageId) {\n let timer: ReturnType<typeof setTimeout> | undefined\n await Promise.race([\n queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n }),\n new Promise((resolve) => {\n timer = setTimeout(resolve, RECONCILE_TIMEOUT_MS)\n }),\n ])\n clearTimeout(timer)\n clearLoadingState(queryClient, streamState.conversationId)\n if (ownsActiveGeneration()) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n }\n void invalidateConversationLists(queryClient)\n return\n }\n\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: 'failed',\n })\n\n // Open the upgrade modal if either (a) the error string carries\n // LiteLLM's ExceededBudget payload directly, or (b) the project's\n // cached AI usage is used up. Either path beats showing only\n // the conversation's generic error.\n const quota =\n quotaFromStreamError(error) ??\n cachedQuotaUsedUp(queryClient, session.getState().workspaceId)\n if (quota) chatHost?.onQuotaExceeded?.(quota)\n\n session.setConversationError(\n streamState.conversationId,\n error instanceof Error ? error.message : String(error),\n content\n )\n }\n },\n [\n selectedWorkspaceId,\n parentMessageId,\n queryClient,\n session,\n createHandlers,\n chatHost,\n arbi,\n invalidateUserWorkspaces,\n routeMessage,\n postComment,\n ]\n )\n\n // Keep the ref pointing at the latest sendMessage so the deferred-interjection\n // resubmit inside sendMessage always calls the current closure.\n sendMessageRef.current = sendMessage\n\n const handleCreateBranch = useCallback(\n async (parentMessageExtId: string | null, newContent: string) => {\n if (!newContent.trim() || !selectedWorkspaceId) return\n await sendMessage(newContent, parentMessageExtId, { branch: true })\n },\n [selectedWorkspaceId, sendMessage]\n )\n\n const handleSendMessage = useCallback(\n async (options?: SendMessageOptions) => {\n const currentMessage = selectDraft(session.getState()).trim()\n // The draft a shared thread starts with (`@<assistant> `) is not a question yet.\n if (!selectedWorkspaceId || !hasMessageBody(currentMessage, assistantLabels(assistantName)))\n return\n\n // A send consumes the suggested follow-up, whether or not it was used \u2014\n // the next turn's metadata brings a fresh one.\n session.setSuggestedQuery(null)\n\n // Chat runs against the server-side AI \u2014 there's nothing to queue offline.\n // Don't fire a mutation that would just pause and hang; tell the user.\n if (refuseChatWhenOffline()) return\n\n // While a turn is active, only true out-of-band controls use /interject.\n // Ordinary text still goes through the typed query endpoint, whose\n // arbi.message_queued event persists and renders it before the response gate\n // opens. The backend then either steers it into the next tool boundary or\n // starts a normal follow-up turn after the current final answer completes.\n if (isGenerating) {\n const convKey = session.getState().conversationId || 'new'\n const genState = session.getState().generating[convKey]\n const streamingAssistantId = genState?.streamingAssistantId\n\n // In a thread, a message that does not @mention the assistant is a comment between\n // people: post it straight away instead of queueing it into the running turn.\n const route = routeMessage(currentMessage)\n if (route.isComment && streamingAssistantId) {\n session.setDraft(draftAfterSend(queryClient, session, route.isComment, assistantName))\n await postComment(currentMessage, streamingAssistantId, route.mentions)\n return\n }\n\n if (streamingAssistantId) {\n const command = currentMessage.toLowerCase()\n const isPause = command === AGENT_CONTROL_COMMANDS.pause\n const isResume = command === AGENT_CONTROL_COMMANDS.resume\n const isReport =\n command === AGENT_CONTROL_COMMANDS.report ||\n command.startsWith(`${AGENT_CONTROL_COMMANDS.report} `)\n\n session.setDraft(draftAfterSend(queryClient, session, route.isComment, assistantName))\n\n if (isPause) {\n session.setAgentControlState(streamingAssistantId, 'pausing')\n } else if (isResume) {\n session.setAgentControlState(streamingAssistantId, 'resuming')\n }\n\n if (isReport) {\n await requestAgentStatus(arbi, session, streamingAssistantId, currentMessage)\n } else if (isPause || isResume) {\n await arbi.assistant.interject(streamingAssistantId, currentMessage)\n } else {\n const queuedClientId = `queued-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`\n session.addQueuedMessage(streamingAssistantId, {\n clientId: queuedClientId,\n content: currentMessage,\n serverId: null,\n acknowledged: false,\n createdAt: Date.now(),\n })\n await sendMessage(currentMessage, streamingAssistantId, {\n ...options,\n queuedContinuation: true,\n queueOwnerAssistantId: streamingAssistantId,\n queuedClientId,\n })\n }\n return\n }\n // Keep the draft intact during the brief pre-stream window.\n return\n }\n\n const parentId = session.getState().cursor\n\n session.setDraft(\n draftAfterSend(queryClient, session, routeMessage(currentMessage).isComment, assistantName)\n )\n\n await sendMessage(currentMessage, parentId, options)\n },\n [\n selectedWorkspaceId,\n isGenerating,\n session,\n sendMessage,\n arbi,\n routeMessage,\n postComment,\n queryClient,\n assistantName,\n ]\n )\n\n const handleAbortGeneration = useCallback(async () => {\n // A second press (a double-click) must not stop the run again: it would cancel twice, and\n // once the local abort has landed it would clear the stopped-stream marker, so the stream's\n // error would read as a failed answer.\n const stream = session.getState().generating[conversationKey]\n if (stopInFlightRef.current || stream?.isGenerating === false) return\n // A tap right after a Stop must not stop the follow-up the queue started in the meantime.\n if (Date.now() - lastStopAtRef.current < STOP_REPEAT_WINDOW_MS) return\n lastStopAtRef.current = Date.now()\n stopInFlightRef.current = true\n try {\n // Stop the run on the server first; closing the stream alone leaves it running and\n // its answer would arrive later.\n const controller = stream?.abortController ?? null\n stoppedStreamRef.current = controller\n let streamKey = conversationKey\n let responseId = stream?.streamingAssistantId ?? null\n // Pressed before the stream reported its id: the run already exists on the server, so wait\n // for the id instead of only closing the stream. Further presses meanwhile do nothing.\n if (!responseId && controller) {\n const reported = await waitForResponseId(session, controller)\n if (reported) {\n streamKey = reported.conversationKey\n responseId = reported.responseId\n }\n }\n // In a sub-agent's branch this is the run that delegated it.\n const threads =\n queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(streamKey))?.threads ?? []\n const runId = responseId ? getRunToCancel(threads, responseId) : null\n if (runId) {\n try {\n await arbi.assistant.cancel(runId)\n } catch {\n // Still stop here (the run may already have ended); say the server may keep going.\n notify.warning(\n \"Stopped here, but the server didn't confirm: the answer may still appear later.\"\n )\n }\n }\n // The cancel is awaited, and the server starts the next queued follow-up as soon as it lands:\n // that follow-up may already own this conversation's generation state and attach. Only close\n // the stream this Stop belongs to, or the next answer goes silent (\"Working\", no stop square).\n const current = session.getState().generating[streamKey]\n const isStoppedStream = controller\n ? current?.abortController === controller\n : !current?.streamingAssistantId || current.streamingAssistantId === responseId\n if (isStoppedStream) session.abortConversationGeneration(streamKey)\n // A reattached run has no local controller: close its stream too, or it keeps painting. The\n // attach follows this conversation's streaming message (in a sub-agent branch, the branch's\n // reply), not the delegating run that was cancelled, so match it by that id.\n if (responseId) disconnectAttachedRun(streamKey, responseId)\n } finally {\n stopInFlightRef.current = false\n }\n }, [session, arbi, conversationKey, queryClient])\n\n const handleRetryOrphanedMessage = useCallback(\n async (messageContent: string, parentId: string | null, messageExtId: string) => {\n // One retry at a time: the alert's Retry and the composer's retry (or a double click) must\n // not delete and resend twice. Released however the retry ends.\n if (retryInFlightRef.current) return\n // Offline the delete would be paused and the resend refused, leaving neither done.\n if (refuseChatWhenOffline()) return\n retryInFlightRef.current = true\n try {\n // A failed parent (a follow-up the restart sweep failed behind a failed answer) is\n // refused by the server, so the resend goes to the nearest message above it instead.\n const replyTo = currentConversationId\n ? resolveReplyTarget(queryClient, currentConversationId, parentId)\n : parentId\n if (!replyTo && currentConversationId) {\n try {\n await arbi.conversations.delete(currentConversationId)\n removeConversationFromLists(queryClient, currentConversationId)\n session.startNewConversation()\n } catch (error) {\n console.error('Failed to delete conversation with orphaned first message:', error)\n }\n } else if (replyTo) {\n try {\n await arbi.conversations.deleteMessage(messageExtId)\n // The message and its replies are gone from whichever thread held them.\n void queryClient.invalidateQueries(allConversationThreads)\n } catch (error) {\n console.error('Failed to delete orphaned message:', error)\n }\n }\n\n await sendMessage(messageContent, replyTo)\n } finally {\n retryInFlightRef.current = false\n }\n },\n [currentConversationId, arbi, session, sendMessage, queryClient]\n )\n\n const handleRetrySend = useCallback(async () => {\n if (isGenerating || !lastFailedMessage || retryInFlightRef.current) return\n if (refuseChatWhenOffline()) return\n retryInFlightRef.current = true\n try {\n session.clearConversationError(conversationKey)\n // sendMessage replies to the nearest message the server accepts: the view may still point at\n // a turn a Retry deleted, or at a failed answer.\n const parentId = session.getState().cursor\n await sendMessage(lastFailedMessage, parentId)\n } finally {\n retryInFlightRef.current = false\n }\n }, [isGenerating, lastFailedMessage, session, conversationKey, sendMessage])\n\n const clearErrorState = useCallback(() => {\n session.clearConversationError(conversationKey)\n }, [session, conversationKey])\n\n // Clear error state when starting a new conversation\n useEffect(() => {\n if (currentConversationId === null) {\n session.clearConversationError('new')\n }\n }, [currentConversationId, session])\n\n return {\n handleCreateBranch,\n handleSendMessage,\n handleAbortGeneration,\n handleRetrySend,\n handleRetryOrphanedMessage,\n clearErrorState,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAOA,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD,SAAS,sBAAwC;AACjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,cAAc;AACvB,SAAS,qBAAqB;AAC9B,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,mBAAmB;AAC5B,SAAS,aAAa,2BAA2B;AAEjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,wBAAwB;AACjC,SAAS,gBAAgB,mBAAmB,uBAAuB;AACnE,SAAS,2BAA2B;AACpC,SAAS,kBAAkB,iBAAiB;AAC5C,SAAS,oBAAoB,uBAAuB;AACpD,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAA2C;AACpD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,MAAM,uBAAuB;AAwC7B,SAAS,eACP,aACA,SACA,YACA,eACQ;AACR,QAAM,SAAS,qBAAqB,aAAa,QAAQ,SAAS,EAAE,cAAc;AAClF,SAAO,UAAU,CAAC,aAAa,IAAI,aAAa,MAAM;AACxD;AAMA,SAAS,uBACP,aACA,SACA,aAMM;AACN,MAAI,YAAY,qBAAqB;AACnC;AAAA,MACE;AAAA,MACA,YAAY;AAAA,MACZ,YAAY;AAAA,MACZ;AAAA,MACA;AAA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,aAAa,WAAW;AAAA,EACjE;AAEA,QAAM,kBAAkB,YAAY,YAAY;AAC9C,QAAI,gBAAgB,CAAC,qBAAqB,iBAAiB,QAAS;AACpE,QAAI,sBAAsB,EAAG;AAC7B,qBAAiB,UAAU;AAC3B,QAAI;AACF,cAAQ,uBAAuB,eAAe;AAG9C,YAAM,WAAW,QAAQ,SAAS,EAAE;AACpC,YAAM,YAAY,mBAAmB,QAAQ;AAAA,IAC/C,UAAE;AACA,uBAAiB,UAAU;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,cAAc,mBAAmB,SAAS,iBAAiB,WAAW,CAAC;AAE3E,QAAM,kBAAkB,YAAY,MAAM;AACxC,YAAQ,uBAAuB,eAAe;AAAA,EAChD,GAAG,CAAC,SAAS,eAAe,CAAC;AAG7B,YAAU,MAAM;AACd,QAAI,0BAA0B,MAAM;AAClC,cAAQ,uBAAuB,KAAK;AAAA,IACtC;AAAA,EACF,GAAG,CAAC,uBAAuB,OAAO,CAAC;AAEnC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var chunkKC474WVG_cjs = require('./chunk-KC474WVG.cjs');
|
|
4
3
|
var chunk5ECKSF6H_cjs = require('./chunk-5ECKSF6H.cjs');
|
|
5
4
|
var chunkN73IMVFF_cjs = require('./chunk-N73IMVFF.cjs');
|
|
5
|
+
var chunkKULS4YWP_cjs = require('./chunk-KULS4YWP.cjs');
|
|
6
|
+
var chunkKC474WVG_cjs = require('./chunk-KC474WVG.cjs');
|
|
6
7
|
var chunkHJDR5HEO_cjs = require('./chunk-HJDR5HEO.cjs');
|
|
7
|
-
var chunkDQODLWFX_cjs = require('./chunk-DQODLWFX.cjs');
|
|
8
8
|
var chunk5NOZDH3F_cjs = require('./chunk-5NOZDH3F.cjs');
|
|
9
9
|
var chunkS6A6FSG7_cjs = require('./chunk-S6A6FSG7.cjs');
|
|
10
10
|
var vanilla = require('zustand/vanilla');
|
|
@@ -416,7 +416,10 @@ function hasMessageBody(value, recipientLabel = "ARBI") {
|
|
|
416
416
|
return !!text && !labels.some((label) => text === `@${label}`.toLowerCase());
|
|
417
417
|
}
|
|
418
418
|
function opensInWord(doc) {
|
|
419
|
-
|
|
419
|
+
if (!doc) return false;
|
|
420
|
+
const name = (doc.file_name ?? "").toLowerCase();
|
|
421
|
+
if (name.endsWith(".docx")) return true;
|
|
422
|
+
return doc.wp_type === "artifact" && (!/\.[a-z0-9]+$/.test(name) || /\.(md|markdown|txt|html|htm|jsx)$/.test(name));
|
|
420
423
|
}
|
|
421
424
|
var isSlideDeck = (doc) => !!doc?.file_name?.toLowerCase().endsWith(".pptx");
|
|
422
425
|
function savedDocumentIdFor(input) {
|
|
@@ -505,7 +508,7 @@ function takeDocumentForTurn(input) {
|
|
|
505
508
|
const { documentId, entry } = picked;
|
|
506
509
|
if (entry) {
|
|
507
510
|
const { shownId, showLive } = entry.current();
|
|
508
|
-
if (shownId && shownId !== documentId &&
|
|
511
|
+
if (shownId && shownId !== documentId && chunkKULS4YWP_cjs.parseVersionRef(shownId).docId === documentId)
|
|
509
512
|
showLive?.();
|
|
510
513
|
}
|
|
511
514
|
return documentId;
|
|
@@ -593,5 +596,5 @@ exports.useAssistantName = useAssistantName;
|
|
|
593
596
|
exports.useOpenDocumentId = useOpenDocumentId;
|
|
594
597
|
exports.useRegisterOpenDocument = useRegisterOpenDocument;
|
|
595
598
|
exports.useTurnDocumentId = useTurnDocumentId;
|
|
596
|
-
//# sourceMappingURL=chunk-
|
|
597
|
-
//# sourceMappingURL=chunk-
|
|
599
|
+
//# sourceMappingURL=chunk-3DPOR5IR.cjs.map
|
|
600
|
+
//# sourceMappingURL=chunk-3DPOR5IR.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/search/session.ts","../src/notifications/Toaster.tsx","../src/notifications/NotificationBell.tsx","../src/host/ArbiHost.tsx","../src/host/assistant-copy.ts","../src/chat/mentions.ts","../src/chat/open-document.ts","../src/chat/thread-document.ts"],"names":["createStore","storage","jsx","Sonner","CheckCircle2","XCircle","AlertTriangle","Info","useState","useNotify","selectUnread","DEFAULT_NOTIFY_TONE","jsxs","DropdownMenu","DropdownMenuTrigger","Bell","DropdownMenuContent","CheckCheck","cn","BellOff","DropdownMenuItem","X","ScrollArea","formatRelativeTime","useContext","ArbiHostContext","useMemo","mergeHostConfig","OWN_SESSION_SLOT","useHostConfigRecord","useRef","useEffect","useSyncExternalStore","parseVersionRef"],"mappings":";;;;;;;;;;;;;;;AA8BA,IAAM,KAAA,GAAyD;AAAA,EAC7D,KAAA,EAAO,EAAA;AAAA,EACP,SAAS,EAAC;AAAA,EACV,QAAA,EAAU,KAAA;AAAA,EACV,MAAA,EAAQ,MAAA;AAAA,EACR,KAAA,EAAO,IAAA;AAAA,EACP,OAAA,EAAS;AACX,CAAA;AAEO,SAAS,mBAAA,GAAqC;AACnD,EAAA,OAAOA,mBAAA,CAAgC,OAAO,EAAE,GAAG,OAAO,WAAA,EAAa,IAAA,EAAM,GAAA,EAAK,CAAA,EAAE,CAAE,CAAA;AACxF;AAGO,IAAM,sBAAqC,mBAAA;AAG3C,SAAS,kBAAA,CACd,WAAA,EACA,OAAA,GAAyB,mBAAA,EACnB;AACN,EAAA,OAAA,CAAQ,QAAA,CAAS,CAAC,CAAA,MAAO;AAAA,IACvB,GAAG,KAAA;AAAA,IACH,WAAA,EAAa,WAAA,KAAgB,MAAA,GAAY,CAAA,CAAE,WAAA,GAAc,WAAA;AAAA,IACzD,GAAA,EAAK,EAAE,GAAA,GAAM;AAAA,GACf,CAAE,CAAA;AACJ;AAMO,SAAS,aAAA,CACd,KAAA,EACA,WAAA,EACA,OAAA,GAAyB,mBAAA,EACnB;AACN,EAAA,kBAAA,CAAmB,aAAa,OAAO,C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AC,cAAA,EAAgB,UAAU,CAAA,IAAK,MAAA,CAAO,QAAQ,MAAM,CAAA;AAC9D,QAAA,IAAI,OAAO,UAAA,KAAe,QAAA,EAAU,GAAA,CAAI,cAAc,CAAA,GAAI,UAAA;AAAA,IAAA;AAAA,EAChE,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,OAAO,GAAA;AACT;AAGO,SAAS,4BAA4B,eAAA,EAA0C;AACpF,EAAA,IAAI,eAAA,CAAgB,WAAW,CAAA,EAAG;AAClC,EAAA,MAAM,OAAO,yBAAA,EAA0B;AACvC,EAAA,eAAA,CAAgB,QAAQ,CAAC,EAAA,KAAO,OAAO,IAAA,CAAK,EAAE,CAAC,CAAA;AAC/C,EAAA,IAAI;AACF,IAAA,IAAI,MAAA,CAAO,KAAK,IAAI,CAAA,CAAE,WAAW,CAAA,EAAG,OAAA,EAAQ,EAAG,UAAA,CAAW,2BAA2B,CAAA;AAAA,kBACxE,EAAG,OAAA,CAAQ,6BAA6B,IAAA,CAAK,SAAA,CAAU,IAAI,CAAC,CAAA;AAAA,EAC3E,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-3DPOR5IR.cjs","sourcesContent":["/**\n * A search's state outside any component: the query last searched, its passages, and whether it\n * is running. A page that shows the shared session (`sharedSearchSession`) keeps its results when\n * it is left and opened again, another surface can hand it a query to run on arrival\n * ({@link requestSearch}), and {@link persistSearchSession} keeps the last query across reloads.\n */\nimport { createStore, type StoreApi } from 'zustand/vanilla'\nimport type { SearchChunk } from '@arbidocs/sdk/browser'\n\nexport type SearchStatus = 'idle' | 'running' | 'done' | 'error'\n\nexport interface SearchSessionState {\n /** The workspace the query and results belong to. */\n workspaceId: string | null\n /** The query last searched, or handed over to run. */\n query: string\n /** The last search's passages, best first. */\n results: SearchChunk[]\n /** A search has finished with results to show (cleared by {@link clearSearchSession}). */\n searched: boolean\n status: SearchStatus\n error: string | null\n /** A query handed over by {@link requestSearch}, run once by the page that shows the session. */\n pending: string | null\n /** Counts searches, so the reply to an older one never overwrites a newer one. */\n run: number\n}\n\nexport type SearchSession = StoreApi<SearchSessionState>\n\nconst EMPTY: Omit<SearchSessionState, 'workspaceId' | 'run'> = {\n query: '',\n results: [],\n searched: false,\n status: 'idle',\n error: null,\n pending: null,\n}\n\nexport function createSearchSession(): SearchSession {\n return createStore<SearchSessionState>(() => ({ ...EMPTY, workspaceId: null, run: 0 }))\n}\n\n/** The session a host's search page shows. */\nexport const sharedSearchSession: SearchSession = createSearchSession()\n\n/** Back to nothing searched (in `workspaceId` when given); a running search's reply is dropped. */\nexport function clearSearchSession(\n workspaceId?: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n session.setState((s) => ({\n ...EMPTY,\n workspaceId: workspaceId === undefined ? s.workspaceId : workspaceId,\n run: s.run + 1,\n }))\n}\n\n/**\n * Hand a query to the search page, which runs it when it shows the session (the user already\n * asked once; the page must not wait for a second Enter).\n */\nexport function requestSearch(\n query: string,\n workspaceId: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n clearSearchSession(workspaceId, session)\n session.setState({ query, pending: query })\n}\n\n/** The handed-over query, once: the next call returns null. */\nexport function takePendingSearch(session: SearchSession = sharedSearchSession): string | null {\n const { pending } = session.getState()\n if (pending !== null) session.setState({ pending: null })\n return pending\n}\n\ninterface SavedSearch {\n query?: string\n workspaceId?: string | null\n}\n\n/**\n * Keep the last query (and its workspace) in `storage` under `key`, so the search box shows it\n * after a reload. Results are not kept. Returns the unsubscribe.\n */\nexport function persistSearchSession(\n key: string,\n storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = globalThis.localStorage,\n session: SearchSession = sharedSearchSession\n): () => void {\n if (!storage) return () => {}\n try {\n const saved = JSON.parse(storage.getItem(key) ?? 'null') as SavedSearch | null\n if (saved && typeof saved.query === 'string' && !session.getState().query)\n session.setState({ query: saved.query, workspaceId: saved.workspaceId ?? null })\n } catch {\n // Unreadable: start empty.\n }\n let last = ''\n return session.subscribe(({ query, workspaceId }) => {\n const next = JSON.stringify({ query, workspaceId })\n if (next === last) return\n last = next\n try {\n storage.setItem(key, next)\n } catch {\n // Storage full or blocked: the query is simply not kept.\n }\n })\n}\n","/**\n * Toaster — the one shared toast surface, built on sonner (the mature engine:\n * stacking, swipe-to-dismiss, a11y, timing). Mount once near the app root; any\n * code then calls `notify.*(...)` (or the re-exported `toast`) from anywhere.\n *\n * Firm-agnostic: every sonner `ToasterProps` passes through, so a consumer sets\n * its own `position` / `theme` / `toastOptions`. The defaults give a neutral\n * shadcn-token card that both apps can override.\n */\nimport { Toaster as Sonner, type ToasterProps } from 'sonner'\n\nexport type { ToasterProps }\n\nconst DEFAULT_TOAST_OPTIONS: ToasterProps['toastOptions'] = {\n classNames: {\n toast:\n 'group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:rounded-lg',\n description: 'group-[.toast]:text-muted-foreground',\n actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',\n cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',\n },\n}\n\nexport function Toaster({ toastOptions, ...props }: ToasterProps) {\n return (\n <Sonner\n className=\"toaster group\"\n toastOptions={toastOptions ?? DEFAULT_TOAST_OPTIONS}\n {...props}\n />\n )\n}\n","/**\n * NotificationBell — the topbar notification centre: a bell with an unread badge\n * that opens a dropdown of recorded entries (newest first) with an unread dot,\n * relative time and optional deep-link. \"Mark all read\" clears the badge. Backed\n * by the shared {@link useNotify} store (the same one the <Toaster/> renders).\n *\n * Firm-agnostic: navigation is a callback (`onNavigate`), styling tracks semantic\n * tokens, and per-variant glyph colours are overridable via `toneClassNames`.\n */\nimport { useState, type ReactElement } from 'react'\nimport {\n Bell,\n BellOff,\n CheckCheck,\n CheckCircle2,\n AlertTriangle,\n XCircle,\n Info,\n X,\n} from 'lucide-react'\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuItem,\n} from '../ui/dropdown-menu'\nimport { ScrollArea } from '../ui/scroll-area'\nimport { cn } from '../lib/utils'\nimport { formatRelativeTime } from '../lib/format-relative-time'\nimport {\n useNotify,\n selectUnread,\n DEFAULT_NOTIFY_TONE,\n type NotifyVariant,\n type AppNotification,\n} from './notify-store'\n\nconst GLYPH: Record<NotifyVariant, typeof Info> = {\n success: CheckCircle2,\n error: XCircle,\n warning: AlertTriangle,\n info: Info,\n}\n\n/** Entries the panel lists, newest first. */\nconst BELL_LIMIT = 100\n\n/** What a custom bell trigger needs to render itself. */\nexport interface NotificationBellTriggerState {\n /** Unread count (0 when none). */\n unread: number\n /** Accessible name, including the count: \"Notifications, 2 unread\". */\n ariaLabel: string\n testId: string\n}\n\nexport interface NotificationBellProps {\n /**\n * Replaces the default icon button with the host's own trigger (for example a labelled sidebar\n * row). It must forward its ref and rest props: it is mounted as the dropdown trigger.\n */\n renderTrigger?: (state: NotificationBellTriggerState) => ReactElement\n /** Called with an entry's `href` when it's clicked (e.g. router navigate). */\n onNavigate?: (href: string) => void\n /** Open this entry in the host notification centre instead of following its link. */\n onSelectNotification?: (notification: AppNotification) => void\n /** Called after an entry is locally marked read — the hook for a backend\n * bridge to propagate read state upstream (filter by the ids it owns). */\n onMarkRead?: (id: string) => void\n /** Called after \"Mark all read\" — same upstream-propagation hook. */\n onMarkAllRead?: () => void\n /** Show the store's toast mute switch in the header — the bell is where notification\n * behaviour is controlled. */\n showMuteToggle?: boolean\n /** Override per-variant glyph colours (e.g. brand emerald for success). */\n toneClassNames?: Partial<Record<NotifyVariant, string>>\n emptyText?: string\n /** Footer link to the app's full notification surface. Omit to hide. */\n onViewAll?: () => void\n viewAllLabel?: string\n testId?: string\n /** Where the panel opens relative to the bell (a sidebar-footer bell opens upward). */\n side?: 'top' | 'right' | 'bottom' | 'left'\n align?: 'start' | 'center' | 'end'\n}\n\nexport function NotificationBell({\n renderTrigger,\n onNavigate,\n onSelectNotification,\n onMarkRead,\n onMarkAllRead,\n showMuteToggle = false,\n toneClassNames,\n emptyText = \"You're all caught up.\",\n onViewAll,\n viewAllLabel = 'View all',\n testId = 'notifications',\n side = 'bottom',\n align = 'end',\n}: NotificationBellProps) {\n const [open, setOpen] = useState(false)\n const notifications = useNotify((s) => s.notifications)\n const unread = useNotify(selectUnread)\n const markAllRead = useNotify((s) => s.markAllRead)\n const markRead = useNotify((s) => s.markRead)\n const muted = useNotify((s) => s.muted)\n const setMuted = useNotify((s) => s.setMuted)\n const tone = (v: NotifyVariant) => toneClassNames?.[v] ?? DEFAULT_NOTIFY_TONE[v]\n\n // Ambient entries (routine session activity — \"Opening workspace…\") are kept\n // for the log but never surfaced in the bell panel: they never badge and are\n // always filtered out here. The panel is the recent history; a host's\n // notification page (`onViewAll`) holds the rest.\n const visible = notifications.filter((n) => !n.ambient).slice(0, BELL_LIMIT)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n {renderTrigger ? (\n renderTrigger({\n unread,\n ariaLabel: `Notifications${unread ? `, ${unread} unread` : ''}`,\n testId,\n })\n ) : (\n <button\n className=\"relative flex size-9 pointer-coarse:size-11 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n data-testid={testId}\n aria-label={`Notifications${unread ? `, ${unread} unread` : ''}`}\n title=\"Notifications\"\n >\n <Bell className=\"size-5\" />\n {unread > 0 && (\n <span\n className=\"absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-xs font-semibold leading-4 text-primary-foreground\"\n data-testid={`${testId}-badge`}\n >\n {unread > 9 ? '9+' : unread}\n </span>\n )}\n </button>\n )}\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align={align}\n side={side}\n sideOffset={8}\n collisionPadding={12}\n className=\"w-60 rounded-lg border-border/60 p-0 shadow-lg pointer-coarse:w-88\"\n data-testid={`${testId}-panel`}\n data-topbar-popover=\"\"\n >\n <div className=\"flex items-center justify-between gap-3 border-b border-border px-3.5 py-2.5 pointer-coarse:py-0\">\n <p className=\"text-sm font-semibold text-foreground\">Notifications</p>\n <div className=\"flex items-center gap-3 pointer-coarse:gap-1\">\n {unread > 0 && (\n <button\n onClick={() => {\n markAllRead()\n onMarkAllRead?.()\n }}\n className=\"flex items-center gap-1 text-xs font-medium text-primary transition-colors hover:opacity-80 pointer-coarse:min-h-11 pointer-coarse:px-2\"\n data-testid={`${testId}-mark-all`}\n >\n <CheckCheck className=\"size-3.5\" /> Mark all read\n </button>\n )}\n {showMuteToggle && (\n <button\n onClick={() => setMuted(!muted)}\n aria-pressed={muted}\n title={muted ? 'Unmute notifications' : 'Mute notifications'}\n aria-label={muted ? 'Unmute notifications' : 'Mute notifications'}\n className={cn(\n 'flex size-6 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-accent pointer-coarse:size-11',\n muted ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'\n )}\n data-testid={`${testId}-mute`}\n >\n <BellOff className=\"size-3.5\" />\n </button>\n )}\n {/* Explicit close — the dropdown otherwise only dismisses via\n tap-outside/Escape, which isn't discoverable on touch and (at\n mobile width, see blocks.css) the panel covers most\n of the screen so there's nothing to tap outside of. Radix\n closes a DropdownMenu on any item select by default, so a\n plain item with no other effect doubles as a close button. */}\n <DropdownMenuItem\n className=\"flex size-6 shrink-0 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus:bg-accent pointer-coarse:size-11\"\n aria-label=\"Close notifications\"\n data-testid={`${testId}-close`}\n >\n <X className=\"size-3.5\" />\n </DropdownMenuItem>\n </div>\n </div>\n {muted && (\n <p\n className=\"border-b border-border/60 bg-amber-500/10 px-3.5 py-1.5 text-xs text-muted-foreground\"\n data-testid={`${testId}-muted-note`}\n >\n Toasts are muted — everything still lands here.\n </p>\n )}\n\n {visible.length === 0 ? (\n <div className=\"px-3.5 py-10 text-center text-sm text-muted-foreground\">{emptyText}</div>\n ) : (\n <ScrollArea className=\"max-h-[380px]\">\n <ul data-testid={`${testId}-list`}>\n {visible.map((n) => {\n const Glyph = GLYPH[n.variant]\n return (\n <li key={n.id}>\n <button\n onClick={() => {\n markRead(n.id)\n if (!n.read) onMarkRead?.(n.id)\n setOpen(false)\n if (onSelectNotification) {\n onSelectNotification(n)\n return\n }\n // The specific action wins over the generic deep link.\n if (n.onSelect) n.onSelect()\n else if (n.href) onNavigate?.(n.href)\n }}\n className={cn(\n 'flex w-full items-start gap-3 border-b border-border/60 px-3.5 py-3 text-left transition-colors hover:bg-accent',\n !n.read && 'bg-accent/40'\n )}\n data-testid={`${testId}-item`}\n data-notification-id={n.id}\n >\n <Glyph className={cn('mt-0.5 size-4 shrink-0', tone(n.variant))} />\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-sm font-medium leading-snug text-foreground\">\n {n.title}\n </p>\n {n.description && (\n <p className=\"mt-0.5 line-clamp-2 text-xs leading-relaxed text-muted-foreground\">\n {n.description}\n </p>\n )}\n <p className=\"mt-1 text-xs text-muted-foreground/80\">\n {formatRelativeTime(new Date(n.ts).toISOString())}\n </p>\n </div>\n {(n.onSelect || n.href) && (\n <span className=\"shrink-0 self-center rounded-md bg-primary/10 px-2 py-1 text-xs font-medium text-primary\">\n {n.actionLabel ?? 'Open'}\n </span>\n )}\n {!n.read && (\n <span className=\"mt-1.5 size-2 shrink-0 rounded-full bg-primary\" />\n )}\n </button>\n </li>\n )\n })}\n </ul>\n </ScrollArea>\n )}\n {onViewAll && (\n // A real menu item, not a bare button: selecting it must CLOSE the\n // dropdown on its way to the full surface.\n <DropdownMenuItem\n onClick={onViewAll}\n className=\"justify-center rounded-none border-t border-border px-3.5 py-2.5 text-xs font-medium text-primary focus:text-primary pointer-coarse:min-h-11\"\n data-testid={`${testId}-view-all`}\n >\n {viewAllLabel}\n </DropdownMenuItem>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n","/**\n * `<ArbiHost config>`: the one place a host app hands its configuration to every hook and kit.\n *\n * <ArbiHost config={{ arbi, session, documents, calendar, mail, account, … }}>\n * <App />\n * </ArbiHost>\n *\n * Every field is optional and has a default (see `ArbiHostConfig`); a kit reads its domain from\n * the config (`useArbiHost().documents`, `useHost().billing` in blocks). A nested `<ArbiHost>`\n * overrides only the fields it gives and inherits the rest (`environment` field by field), for a\n * subtree that opens projects in its own tabs, say. There is no other host provider: a new domain\n * is a new optional field, never a new provider.\n *\n * SDK-free (this module, ./context, ./merge and the entity vocabulary are all it reaches), so a\n * marketing site that only sets the blocks environment does not bundle the SDK.\n */\n\nimport { useContext, useMemo, useState, type ComponentType, type ReactNode } from 'react'\nimport { ArbiHostContext } from './context'\nimport { mergeHostConfig, OWN_SESSION_SLOT } from './merge'\nimport { configureEntityVocabulary, type EntityVocabulary } from '../entities/vocabulary'\n\n/** A sign-in layer mounted inside the host (`defaultHost` in `@arbidocs/blocks/connect`). */\nexport interface ArbiHostConnection {\n Provider: ComponentType<{ children: ReactNode }>\n}\n\nexport interface ArbiHostProps<Config extends object> {\n config: Config\n children?: ReactNode\n}\n\n/**\n * Provide the host configuration. Typed by the package it is imported from: `@arbidocs/react`'s\n * takes the react domains, `@arbidocs/blocks`' the blocks domains as well.\n */\nexport function ArbiHost<Config extends object>({\n config,\n children,\n}: ArbiHostProps<Config>): React.ReactElement {\n const parent = useContext(ArbiHostContext)\n // A top-level host without a session store gets its own, made on first use (useArbiSessionStore).\n const [ownSession] = useState(() => ({ current: null as unknown }))\n const value = useMemo(() => {\n const merged = mergeHostConfig(parent, config)\n return merged[OWN_SESSION_SLOT] ? merged : { ...merged, [OWN_SESSION_SLOT]: ownSession }\n }, [parent, config, ownSession])\n // The site's nouns are in place before any kit below renders a label.\n const { vocabulary } = config as { vocabulary?: EntityVocabulary }\n if (vocabulary) configureEntityVocabulary(vocabulary)\n const Connection = (config as { connection?: ArbiHostConnection }).connection?.Provider\n return (\n <ArbiHostContext.Provider value={value}>\n {Connection ? <Connection>{children}</Connection> : children}\n </ArbiHostContext.Provider>\n )\n}\n","/**\n * What the kits call the assistant in their own words, from the host's name for it\n * (`ArbiHostConfig.assistantName`, also what people @mention). One label source: every kit phrase\n * that names the assistant is here, written once around the name, so a custom site's name shows\n * everywhere and ARBI's own text is unchanged (\"ARBI\" when the host names it nothing else).\n *\n * const copy = useAssistantCopy()\n * <Button>{copy.ask}</Button> // \"Ask ARBI\", or \"Ask Acme Assistant\"\n *\n * SDK-free: exported from `@arbidocs/react/shell` too, for presentational parts.\n */\nimport { useMemo } from 'react'\n// The record, not `useArbiHost` (`./config` names the SDK's types): this module stays SDK-free.\nimport { useHostConfigRecord } from './context'\n\n/** The assistant's name when the host names it nothing else. */\nexport const DEFAULT_ASSISTANT_NAME = 'ARBI'\n\n/** Every kit phrase that names the assistant. */\nexport interface AssistantCopy {\n /** The name itself. */\n name: string\n /** \"Ask ARBI\": a button or tab that starts a question. */\n ask: string\n /** \"Ask ARBI anything\": an empty list's call to ask. */\n askAnything: string\n /** \"Ask ARBI anything…\": the chat composer's placeholder. */\n askAnythingPlaceholder: string\n /** \"Ask ARBI...\": a compact composer's placeholder. */\n askPlaceholder: string\n /** \"Ask ARBI about your documents\": the empty chat's heading. */\n askAboutDocuments: string\n /** The files bulk bar's chat tooltip. */\n askAboutSelection: string\n /** \"ARBI is asking\": the heading over a question the assistant asks. */\n isAsking: string\n /** The composer's placeholder while the assistant waits for an answer. */\n answerPlaceholder: string\n /** The empty threads list, with the composer below it. */\n emptyThreadsComposer: string\n /** The empty threads list, with a New Task button. */\n emptyThreadsNewTask: string\n /** The drafting chip's hint while the thread drafts in a document. */\n draftingHint: string\n /** The drafting chip's hint before the document is attached. */\n draftingAttachHint: string\n /** The chat's facts tab note. */\n factsInContext: (facts: string) => string\n /** \"Ask one question — ARBI answers it for each of …\": the AI review's ask step. */\n reviewEach: (count: number, scope: string) => string\n /** The facts bar's note on the chat's facts budget. */\n factsBudgetHint: string\n /** An AI review cell left without an answer. */\n noAnswerHint: string\n /** The new-thread dialog's button that hands the thread to the assistant. */\n startWith: string\n /** The mail action bar's \"Reply with ARBI\". */\n replyWith: string\n /** The Word editor's comment button that @mentions the assistant. */\n include: string\n /** A reply to an email asked for outside a workspace. */\n replyNeedsWorkspace: string\n /** After an upload. */\n uploadedIndexing: string\n /** Before an upload completes. */\n afterUpload: string\n /** The built-in Deep research workflow's description and details. */\n deepResearch: { description: string; details: string }\n /** The built-in AI annotation operation's details. */\n annotate: { details: string; placeholder: string }\n}\n\nconst plural = (n: number) => (n === 1 ? '' : 's')\n\n/** The phrases for one name. `assistantCopy()` is ARBI's own text. */\nexport function assistantCopy(name: string = DEFAULT_ASSISTANT_NAME): AssistantCopy {\n return {\n name,\n ask: `Ask ${name}`,\n askAnything: `Ask ${name} anything`,\n askAnythingPlaceholder: `Ask ${name} anything…`,\n askPlaceholder: `Ask ${name}...`,\n askAboutDocuments: `Ask ${name} about your documents`,\n askAboutSelection: `Ask ${name} about the selected document(s) in a new thread`,\n isAsking: `${name} is asking`,\n answerPlaceholder: `Type your answer to ${name} — or pick an option above`,\n emptyThreadsComposer: `Type below to ask ${name}, bring in people, or both.`,\n emptyThreadsNewTask: `Use New Task to ask ${name}, bring in people, or both.`,\n draftingHint: `This thread works in the document: ${name} reads what it needs and makes its edits as tracked changes you accept or reject.`,\n draftingAttachHint: `Attach the open document to this thread: its questions then edit the document as tracked changes. Until then, ${name} only answers.`,\n factsInContext: (facts) =>\n `${facts} added to this chat are always in ${name}'s context for this chat.`,\n reviewEach: (count, scope) =>\n `Ask one question — ${name} answers it for each of the ${count} ${scope} document${plural(count)}.`,\n factsBudgetHint: `Facts added to this chat are always in ${name}'s context for this chat, so they share one budget. This estimates the tokens they add (≈4 characters per token), capped at ~2,000.`,\n noAnswerHint: `${name} finished this document without an answer for this field. The document may not say, or the request failed. Run it again to retry.`,\n startWith: `Start with ${name}`,\n replyWith: `Reply with ${name}`,\n include: `Include ${name}`,\n replyNeedsWorkspace: `Open a workspace to chat with ${name} about this email`,\n uploadedIndexing: `Files uploaded successfully. ${name} is now indexing them in the background.`,\n afterUpload: `After upload completes, ${name} will index files in the background.`,\n deepResearch: {\n description: `Send ${name} through your files and the web, and get an answer with sources`,\n details: `${name} searches your files and the web, then answers with the sources it used. You’ll see the research unfold in the chat.`,\n },\n annotate: {\n details: `Ask one question — ${name} answers it for every selected file and fills a new column with the answers.`,\n placeholder: `What should ${name} read out? e.g. What currency is the penalty clause denominated in?`,\n },\n }\n}\n\n/** The host's name for its assistant (`ArbiHostConfig.assistantName`), else \"ARBI\". */\nexport function useAssistantName(): string {\n const name = useHostConfigRecord().assistantName\n return (typeof name === 'string' && name.trim()) || DEFAULT_ASSISTANT_NAME\n}\n\n/** The kit phrases for the host's assistant name. */\nexport function useAssistantCopy(): AssistantCopy {\n const name = useAssistantName()\n return useMemo(() => assistantCopy(name), [name])\n}\n","/**\n * @mentions in chat text: pure helpers shared by the composer (autocomplete, extraction) and\n * the message renderer (chips). No React, no SDK.\n *\n * A mention lives in two places: the readable `@Label` text in the message content, and a\n * structured entry on the message (`{ type, user_ext_id, label }`) that the server reads to share\n * the conversation and notify. The composer only ever inserts `@<label>` for a known candidate,\n * so the structured list can be recovered from the text at send time ({@link extractMentions});\n * the renderer turns each stored mention back into a chip ({@link linkMentions}).\n */\n\n/** Who can be mentioned: a workspace member, or the assistant. */\nexport type MentionKind = 'user' | 'assistant'\n\n/** One entry of the mention autocomplete. */\nexport interface MentionCandidate {\n /** User external id (`usr-…`) for a person; any stable key (e.g. `assistant`) for the assistant. */\n id: string\n kind: MentionKind\n /** Inserted as `@<label>`. For people this must be the server's display name (given + family). */\n label: string\n /** Secondary line in the menu (email, role, …). */\n description?: string\n}\n\n/** The structured mention a message carries (the API's `MessageMention`). */\nexport interface MessageMentionRef {\n type: MentionKind\n user_ext_id?: string | null\n label?: string | null\n}\n\n/** Longest text after `@` that still counts as a query in progress. */\nconst MAX_QUERY_LENGTH = 40\n\n/**\n * The `@query` the caret is in, if any: the `@` must start the text or follow whitespace, and the\n * query may contain spaces (names do) but no newline. Returns the index of the `@` and the query.\n */\nexport function findMentionQuery(\n text: string,\n caret: number\n): { start: number; query: string } | null {\n const before = text.slice(0, caret)\n const at = before.lastIndexOf('@')\n if (at < 0) return null\n if (at > 0 && !/\\s/.test(before[at - 1])) return null\n const query = before.slice(at + 1)\n if (query.length > MAX_QUERY_LENGTH || query.includes('\\n') || query.startsWith(' ')) return null\n return { start: at, query }\n}\n\n/** Candidates matching a query: label prefix (or word-prefix) matches, prefix matches first. */\nexport function filterMentionCandidates(\n candidates: ReadonlyArray<MentionCandidate>,\n query: string\n): MentionCandidate[] {\n const q = query.trim().toLowerCase()\n if (!q) return candidates.slice()\n const scored: Array<{ c: MentionCandidate; score: number }> = []\n for (const c of candidates) {\n const label = c.label.toLowerCase()\n if (label.startsWith(q)) scored.push({ c, score: 0 })\n else if (label.split(/\\s+/).some((word) => word.startsWith(q))) scored.push({ c, score: 1 })\n else if (c.description?.toLowerCase().startsWith(q)) scored.push({ c, score: 2 })\n }\n return scored.sort((a, b) => a.score - b.score).map((s) => s.c)\n}\n\n/** Replace the `@query` at `start…caret` with `@<label> `; returns the new text and caret. */\nexport function insertMention(\n text: string,\n start: number,\n caret: number,\n label: string\n): { text: string; caret: number } {\n const inserted = `@${label} `\n return {\n text: text.slice(0, start) + inserted + text.slice(caret),\n caret: start + inserted.length,\n }\n}\n\n/** Every `[from, to)` range where `@<label>` occurs as a whole token. */\nfunction tokenRanges(text: string, label: string): Array<[number, number]> {\n const needle = `@${label}`\n const ranges: Array<[number, number]> = []\n let from = 0\n for (;;) {\n const i = text.indexOf(needle, from)\n if (i < 0) break\n const end = i + needle.length\n const startsToken = i === 0 || /\\s|\\(|\\[/.test(text[i - 1])\n const endsToken = end === text.length || !/[\\p{L}\\p{N}_]/u.test(text[end])\n if (startsToken && endsToken) ranges.push([i, end])\n from = end\n }\n return ranges\n}\n\n/**\n * The candidates mentioned in `text`, in order of first appearance. Longer labels win overlaps,\n * so `@Bob Smith` is Bob Smith, not a separate `@Bob`.\n */\nexport function extractMentions(\n text: string,\n candidates: ReadonlyArray<MentionCandidate>\n): MentionCandidate[] {\n const taken: Array<[number, number]> = []\n const found: Array<{ c: MentionCandidate; at: number }> = []\n const byLength = [...candidates].sort((a, b) => b.label.length - a.label.length)\n for (const c of byLength) {\n if (!c.label) continue\n for (const [from, to] of tokenRanges(text, c.label)) {\n if (taken.some(([a, b]) => from < b && to > a)) continue\n taken.push([from, to])\n if (!found.some((f) => f.c.id === c.id)) found.push({ c, at: from })\n }\n }\n return found.sort((a, b) => a.at - b.at).map((f) => f.c)\n}\n\n/** The API payload for mentioned candidates. */\nexport function toMessageMentions(mentioned: ReadonlyArray<MentionCandidate>): MessageMentionRef[] {\n return mentioned.map((c) =>\n c.kind === 'assistant' ? { type: 'assistant' } : { type: 'user', user_ext_id: c.id }\n )\n}\n\n/** Fragment prefix of the links {@link linkMentions} writes. */\nexport const MENTION_HREF_PREFIX = '#mention-'\n\n/** Escape the characters that would end a markdown link text early. */\nfunction escapeLinkText(label: string): string {\n return label.replace(/[[\\]\\\\]/g, (ch) => `\\\\${ch}`)\n}\n\n/**\n * Turn each stored mention's `@<label>` in `content` into a markdown link\n * `[@<label>](#mention-<id>)`, so a markdown renderer can draw it as a chip (see\n * {@link mentionFromHref}). Text that no longer matches (a renamed user) stays plain text.\n * `assistantLabels` lists other names the assistant may have been mentioned by.\n */\nexport function linkMentions(\n content: string,\n mentions: ReadonlyArray<MessageMentionRef> | null | undefined,\n assistantLabels: ReadonlyArray<string> = []\n): string {\n if (!mentions || mentions.length === 0 || !content) return content\n const targets: Array<{ label: string; id: string }> = []\n for (const m of mentions) {\n const id = m.type === 'assistant' ? 'assistant' : m.user_ext_id\n if (!id) continue\n const labels = m.type === 'assistant' ? [m.label ?? '', ...assistantLabels] : [m.label ?? '']\n for (const label of labels) if (label) targets.push({ label, id })\n }\n targets.sort((a, b) => b.label.length - a.label.length)\n const replacements: Array<{ from: number; to: number; text: string }> = []\n for (const { label, id } of targets) {\n for (const [from, to] of tokenRanges(content, label)) {\n if (replacements.some((r) => from < r.to && to > r.from)) continue\n replacements.push({\n from,\n to,\n text: `[@${escapeLinkText(label)}](${MENTION_HREF_PREFIX}${id})`,\n })\n }\n }\n replacements.sort((a, b) => b.from - a.from)\n let out = content\n for (const r of replacements) out = out.slice(0, r.from) + r.text + out.slice(r.to)\n return out\n}\n\n/** The mention a `#mention-…` href points at, or null for any other href. */\nexport function mentionFromHref(\n href: string | null | undefined\n): { kind: MentionKind; id: string } | null {\n if (!href?.startsWith(MENTION_HREF_PREFIX)) return null\n const id = href.slice(MENTION_HREF_PREFIX.length)\n if (!id) return null\n return { kind: id === 'assistant' ? 'assistant' : 'user', id }\n}\n\n/** A recipient alone (by any of its labels) is not a message. */\nexport function hasMessageBody(\n value: string,\n recipientLabel: string | ReadonlyArray<string> = 'ARBI'\n): boolean {\n const text = value.trim().toLowerCase()\n const labels = typeof recipientLabel === 'string' ? [recipientLabel] : recipientLabel\n return !!text && !labels.some((label) => text === `@${label}`.toLowerCase())\n}\n","import { useEffect, useRef, useSyncExternalStore } from 'react'\nimport { parseVersionRef } from '../artifacts/versions'\n\n/**\n * Drafting mode: the documents open beside the chat, and which one a chat turn drafts in.\n *\n * A viewer registers the document it shows (`useRegisterOpenDocument`). Being open binds nothing:\n * a turn names a document (`active_artifact_ext_id`, read with `takeDocumentForTurn` as the\n * question is sent) only when its thread is bound to it (`./thread-document`: started from the\n * document, or attached in that thread), when the document was made in that thread, or when the\n * open document is ambient (an email draft open in the composer). The server then binds the live\n * document to the turn: a Word document is read on demand and edited as tracked changes in the\n * open editor, and what the assistant saves becomes a child version of it. The request carries a\n * reference, never the content.\n *\n * The named document is always the subject, also while one of its earlier versions is on screen\n * read-only: a version still names its document. Sending a turn then returns the viewer to the live\n * document (`showLive`), where the assistant's edits appear as they are made. (Pinning a specific\n * version as a source is a separate feature: it does not go through here.)\n *\n * A module-level registry (not React context), like `useChatSurface`, so a viewer and a chat agree\n * wherever they sit in the tree; the most recently opened document is on top and closing it hands\n * back to the one before. It is not the session state's viewing document (`useArbiSessionState`):\n * it holds what mounted viewers can draft in (saved documents only, with the callback that shows\n * the live one again), and a turn reads it outside React. A viewer on the session's viewing\n * document passes that as `shownId` (it may be a version reference, resolved here the same way as\n * `selectViewingDocumentId` does).\n */\n\n/** What a viewer knows about the document it shows. */\nexport interface SavedDocumentInput {\n /** The document (`doc-…`), never a version reference. */\n documentId: string | null | undefined\n /** An unsaved draft (client-minted id, no backend record). */\n isDraft: boolean\n /** Still streaming: nothing is persisted yet. */\n isStreaming: boolean\n /** An image, audio or video artifact: there is no text to draft in. */\n isBlobArtifact: boolean\n /** The loaded document record. */\n documentData:\n | { external_id?: string | null; wp_type?: string | null; file_name?: string | null }\n | null\n | undefined\n}\n\n/** The fields that decide where a document opens. */\nexport interface WordDocumentKind {\n file_name?: string | null\n wp_type?: string | null\n}\n\n/**\n * A document edited in the Word editor: a `.docx`, or a document the assistant wrote (an\n * artifact). The one rule for where a document opens (`openWordEditor` or `openDocument`) and\n * which documents a chat drafts in.\n */\nexport function opensInWord(doc: WordDocumentKind | null | undefined): boolean {\n if (!doc) return false\n const name = (doc.file_name ?? '').toLowerCase()\n if (name.endsWith('.docx')) return true\n // Sandboxed outputs are artifacts too; PDFs, images, archives and recordings\n // must never become Word drafting targets merely because an agent saved them.\n return (\n doc.wp_type === 'artifact' &&\n (!/\\.[a-z0-9]+$/.test(name) || /\\.(md|markdown|txt|html|htm|jsx)$/.test(name))\n )\n}\n\n/** A slide deck (a PowerPoint file): the assistant edits it with its presentation tool. */\nexport const isSlideDeck = (doc: WordDocumentKind | null | undefined): boolean =>\n !!doc?.file_name?.toLowerCase().endsWith('.pptx')\n\n/**\n * The saved, content-backed document a chat can draft in, or null. Only a saved artifact, Word\n * document or slide deck counts: drafts, an artifact still streaming and blob artifacts do not.\n */\nexport function savedDocumentIdFor(input: SavedDocumentInput): string | null {\n const { documentId, isDraft, isStreaming, isBlobArtifact, documentData } = input\n if (!documentId || isDraft || isStreaming || isBlobArtifact) return null\n if (!documentData || !(opensInWord(documentData) || isSlideDeck(documentData))) return null\n // A stale record of the previously viewed document is not this one.\n if (documentData.external_id !== documentId) return null\n return documentId\n}\n\nexport interface OpenDocumentRegistration {\n /** The saved document the viewer shows (`doc-…`); null or empty registers nothing. */\n documentId: string | null | undefined\n /** What is on screen: the document itself, or one of its earlier versions (`doc-…@v2`). */\n shownId?: string | null\n /** Show the live document again. Called when a turn starts while an earlier version is shown. */\n showLive?: () => void\n /** The workspace the document belongs to; a chat in another workspace does not draft in it. */\n workspaceId?: string | null\n /** The thread the document was made in: that thread drafts in it without being bound to it. */\n conversationId?: string | null\n /**\n * Drafted in by whichever chat is beside it, bound or not (an email draft open in the composer:\n * the composer is a drafting surface of its own).\n */\n ambient?: boolean\n}\n\ninterface Entry {\n documentId: string\n current: () => OpenDocumentRegistration\n}\n\nlet entries: Entry[] = []\nconst listeners = new Set<() => void>()\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nfunction emit() {\n listeners.forEach((l) => l())\n}\n\nconst top = (): Entry | undefined => entries[entries.length - 1]\n\n/**\n * Registers the document a viewer shows as the open document while the caller is mounted and\n * `documentId` is set. Pass `savedDocumentIdFor(...)`, or the id of a document known to be saved.\n */\nexport function useRegisterOpenDocument(registration: OpenDocumentRegistration): void {\n const latest = useRef(registration)\n const { documentId, workspaceId, conversationId, ambient } = registration\n useEffect(() => {\n latest.current = registration\n })\n // What decides which chat drafts in it changed (its record loaded): readers re-render.\n useEffect(() => {\n if (documentId) emit()\n }, [documentId, workspaceId, conversationId, ambient])\n useEffect(() => {\n if (!documentId) return\n const entry: Entry = { documentId, current: () => latest.current }\n entries = [...entries, entry]\n emit()\n return () => {\n entries = entries.filter((e) => e !== entry)\n emit()\n }\n }, [documentId])\n}\n\n/** The open document's id (the most recently opened), or null. Re-renders when it changes. */\nexport function useOpenDocumentId(options?: { workspaceId?: string | null }): string | null {\n const workspaceId = options?.workspaceId ?? null\n return useSyncExternalStore(\n subscribe,\n () => openDocumentId({ workspaceId }),\n () => null\n )\n}\n\n/** The open document's id (the most recently opened); with `workspaceId`, only one of it. */\nexport function openDocumentId(options?: { workspaceId?: string | null }): string | null {\n const entry = top()\n if (!entry || !inWorkspace(entry, options?.workspaceId)) return null\n return entry.documentId\n}\n\nfunction inWorkspace(entry: Entry, workspaceId: string | null | undefined): boolean {\n const own = entry.current().workspaceId\n return !workspaceId || !own || own === workspaceId\n}\n\n/** What a turn is about to be sent in: its conversation and the document its thread is bound to. */\nexport interface TurnDocumentInput {\n /** The thread's bound document (`threadDocumentId` / the session's `newChatDocumentId`). */\n boundDocumentId: string | null | undefined\n /** The conversation (null: a new chat). */\n conversationId: string | null | undefined\n /** The chat's workspace: an open document of another workspace is never picked up. */\n workspaceId?: string | null\n}\n\n/** The document a turn drafts in, and the open viewer showing it (if one is). */\nfunction pickTurnDocument({\n boundDocumentId,\n conversationId,\n workspaceId,\n}: TurnDocumentInput): { documentId: string; entry: Entry | undefined } | null {\n // A bound thread names its document on every turn, open or not.\n if (boundDocumentId) {\n const entry = [...entries].reverse().find((e) => e.documentId === boundDocumentId)\n return { documentId: boundDocumentId, entry }\n }\n // Unbound: only a document made in this thread, or an ambient one (an email draft).\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i]\n if (!inWorkspace(entry, workspaceId)) continue\n const { ambient, conversationId: madeIn } = entry.current()\n if (ambient || (conversationId && madeIn === conversationId))\n return { documentId: entry.documentId, entry }\n }\n return null\n}\n\n/** The document a turn sent now would draft in, or null. Re-renders as documents open and close. */\nexport function useTurnDocumentId(input: TurnDocumentInput): string | null {\n const { boundDocumentId = null, conversationId = null, workspaceId = null } = input\n return useSyncExternalStore(\n subscribe,\n () => pickTurnDocument({ boundDocumentId, conversationId, workspaceId })?.documentId ?? null,\n () => null\n )\n}\n\n/**\n * The document an assistant turn about to be sent drafts in, or null. Call it once per turn as the\n * question is sent: when an earlier version of the document is on screen, the viewer returns to the\n * live document, where the assistant's edits appear.\n */\nexport function takeDocumentForTurn(input: TurnDocumentInput): string | null {\n const picked = pickTurnDocument(input)\n if (!picked) return null\n const { documentId, entry } = picked\n if (entry) {\n const { shownId, showLive } = entry.current()\n if (shownId && shownId !== documentId && parseVersionRef(shownId).docId === documentId)\n showLive?.()\n }\n return documentId\n}\n","/**\n * A thread's document: the one document a conversation drafts in, part of the conversation.\n *\n * A thread is bound to a document only when it was started from it (\"Chat about this document\" in\n * the viewer) or the person attached it in that thread. Only that thread names it on its turns\n * (`active_artifact_ext_id`), on every turn and after a reload. A document merely open or docked\n * beside the chat binds nothing: a new chat (the ask bar, the new-chat button, the thread\n * launcher, home) starts unbound, so a question there never becomes an edit of whatever is open.\n *\n * The binding is the server's: the conversation's `bound_document_ext_id`, set by the first turn\n * (`bound_document_ext_id` on the turn that starts it) or by a PATCH, and read under each reader's\n * access (`bound_document_unavailable`: bound to a document this reader cannot open). It follows\n * the person to every device, and a shared thread's members all see it. The query cache holds it\n * (`./thread-binding`); a new chat's binding is the session's `newChatDocumentId` until its first\n * turn creates the conversation.\n *\n * This module is the light half (no query client, no SDK), so the shell entry can carry it.\n */\n\n/** What a conversation row says about its binding. */\nexport interface ThreadBindingRow {\n external_id: string\n bound_document_ext_id?: string | null\n bound_document_unavailable?: boolean | null\n updated_at?: string | null\n}\n\n/** A conversation's binding as this reader sees it. */\nexport interface ThreadBinding {\n /** The bound document, or null (unbound, or bound to one this reader cannot open). */\n documentId: string | null\n /** Bound to a document this reader cannot open (another member's private document, or deleted). */\n unavailable: boolean\n}\n\nexport const UNBOUND: ThreadBinding = { documentId: null, unavailable: false }\n\n/** A row's binding. */\nexport function bindingOfRow(row: ThreadBindingRow | null | undefined): ThreadBinding {\n if (!row) return UNBOUND\n const documentId = row.bound_document_ext_id ?? null\n return { documentId, unavailable: !documentId && row.bound_document_unavailable === true }\n}\n\n/** The most recently active conversation bound to a document, among `conversations`, or null. */\nexport function latestThreadOfDocument(\n conversations: readonly ThreadBindingRow[] | null | undefined,\n documentId: string\n): string | null {\n let latest: ThreadBindingRow | null = null\n for (const row of conversations ?? []) {\n if (row.bound_document_ext_id !== documentId) continue\n if (!latest || (row.updated_at ?? '') > (latest.updated_at ?? '')) latest = row\n }\n return latest?.external_id ?? null\n}\n\n// --------------------------------------------------------------------------------------------- //\n// Bindings this browser kept before the server held them (`localStorage`), moved to the server\n// once (`migrateLegacyThreadDocuments` in `./thread-binding`) and then forgotten.\n// --------------------------------------------------------------------------------------------- //\n\nexport const LEGACY_THREAD_DOCUMENTS_KEY = 'arbi-thread-documents'\n\nfunction storage(): Storage | undefined {\n try {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n } catch {\n return undefined\n }\n}\n\n/** The bindings this browser kept locally (conversation id → document id); empty when none. */\nexport function readLegacyThreadDocuments(): Record<string, string> {\n const out: Record<string, string> = {}\n try {\n const parsed = JSON.parse(storage()?.getItem(LEGACY_THREAD_DOCUMENTS_KEY) ?? 'null') as unknown\n if (parsed && typeof parsed === 'object')\n for (const [conversationId, documentId] of Object.entries(parsed))\n if (typeof documentId === 'string') out[conversationId] = documentId\n } catch {\n // Damaged or blocked: nothing to move.\n }\n return out\n}\n\n/** Forget locally kept bindings (moved to the server); the key goes with the last of them. */\nexport function forgetLegacyThreadDocuments(conversationIds: readonly string[]): void {\n if (conversationIds.length === 0) return\n const rest = readLegacyThreadDocuments()\n conversationIds.forEach((id) => delete rest[id])\n try {\n if (Object.keys(rest).length === 0) storage()?.removeItem(LEGACY_THREAD_DOCUMENTS_KEY)\n else storage()?.setItem(LEGACY_THREAD_DOCUMENTS_KEY, JSON.stringify(rest))\n } catch {\n // Blocked: nothing more to do.\n }\n}\n"]}
|