@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/open-document.ts"],
|
|
4
|
-
"sourcesContent": ["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-\u2026`), 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 return !!doc && (doc.wp_type === 'artifact' || !!doc.file_name?.toLowerCase().endsWith('.docx'))\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-\u2026`); 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-\u2026@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"],
|
|
5
|
-
"mappings": "AAAA,SAAS,WAAW,QAAQ,4BAA4B;AACxD,SAAS,uBAAuB;AAwDzB,SAAS,YAAY,KAAmD;AAC7E,
|
|
4
|
+
"sourcesContent": ["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-\u2026`), 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-\u2026`); 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-\u2026@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"],
|
|
5
|
+
"mappings": "AAAA,SAAS,WAAW,QAAQ,4BAA4B;AACxD,SAAS,uBAAuB;AAwDzB,SAAS,YAAY,KAAmD;AAC7E,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,QAAQ,IAAI,aAAa,IAAI,YAAY;AAC/C,MAAI,KAAK,SAAS,OAAO,EAAG,QAAO;AAGnC,SACE,IAAI,YAAY,eACf,CAAC,eAAe,KAAK,IAAI,KAAK,oCAAoC,KAAK,IAAI;AAEhF;AAGO,MAAM,cAAc,CAAC,QAC1B,CAAC,CAAC,KAAK,WAAW,YAAY,EAAE,SAAS,OAAO;AAM3C,SAAS,mBAAmB,OAA0C;AAC3E,QAAM,EAAE,YAAY,SAAS,aAAa,gBAAgB,aAAa,IAAI;AAC3E,MAAI,CAAC,cAAc,WAAW,eAAe,eAAgB,QAAO;AACpE,MAAI,CAAC,gBAAgB,EAAE,YAAY,YAAY,KAAK,YAAY,YAAY,GAAI,QAAO;AAEvF,MAAI,aAAa,gBAAgB,WAAY,QAAO;AACpD,SAAO;AACT;AAyBA,IAAI,UAAmB,CAAC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B;AAAA,EACA;AAAA,EACA;AACF,GAA+E;AAE7E,MAAI,iBAAiB;AACnB,UAAM,QAAQ,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,MAAM,EAAE,eAAe,eAAe;AACjF,WAAO,EAAE,YAAY,iBAAiB,MAAM;AAAA,EAC9C;AAEA,WAAS,IAAI,QAAQ,SAAS,GAAG,KAAK,GAAG,KAAK;AAC5C,UAAM,QAAQ,QAAQ,CAAC;AACvB,QAAI,CAAC,YAAY,OAAO,WAAW,EAAG;AACtC,UAAM,EAAE,SAAS,gBAAgB,OAAO,IAAI,MAAM,QAAQ;AAC1D,QAAI,WAAY,kBAAkB,WAAW;AAC3C,aAAO,EAAE,YAAY,MAAM,YAAY,MAAM;AAAA,EACjD;AACA,SAAO;AACT;AAGO,SAAS,kBAAkB,OAAyC;AACzE,QAAM,EAAE,kBAAkB,MAAM,iBAAiB,MAAM,cAAc,KAAK,IAAI;AAC9E,SAAO;AAAA,IACL;AAAA,IACA,MAAM,iBAAiB,EAAE,iBAAiB,gBAAgB,YAAY,CAAC,GAAG,cAAc;AAAA,IACxF,MAAM;AAAA,EACR;AACF;AAOO,SAAS,oBAAoB,OAAyC;AAC3E,QAAM,SAAS,iBAAiB,KAAK;AACrC,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,EAAE,YAAY,MAAM,IAAI;AAC9B,MAAI,OAAO;AACT,UAAM,EAAE,SAAS,SAAS,IAAI,MAAM,QAAQ;AAC5C,QAAI,WAAW,YAAY,cAAc,gBAAgB,OAAO,EAAE,UAAU;AAC1E,iBAAW;AAAA,EACf;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { notify } from "../shell/index.js";
|
|
2
|
+
import { AGENT_CONTROL_COMMANDS } from "./turn-control.js";
|
|
3
|
+
const STATUS_WAIT_MS = 1e4;
|
|
4
|
+
async function requestAgentStatus(arbi, session, responseId, command = AGENT_CONTROL_COMMANDS.report) {
|
|
5
|
+
if (session.getState().agentProbePending[responseId]) return;
|
|
6
|
+
session.setAgentProbePending(responseId, true);
|
|
7
|
+
let waiting = true;
|
|
8
|
+
const finish = () => {
|
|
9
|
+
if (!waiting) return false;
|
|
10
|
+
waiting = false;
|
|
11
|
+
clearTimeout(timer);
|
|
12
|
+
unsubscribe();
|
|
13
|
+
return true;
|
|
14
|
+
};
|
|
15
|
+
const timer = setTimeout(() => {
|
|
16
|
+
if (!finish()) return;
|
|
17
|
+
session.setAgentProbePending(responseId, false);
|
|
18
|
+
notify.warning("No status update received yet. You can ask for status again.");
|
|
19
|
+
}, STATUS_WAIT_MS);
|
|
20
|
+
const unsubscribe = session.subscribe(() => {
|
|
21
|
+
if (!session.getState().agentProbePending[responseId]) finish();
|
|
22
|
+
});
|
|
23
|
+
try {
|
|
24
|
+
await arbi.assistant.interject(responseId, command);
|
|
25
|
+
} catch {
|
|
26
|
+
if (!finish()) return;
|
|
27
|
+
session.setAgentProbePending(responseId, false);
|
|
28
|
+
notify.error("Could not request a status update. Please try again.");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export {
|
|
32
|
+
requestAgentStatus
|
|
33
|
+
};
|
|
34
|
+
//# sourceMappingURL=request-agent-status.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/chat/request-agent-status.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Arbi } from '@arbidocs/sdk/browser'\nimport type { ArbiSessionStore } from '../session/store'\nimport { notify } from '../shell'\nimport { AGENT_CONTROL_COMMANDS } from './turn-control'\n\n/** Stop showing an indefinite status check; a late reply can still arrive on the run's stream. */\nconst STATUS_WAIT_MS = 10_000\n\n/** Shared by the turn menu and the composer's /report command. Delivery is not the reply. */\nexport async function requestAgentStatus(\n arbi: Arbi,\n session: ArbiSessionStore,\n responseId: string,\n command: string = AGENT_CONTROL_COMMANDS.report\n): Promise<void> {\n if (session.getState().agentProbePending[responseId]) return\n session.setAgentProbePending(responseId, true)\n\n let waiting = true\n const finish = () => {\n if (!waiting) return false\n waiting = false\n clearTimeout(timer)\n unsubscribe()\n return true\n }\n const timer = setTimeout(() => {\n if (!finish()) return\n session.setAgentProbePending(responseId, false)\n notify.warning('No status update received yet. You can ask for status again.')\n }, STATUS_WAIT_MS)\n // A reply, turn completion or session reset owns cleanup, even if delivery is still in flight.\n const unsubscribe = session.subscribe(() => {\n if (!session.getState().agentProbePending[responseId]) finish()\n })\n\n try {\n await arbi.assistant.interject(responseId, command)\n } catch {\n // A timed-out request can fail after a retry started. It must not clear the new request.\n if (!finish()) return\n session.setAgentProbePending(responseId, false)\n notify.error('Could not request a status update. Please try again.')\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,cAAc;AACvB,SAAS,8BAA8B;AAGvC,MAAM,iBAAiB;AAGvB,eAAsB,mBACpB,MACA,SACA,YACA,UAAkB,uBAAuB,QAC1B;AACf,MAAI,QAAQ,SAAS,EAAE,kBAAkB,UAAU,EAAG;AACtD,UAAQ,qBAAqB,YAAY,IAAI;AAE7C,MAAI,UAAU;AACd,QAAM,SAAS,MAAM;AACnB,QAAI,CAAC,QAAS,QAAO;AACrB,cAAU;AACV,iBAAa,KAAK;AAClB,gBAAY;AACZ,WAAO;AAAA,EACT;AACA,QAAM,QAAQ,WAAW,MAAM;AAC7B,QAAI,CAAC,OAAO,EAAG;AACf,YAAQ,qBAAqB,YAAY,KAAK;AAC9C,WAAO,QAAQ,8DAA8D;AAAA,EAC/E,GAAG,cAAc;AAEjB,QAAM,cAAc,QAAQ,UAAU,MAAM;AAC1C,QAAI,CAAC,QAAQ,SAAS,EAAE,kBAAkB,UAAU,EAAG,QAAO;AAAA,EAChE,CAAC;AAED,MAAI;AACF,UAAM,KAAK,UAAU,UAAU,YAAY,OAAO;AAAA,EACpD,QAAQ;AAEN,QAAI,CAAC,OAAO,EAAG;AACf,YAAQ,qBAAqB,YAAY,KAAK;AAC9C,WAAO,MAAM,sDAAsD;AAAA,EACrE;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -3,6 +3,7 @@ import { refreshDocuments } from "../documents/documents-data.js";
|
|
|
3
3
|
import { applyConversationEvent } from "./conversation-events.js";
|
|
4
4
|
import { cachedQuotaUsedUp } from "./turn-control.js";
|
|
5
5
|
function applyRunFinished(queryClient, arbi, session, message, onQuotaExceeded) {
|
|
6
|
+
session.clearAgentControl(message.response_id);
|
|
6
7
|
const { generating } = session.getState();
|
|
7
8
|
const streaming = Object.entries(generating).find(
|
|
8
9
|
([, generation]) => generation.streamingAssistantId === message.response_id
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/chat/run-finished.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * A run that finished on the server (`response_complete` on the WebSocket), applied by every site:\n * the session side and the cache side of `applyConversationEvent`. `ArbiWebSocketProvider` applies\n * it itself.\n *\n * The run is matched to the conversation whose answer is streaming under its id, else the\n * conversation the event names (a run the server started: a queued follow-up, a background task).\n * That conversation stops generating, the follow-up it answered leaves the queue box, the documents\n * a background run saved are read again (it has no foreground stream to bring them), and the thread,\n * its follow-up, the list and the usage follow. A run that failed because the project's AI usage is\n * used up is reported to `onQuotaExceeded` (the chat host's, as a failed stream is).\n */\nimport type { QueryClient } from '@tanstack/react-query'\nimport type { Arbi, QuotaExceeded } from '@arbidocs/sdk/browser'\nimport { logger, type WsResponseCompleteMessage } from '@arbidocs/client'\nimport type { ArbiSessionStore } from '../session/store'\nimport { refreshDocuments } from '../documents/documents-data'\nimport { applyConversationEvent } from './conversation-events'\nimport { cachedQuotaUsedUp } from './turn-control'\n\nexport function applyRunFinished(\n queryClient: QueryClient,\n arbi: Arbi,\n session: Pick<\n ArbiSessionStore,\n 'getState' | 'setConversationGenerating' | 'removeQueuedMessageByServerId'\n >,\n message: WsResponseCompleteMessage,\n onQuotaExceeded?: (quota: QuotaExceeded) => void\n): void {\n const { generating } = session.getState()\n const streaming = Object.entries(generating).find(\n ([, generation]) => generation.streamingAssistantId === message.response_id\n )?.[0]\n const conversationId = streaming ?? message.conversation_ext_id ?? null\n if (!conversationId) return\n\n session.setConversationGenerating(conversationId, false, null)\n if (message.doc_ext_ids?.length) {\n refreshDocuments(queryClient, arbi, message.doc_ext_ids).catch((error) =>\n logger.error('[WebSocket] Failed to refresh task outputs:', error)\n )\n }\n if (message.user_message_id) session.removeQueuedMessageByServerId(message.user_message_id)\n void applyConversationEvent(queryClient, { ...message, conversation_ext_id: conversationId })\n if (message.status === 'failed') {\n const quota = cachedQuotaUsedUp(queryClient, session.getState().workspaceId)\n if (quota) onQuotaExceeded?.(quota)\n }\n}\n"],
|
|
5
|
-
"mappings": "AAcA,SAAS,cAA8C;AAEvD,SAAS,wBAAwB;AACjC,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAE3B,SAAS,iBACd,aACA,MACA,SAIA,SACA,iBACM;AACN,QAAM,EAAE,WAAW,IAAI,QAAQ,SAAS;AACxC,QAAM,YAAY,OAAO,QAAQ,UAAU,EAAE;AAAA,IAC3C,CAAC,CAAC,EAAE,UAAU,MAAM,WAAW,yBAAyB,QAAQ;AAAA,EAClE,IAAI,CAAC;AACL,QAAM,iBAAiB,aAAa,QAAQ,uBAAuB;AACnE,MAAI,CAAC,eAAgB;AAErB,UAAQ,0BAA0B,gBAAgB,OAAO,IAAI;AAC7D,MAAI,QAAQ,aAAa,QAAQ;AAC/B,qBAAiB,aAAa,MAAM,QAAQ,WAAW,EAAE;AAAA,MAAM,CAAC,UAC9D,OAAO,MAAM,+CAA+C,KAAK;AAAA,IACnE;AAAA,EACF;AACA,MAAI,QAAQ,gBAAiB,SAAQ,8BAA8B,QAAQ,eAAe;AAC1F,OAAK,uBAAuB,aAAa,EAAE,GAAG,SAAS,qBAAqB,eAAe,CAAC;AAC5F,MAAI,QAAQ,WAAW,UAAU;AAC/B,UAAM,QAAQ,kBAAkB,aAAa,QAAQ,SAAS,EAAE,WAAW;AAC3E,QAAI,MAAO,mBAAkB,KAAK;AAAA,EACpC;AACF;",
|
|
4
|
+
"sourcesContent": ["/**\n * A run that finished on the server (`response_complete` on the WebSocket), applied by every site:\n * the session side and the cache side of `applyConversationEvent`. `ArbiWebSocketProvider` applies\n * it itself.\n *\n * The run is matched to the conversation whose answer is streaming under its id, else the\n * conversation the event names (a run the server started: a queued follow-up, a background task).\n * That conversation stops generating, the follow-up it answered leaves the queue box, the documents\n * a background run saved are read again (it has no foreground stream to bring them), and the thread,\n * its follow-up, the list and the usage follow. A run that failed because the project's AI usage is\n * used up is reported to `onQuotaExceeded` (the chat host's, as a failed stream is).\n */\nimport type { QueryClient } from '@tanstack/react-query'\nimport type { Arbi, QuotaExceeded } from '@arbidocs/sdk/browser'\nimport { logger, type WsResponseCompleteMessage } from '@arbidocs/client'\nimport type { ArbiSessionStore } from '../session/store'\nimport { refreshDocuments } from '../documents/documents-data'\nimport { applyConversationEvent } from './conversation-events'\nimport { cachedQuotaUsedUp } from './turn-control'\n\nexport function applyRunFinished(\n queryClient: QueryClient,\n arbi: Arbi,\n session: Pick<\n ArbiSessionStore,\n 'getState' | 'setConversationGenerating' | 'removeQueuedMessageByServerId' | 'clearAgentControl'\n >,\n message: WsResponseCompleteMessage,\n onQuotaExceeded?: (quota: QuotaExceeded) => void\n): void {\n session.clearAgentControl(message.response_id)\n const { generating } = session.getState()\n const streaming = Object.entries(generating).find(\n ([, generation]) => generation.streamingAssistantId === message.response_id\n )?.[0]\n const conversationId = streaming ?? message.conversation_ext_id ?? null\n if (!conversationId) return\n\n session.setConversationGenerating(conversationId, false, null)\n if (message.doc_ext_ids?.length) {\n refreshDocuments(queryClient, arbi, message.doc_ext_ids).catch((error) =>\n logger.error('[WebSocket] Failed to refresh task outputs:', error)\n )\n }\n if (message.user_message_id) session.removeQueuedMessageByServerId(message.user_message_id)\n void applyConversationEvent(queryClient, { ...message, conversation_ext_id: conversationId })\n if (message.status === 'failed') {\n const quota = cachedQuotaUsedUp(queryClient, session.getState().workspaceId)\n if (quota) onQuotaExceeded?.(quota)\n }\n}\n"],
|
|
5
|
+
"mappings": "AAcA,SAAS,cAA8C;AAEvD,SAAS,wBAAwB;AACjC,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAE3B,SAAS,iBACd,aACA,MACA,SAIA,SACA,iBACM;AACN,UAAQ,kBAAkB,QAAQ,WAAW;AAC7C,QAAM,EAAE,WAAW,IAAI,QAAQ,SAAS;AACxC,QAAM,YAAY,OAAO,QAAQ,UAAU,EAAE;AAAA,IAC3C,CAAC,CAAC,EAAE,UAAU,MAAM,WAAW,yBAAyB,QAAQ;AAAA,EAClE,IAAI,CAAC;AACL,QAAM,iBAAiB,aAAa,QAAQ,uBAAuB;AACnE,MAAI,CAAC,eAAgB;AAErB,UAAQ,0BAA0B,gBAAgB,OAAO,IAAI;AAC7D,MAAI,QAAQ,aAAa,QAAQ;AAC/B,qBAAiB,aAAa,MAAM,QAAQ,WAAW,EAAE;AAAA,MAAM,CAAC,UAC9D,OAAO,MAAM,+CAA+C,KAAK;AAAA,IACnE;AAAA,EACF;AACA,MAAI,QAAQ,gBAAiB,SAAQ,8BAA8B,QAAQ,eAAe;AAC1F,OAAK,uBAAuB,aAAa,EAAE,GAAG,SAAS,qBAAqB,eAAe,CAAC;AAC5F,MAAI,QAAQ,WAAW,UAAU;AAC/B,UAAM,QAAQ,kBAAkB,aAAa,QAAQ,SAAS,EAAE,WAAW;AAC3E,QAAI,MAAO,mBAAkB,KAAK;AAAA,EACpC;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -2,6 +2,7 @@ import { useCallback } from "react";
|
|
|
2
2
|
import { useArbi } from "../useArbi.js";
|
|
3
3
|
import { useArbiSessionStore } from "../session/index.js";
|
|
4
4
|
import { AGENT_CONTROL_COMMANDS } from "./turn-control.js";
|
|
5
|
+
import { requestAgentStatus } from "./request-agent-status.js";
|
|
5
6
|
function useAgentRunControl(assistantMessageExtId) {
|
|
6
7
|
const arbi = useArbi();
|
|
7
8
|
const session = useArbiSessionStore();
|
|
@@ -25,9 +26,8 @@ function useAgentRunControl(assistantMessageExtId) {
|
|
|
25
26
|
}, [assistantMessageExtId, session, send]);
|
|
26
27
|
const report = useCallback(() => {
|
|
27
28
|
if (!assistantMessageExtId) return;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}, [assistantMessageExtId, session, send]);
|
|
29
|
+
void requestAgentStatus(arbi, session, assistantMessageExtId);
|
|
30
|
+
}, [assistantMessageExtId, arbi, session]);
|
|
31
31
|
return { pause, resume, report };
|
|
32
32
|
}
|
|
33
33
|
export {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/chat/useAgentRunControl.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Run-control commands to a running agent turn. Choosing Pause in the turn bar's menu and typing\n * `/pause` in the composer are the same act: both send the command's text as an interjection\n * (`arbi.assistant.interject`), and the backend dispatches it. There is no dedicated control\n * endpoint; the menu is a shortcut for the slash command.\n *\n * Each action also sets an optimistic state in the session, because the loop only confirms at its\n * next boundary (`paused` / `running`) and a probe answers in the background. The\n * `arbi.agent_control_state` and `arbi.probe_answer` events then confirm or correct it.\n */\n\nimport { useCallback } from 'react'\nimport { useArbi } from '../useArbi'\nimport { useArbiSessionStore } from '../session'\nimport { AGENT_CONTROL_COMMANDS } from './turn-control'\n\nexport function useAgentRunControl(assistantMessageExtId: string | null) {\n const arbi = useArbi()\n const session = useArbiSessionStore()\n\n const send = useCallback(\n (command: string) => {\n if (!assistantMessageExtId) return\n // Fire and forget: the control events confirm or correct the optimistic state.\n void arbi.assistant.interject(assistantMessageExtId, command).catch(() => {})\n },\n [assistantMessageExtId, arbi]\n )\n\n const pause = useCallback(() => {\n if (!assistantMessageExtId) return\n session.setAgentControlState(assistantMessageExtId, 'pausing')\n send(AGENT_CONTROL_COMMANDS.pause)\n }, [assistantMessageExtId, session, send])\n\n const resume = useCallback(() => {\n if (!assistantMessageExtId) return\n session.setAgentControlState(assistantMessageExtId, 'resuming')\n send(AGENT_CONTROL_COMMANDS.resume)\n }, [assistantMessageExtId, session, send])\n\n const report = useCallback(() => {\n if (!assistantMessageExtId) return\n
|
|
5
|
-
"mappings": "AAWA,SAAS,mBAAmB;AAC5B,SAAS,eAAe;AACxB,SAAS,2BAA2B;AACpC,SAAS,8BAA8B;
|
|
4
|
+
"sourcesContent": ["/**\n * Run-control commands to a running agent turn. Choosing Pause in the turn bar's menu and typing\n * `/pause` in the composer are the same act: both send the command's text as an interjection\n * (`arbi.assistant.interject`), and the backend dispatches it. There is no dedicated control\n * endpoint; the menu is a shortcut for the slash command.\n *\n * Each action also sets an optimistic state in the session, because the loop only confirms at its\n * next boundary (`paused` / `running`) and a probe answers in the background. The\n * `arbi.agent_control_state` and `arbi.probe_answer` events then confirm or correct it.\n */\n\nimport { useCallback } from 'react'\nimport { useArbi } from '../useArbi'\nimport { useArbiSessionStore } from '../session'\nimport { AGENT_CONTROL_COMMANDS } from './turn-control'\nimport { requestAgentStatus } from './request-agent-status'\n\nexport function useAgentRunControl(assistantMessageExtId: string | null) {\n const arbi = useArbi()\n const session = useArbiSessionStore()\n\n const send = useCallback(\n (command: string) => {\n if (!assistantMessageExtId) return\n // Fire and forget: the control events confirm or correct the optimistic state.\n void arbi.assistant.interject(assistantMessageExtId, command).catch(() => {})\n },\n [assistantMessageExtId, arbi]\n )\n\n const pause = useCallback(() => {\n if (!assistantMessageExtId) return\n session.setAgentControlState(assistantMessageExtId, 'pausing')\n send(AGENT_CONTROL_COMMANDS.pause)\n }, [assistantMessageExtId, session, send])\n\n const resume = useCallback(() => {\n if (!assistantMessageExtId) return\n session.setAgentControlState(assistantMessageExtId, 'resuming')\n send(AGENT_CONTROL_COMMANDS.resume)\n }, [assistantMessageExtId, session, send])\n\n const report = useCallback(() => {\n if (!assistantMessageExtId) return\n void requestAgentStatus(arbi, session, assistantMessageExtId)\n }, [assistantMessageExtId, arbi, session])\n\n return { pause, resume, report }\n}\n"],
|
|
5
|
+
"mappings": "AAWA,SAAS,mBAAmB;AAC5B,SAAS,eAAe;AACxB,SAAS,2BAA2B;AACpC,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AAE5B,SAAS,mBAAmB,uBAAsC;AACvE,QAAM,OAAO,QAAQ;AACrB,QAAM,UAAU,oBAAoB;AAEpC,QAAM,OAAO;AAAA,IACX,CAAC,YAAoB;AACnB,UAAI,CAAC,sBAAuB;AAE5B,WAAK,KAAK,UAAU,UAAU,uBAAuB,OAAO,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAC9E;AAAA,IACA,CAAC,uBAAuB,IAAI;AAAA,EAC9B;AAEA,QAAM,QAAQ,YAAY,MAAM;AAC9B,QAAI,CAAC,sBAAuB;AAC5B,YAAQ,qBAAqB,uBAAuB,SAAS;AAC7D,SAAK,uBAAuB,KAAK;AAAA,EACnC,GAAG,CAAC,uBAAuB,SAAS,IAAI,CAAC;AAEzC,QAAM,SAAS,YAAY,MAAM;AAC/B,QAAI,CAAC,sBAAuB;AAC5B,YAAQ,qBAAqB,uBAAuB,UAAU;AAC9D,SAAK,uBAAuB,MAAM;AAAA,EACpC,GAAG,CAAC,uBAAuB,SAAS,IAAI,CAAC;AAEzC,QAAM,SAAS,YAAY,MAAM;AAC/B,QAAI,CAAC,sBAAuB;AAC5B,SAAK,mBAAmB,MAAM,SAAS,qBAAqB;AAAA,EAC9D,GAAG,CAAC,uBAAuB,MAAM,OAAO,CAAC;AAEzC,SAAO,EAAE,OAAO,QAAQ,OAAO;AACjC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -109,6 +109,10 @@ function useAttachRun(conversationId, responseId) {
|
|
|
109
109
|
if (disposed) return;
|
|
110
110
|
session.setAgentControlState(responseId, event.state);
|
|
111
111
|
},
|
|
112
|
+
onProbeAnswer: (probe) => {
|
|
113
|
+
if (disposed) return;
|
|
114
|
+
session.setAgentProbeAnswer(responseId, probe);
|
|
115
|
+
},
|
|
112
116
|
// The authoritative message, and the only frame that carries the answer with its citation
|
|
113
117
|
// markers applied plus the `tools.model_citations` map they resolve through. The
|
|
114
118
|
// "Answered" item above carries the model's raw text, which predates both, so without
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/chat/useConnectRunStream.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * useConnectRunStream: connect a conversation view to the live stream of the run its conversation\n * shows as still running, when this client is not the one streaming it.\n *\n * There is no \"background run\" vs \"foreground run\": a run's output is one durable, reconnectable\n * event stream keyed by the response id, and the run exists independent of any viewer. This hook\n * attaches whenever an assistant message in the conversation is still `in_progress` (or `queued`)\n * but THIS client holds no local stream for it (a scheduled run, or the same account on another\n * device; see `getRunToAttach`). It replays what happened so far, then tails live frames, feeding\n * every one into the SAME state a local turn uses (the conversation cache and the session's\n * generation and control state), so it renders in the ordinary message timeline: steps, goal\n * banner, answer.\n *\n * Connect / disconnect freely: the run keeps going regardless. When the message flips to\n * `completed`, `settle` re-reads the authoritative row and this stream disconnects. Control (pause /\n * resume / message) is the reverse direction, keyed by the same response id via `interject`.\n *\n * The one thing this stream does NOT carry is token-by-token deltas (too heavy to buffer for\n * reconnect): the client that STARTED the turn keeps its inline stream for live typing; every other\n * viewer gets steps, goal and the final answer text.\n */\n\nimport { useEffect, useRef } from 'react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { getRunToAttach } from '@arbidocs/sdk/browser'\nimport { useArbi } from '../useArbi'\nimport { useArbiSessionState, useArbiSessionStore } from '../session'\nimport {\n applyOutputItemToMessage,\n clearLoadingState,\n completeQueuedUserMessageByContent,\n ensureAssistantMessageLoading,\n flushStreamingTokens,\n getInterjectionText,\n getRunStartedAt,\n getThreadsQueryKey,\n isMessageRunning,\n setMessageContent,\n updateMessageWithMetadata,\n} from './conversation-cache'\nimport { registerAttachedRun } from './turn-control'\n\n/** Wait this long before attaching again to a run whose stream ended while it still runs. */\nconst RECONNECT_DELAY_MS = 2000\n/** Attaches in a row, with no frame received in between, before the view stops trying. */\nconst MAX_RECONNECTS = 5\n\n/** The fields of a conversation's messages the attach reads. */\ninterface AttachMessage {\n external_id: string\n role: string\n status?: string | null\n}\n\n/**\n * Attach the conversation view to its running run, if it has one this client is not streaming.\n *\n * @param conversationId The open conversation, or null for none.\n * @param messages The messages on screen (the line being viewed).\n */\nexport function useConnectRunStream(\n conversationId: string | null,\n messages: readonly AttachMessage[]\n): void {\n const generation = useArbiSessionState((s) =>\n conversationId ? s.generating[conversationId] : undefined\n )\n const responseId = conversationId ? getRunToAttach(generation, messages) : null\n useAttachRun(conversationId, responseId)\n}\n\nfunction useAttachRun(conversationId: string | null, responseId: string | null): void {\n const queryClient = useQueryClient()\n const session = useArbiSessionStore()\n // Read when attaching: a renewed session (a new `arbi`) must not cut and re-open a live attach.\n const arbi = useArbi()\n const arbiRef = useRef(arbi)\n arbiRef.current = arbi\n\n useEffect(() => {\n if (!conversationId || !responseId) return\n\n // A `disposed` flag ignores a stale effect's callbacks; the AbortController actually closes its\n // connection. That matters: each open run stream holds one of the browser's few HTTP/1.1\n // connections to the origin, so a stream left running after its view went away starves every\n // later request (the page stalls on load). The StrictMode double-invoke aborts the first stream\n // and opens the second, which is the normal fetch lifecycle.\n let disposed = false\n // The current attach's connection (a re-attach after an early end opens a new one).\n let controller = new AbortController()\n let retryTimer: ReturnType<typeof setTimeout> | undefined\n let reconnects = 0\n\n // Leaving the view saves this run's start on its message timer. Reuse it: a re-attach after\n // navigating away must keep counting from the real start, not restart.\n const runStartedAt =\n session.getState().messageTimers[`${conversationId}:${responseId}`]?.startTime\n // Mark the conversation as generating (no abort controller: this client didn't start the run,\n // so there's nothing local to abort) and point the control bar at the run's answer.\n session.setConversationGenerating(conversationId, true, null)\n // Anchor the live timer at the run's own start: a reattach (e.g. after a reload) must not\n // restart \"Thinking 0s\" while the run has been going for minutes. Prefer the start this client\n // saved when it left; after a reload only the message's created_at is left.\n session.setStreamingAssistantId(\n conversationId,\n responseId,\n runStartedAt ?? getRunStartedAt(queryClient, conversationId, responseId) ?? Date.now()\n )\n\n // Settle the streaming state: stop showing the message as generating and drop the loading\n // flags so it renders normally. When `refetch`, also re-read the thread so the settled message\n // matches the server exactly: final content, status `completed` (which disconnects this\n // stream), and the persisted `stream_events`/`trace` hydrated into steps and goal banner (robust\n // even if the live replay window had already expired).\n const settle = (refetch: boolean) => {\n session.setConversationGenerating(conversationId, false, null)\n session.clearAgentControl(responseId)\n clearLoadingState(queryClient, conversationId)\n if (refetch) {\n void queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n }\n }\n\n // Give the live steps / answer a row to land on (idempotent: reuses the history row if the\n // run's answer is already loaded). A refetch drops the flag, so re-add it.\n const markLoading = () => ensureAssistantMessageLoading(queryClient, conversationId, responseId)\n\n // The stream ended without a final frame. That can be a stopped run, or a connection that\n // dropped while the run goes on. Re-read the thread: a message the server still reports as\n // running is attached again, not shown as finished with no answer. Otherwise it settles.\n const endedEarly = async () => {\n // Commit the streamed text still waiting for a frame before the re-read replaces the message:\n // painted afterwards, it would be appended to the content the server stored.\n flushStreamingTokens(queryClient)\n await queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n if (disposed) return\n if (\n isMessageRunning(queryClient, conversationId, responseId) &&\n reconnects < MAX_RECONNECTS\n ) {\n reconnects += 1\n markLoading()\n retryTimer = setTimeout(connect, RECONNECT_DELAY_MS)\n return\n }\n settle(false)\n // Gave up while the run still shows as running, most often because the connection is down (a\n // dropped connection leaves a local turn to this attach too). Try again once it is back: the\n // view does not attach the same run a second time on its own.\n if (isMessageRunning(queryClient, conversationId, responseId)) {\n window.removeEventListener('online', reconnectWhenOnline)\n window.addEventListener('online', reconnectWhenOnline, { once: true })\n }\n }\n\n const reconnectWhenOnline = () => {\n // A turn this client started meanwhile owns the conversation's stream: leave it be.\n if (disposed || session.getState().generating[conversationId]?.isGenerating) return\n reconnects = 0\n session.setConversationGenerating(conversationId, true, null)\n connect()\n }\n\n const connect = () => {\n markLoading()\n controller = new AbortController()\n // Whether this attach itself saw a final frame or an error (each ends the attach once).\n let ended = false\n arbiRef.current.assistant\n .attachRun(responseId, {\n signal: controller.signal,\n // The reconnect learns its conversation from the stream; we already know it, but assert\n // the match so a stray attach on a mismatched cache can't write to the wrong conversation.\n onUserMessage: (userMessage) => {\n if (disposed) return\n if (\n userMessage.conversation_ext_id &&\n userMessage.conversation_ext_id !== conversationId\n ) {\n disposed = true\n }\n },\n onOutputItemDone: (ev) => {\n if (disposed) return\n reconnects = 0\n applyOutputItemToMessage(queryClient, conversationId, responseId, ev)\n // A prompt queued on this run was steered into it: it is no longer waiting.\n const interjection = getInterjectionText(ev.item)\n if (interjection) {\n completeQueuedUserMessageByContent(queryClient, conversationId, interjection)\n session.consumeQueuedMessage(responseId, interjection)\n }\n // NON-DESTRUCTIVE reconnect. This path runs when a viewer (re)attaches to a run,\n // including a REMOUNT of the conversation mid-stream (navigate away and back). The\n // live token stream (the local ask) already wrote the streamed-so-far answer into the\n // cache, and that cache SURVIVES the remount. So on reconnect only ADD the final\n // answer, never clobber what's there: set the body ONLY from the terminal \"Answered\"\n // item, and never overwrite or clear on narration/steps.\n const item = ev.item as {\n type?: string\n arbi?: { label?: string }\n content?: Array<{ text?: string }>\n }\n if (item?.type === 'message' && item.arbi?.label === 'Answered') {\n const text = Array.isArray(item.content)\n ? item.content.map((c) => c.text ?? '').join('')\n : ''\n if (text) setMessageContent(queryClient, conversationId, responseId, text)\n }\n },\n onAgentControlState: (event) => {\n if (disposed) return\n // Server-confirmed pause/resume: overrides the optimistic click state.\n session.setAgentControlState(responseId, event.state)\n },\n // The authoritative message, and the only frame that carries the answer with its citation\n // markers applied plus the `tools.model_citations` map they resolve through. The\n // \"Answered\" item above carries the model's raw text, which predates both, so without\n // this an attacher rendered a citation-free answer. Relying on the settle(true) refetch\n // is not enough: the cleanup path settles WITHOUT a refetch, and sets `disposed` first,\n // so a viewer who leaves as the run ends never gets the reconciliation.\n onMetadata: (metadata) => {\n if (disposed) return\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...messageData } = metadata\n updateMessageWithMetadata(queryClient, conversationId, responseId, messageData)\n },\n // onTextDone intentionally omitted: it fires for EVERY settled message item (narration\n // included) and, being label-blind, would overwrite the streamed body. The terminal\n // answer is applied above from the \"Answered\" item, then replaced by the authoritative\n // metadata content in onMetadata.\n onComplete: () => {\n if (disposed) return\n ended = true\n flushStreamingTokens(queryClient)\n settle(true)\n },\n onError: () => {\n if (disposed) return\n ended = true\n // A 404 = the run is no longer active here. Read the thread again to see whether it has\n // finished or is still running elsewhere.\n void endedEarly()\n },\n })\n .then(() => {\n // The stream can also just end, with no final frame: a stopped (cancelled) run's replay\n // stops without `response.completed`. Re-read the thread so the message shows its real\n // status, and attach again if the server still runs it.\n if (disposed || ended) return\n void endedEarly()\n })\n .catch(() => {\n if (disposed) return\n void endedEarly()\n })\n }\n\n connect()\n\n // Stop: close the stream for good (no re-attach, even if the server has not caught up with the\n // cancel yet), and re-read the thread so the message shows how it ended.\n const stop = () => {\n if (disposed) return\n disposed = true\n clearTimeout(retryTimer)\n window.removeEventListener('online', reconnectWhenOnline)\n controller.abort()\n settle(true)\n }\n const unregister = registerAttachedRun(conversationId, responseId, stop)\n\n return () => {\n unregister()\n // Disconnecting (run finished, or navigated away) must settle the streaming flags, not just\n // stop listening: otherwise the message is stuck as an empty streaming target. Clear without\n // a refetch here (a completing run already refetched via onComplete; a nav-away needs none).\n disposed = true\n clearTimeout(retryTimer)\n window.removeEventListener('online', reconnectWhenOnline)\n controller.abort()\n settle(false)\n }\n }, [conversationId, responseId, queryClient, session])\n}\n"],
|
|
5
|
-
"mappings": "AAsBA,SAAS,WAAW,cAAc;AAClC,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B,S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MAAM;AACjB,aAAO,KAAK;AAAA,IACd;AAAA,EACF,GAAG,CAAC,gBAAgB,YAAY,aAAa,OAAO,CAAC;AACvD;",
|
|
4
|
+
"sourcesContent": ["/**\n * useConnectRunStream: connect a conversation view to the live stream of the run its conversation\n * shows as still running, when this client is not the one streaming it.\n *\n * There is no \"background run\" vs \"foreground run\": a run's output is one durable, reconnectable\n * event stream keyed by the response id, and the run exists independent of any viewer. This hook\n * attaches whenever an assistant message in the conversation is still `in_progress` (or `queued`)\n * but THIS client holds no local stream for it (a scheduled run, or the same account on another\n * device; see `getRunToAttach`). It replays what happened so far, then tails live frames, feeding\n * every one into the SAME state a local turn uses (the conversation cache and the session's\n * generation and control state), so it renders in the ordinary message timeline: steps, goal\n * banner, answer.\n *\n * Connect / disconnect freely: the run keeps going regardless. When the message flips to\n * `completed`, `settle` re-reads the authoritative row and this stream disconnects. Control (pause /\n * resume / message) is the reverse direction, keyed by the same response id via `interject`.\n *\n * The one thing this stream does NOT carry is token-by-token deltas (too heavy to buffer for\n * reconnect): the client that STARTED the turn keeps its inline stream for live typing; every other\n * viewer gets steps, goal and the final answer text.\n */\n\nimport { useEffect, useRef } from 'react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { getRunToAttach } from '@arbidocs/sdk/browser'\nimport { useArbi } from '../useArbi'\nimport { useArbiSessionState, useArbiSessionStore } from '../session'\nimport {\n applyOutputItemToMessage,\n clearLoadingState,\n completeQueuedUserMessageByContent,\n ensureAssistantMessageLoading,\n flushStreamingTokens,\n getInterjectionText,\n getRunStartedAt,\n getThreadsQueryKey,\n isMessageRunning,\n setMessageContent,\n updateMessageWithMetadata,\n} from './conversation-cache'\nimport { registerAttachedRun } from './turn-control'\n\n/** Wait this long before attaching again to a run whose stream ended while it still runs. */\nconst RECONNECT_DELAY_MS = 2000\n/** Attaches in a row, with no frame received in between, before the view stops trying. */\nconst MAX_RECONNECTS = 5\n\n/** The fields of a conversation's messages the attach reads. */\ninterface AttachMessage {\n external_id: string\n role: string\n status?: string | null\n}\n\n/**\n * Attach the conversation view to its running run, if it has one this client is not streaming.\n *\n * @param conversationId The open conversation, or null for none.\n * @param messages The messages on screen (the line being viewed).\n */\nexport function useConnectRunStream(\n conversationId: string | null,\n messages: readonly AttachMessage[]\n): void {\n const generation = useArbiSessionState((s) =>\n conversationId ? s.generating[conversationId] : undefined\n )\n const responseId = conversationId ? getRunToAttach(generation, messages) : null\n useAttachRun(conversationId, responseId)\n}\n\nfunction useAttachRun(conversationId: string | null, responseId: string | null): void {\n const queryClient = useQueryClient()\n const session = useArbiSessionStore()\n // Read when attaching: a renewed session (a new `arbi`) must not cut and re-open a live attach.\n const arbi = useArbi()\n const arbiRef = useRef(arbi)\n arbiRef.current = arbi\n\n useEffect(() => {\n if (!conversationId || !responseId) return\n\n // A `disposed` flag ignores a stale effect's callbacks; the AbortController actually closes its\n // connection. That matters: each open run stream holds one of the browser's few HTTP/1.1\n // connections to the origin, so a stream left running after its view went away starves every\n // later request (the page stalls on load). The StrictMode double-invoke aborts the first stream\n // and opens the second, which is the normal fetch lifecycle.\n let disposed = false\n // The current attach's connection (a re-attach after an early end opens a new one).\n let controller = new AbortController()\n let retryTimer: ReturnType<typeof setTimeout> | undefined\n let reconnects = 0\n\n // Leaving the view saves this run's start on its message timer. Reuse it: a re-attach after\n // navigating away must keep counting from the real start, not restart.\n const runStartedAt =\n session.getState().messageTimers[`${conversationId}:${responseId}`]?.startTime\n // Mark the conversation as generating (no abort controller: this client didn't start the run,\n // so there's nothing local to abort) and point the control bar at the run's answer.\n session.setConversationGenerating(conversationId, true, null)\n // Anchor the live timer at the run's own start: a reattach (e.g. after a reload) must not\n // restart \"Thinking 0s\" while the run has been going for minutes. Prefer the start this client\n // saved when it left; after a reload only the message's created_at is left.\n session.setStreamingAssistantId(\n conversationId,\n responseId,\n runStartedAt ?? getRunStartedAt(queryClient, conversationId, responseId) ?? Date.now()\n )\n\n // Settle the streaming state: stop showing the message as generating and drop the loading\n // flags so it renders normally. When `refetch`, also re-read the thread so the settled message\n // matches the server exactly: final content, status `completed` (which disconnects this\n // stream), and the persisted `stream_events`/`trace` hydrated into steps and goal banner (robust\n // even if the live replay window had already expired).\n const settle = (refetch: boolean) => {\n session.setConversationGenerating(conversationId, false, null)\n session.clearAgentControl(responseId)\n clearLoadingState(queryClient, conversationId)\n if (refetch) {\n void queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n }\n }\n\n // Give the live steps / answer a row to land on (idempotent: reuses the history row if the\n // run's answer is already loaded). A refetch drops the flag, so re-add it.\n const markLoading = () => ensureAssistantMessageLoading(queryClient, conversationId, responseId)\n\n // The stream ended without a final frame. That can be a stopped run, or a connection that\n // dropped while the run goes on. Re-read the thread: a message the server still reports as\n // running is attached again, not shown as finished with no answer. Otherwise it settles.\n const endedEarly = async () => {\n // Commit the streamed text still waiting for a frame before the re-read replaces the message:\n // painted afterwards, it would be appended to the content the server stored.\n flushStreamingTokens(queryClient)\n await queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n if (disposed) return\n if (\n isMessageRunning(queryClient, conversationId, responseId) &&\n reconnects < MAX_RECONNECTS\n ) {\n reconnects += 1\n markLoading()\n retryTimer = setTimeout(connect, RECONNECT_DELAY_MS)\n return\n }\n settle(false)\n // Gave up while the run still shows as running, most often because the connection is down (a\n // dropped connection leaves a local turn to this attach too). Try again once it is back: the\n // view does not attach the same run a second time on its own.\n if (isMessageRunning(queryClient, conversationId, responseId)) {\n window.removeEventListener('online', reconnectWhenOnline)\n window.addEventListener('online', reconnectWhenOnline, { once: true })\n }\n }\n\n const reconnectWhenOnline = () => {\n // A turn this client started meanwhile owns the conversation's stream: leave it be.\n if (disposed || session.getState().generating[conversationId]?.isGenerating) return\n reconnects = 0\n session.setConversationGenerating(conversationId, true, null)\n connect()\n }\n\n const connect = () => {\n markLoading()\n controller = new AbortController()\n // Whether this attach itself saw a final frame or an error (each ends the attach once).\n let ended = false\n arbiRef.current.assistant\n .attachRun(responseId, {\n signal: controller.signal,\n // The reconnect learns its conversation from the stream; we already know it, but assert\n // the match so a stray attach on a mismatched cache can't write to the wrong conversation.\n onUserMessage: (userMessage) => {\n if (disposed) return\n if (\n userMessage.conversation_ext_id &&\n userMessage.conversation_ext_id !== conversationId\n ) {\n disposed = true\n }\n },\n onOutputItemDone: (ev) => {\n if (disposed) return\n reconnects = 0\n applyOutputItemToMessage(queryClient, conversationId, responseId, ev)\n // A prompt queued on this run was steered into it: it is no longer waiting.\n const interjection = getInterjectionText(ev.item)\n if (interjection) {\n completeQueuedUserMessageByContent(queryClient, conversationId, interjection)\n session.consumeQueuedMessage(responseId, interjection)\n }\n // NON-DESTRUCTIVE reconnect. This path runs when a viewer (re)attaches to a run,\n // including a REMOUNT of the conversation mid-stream (navigate away and back). The\n // live token stream (the local ask) already wrote the streamed-so-far answer into the\n // cache, and that cache SURVIVES the remount. So on reconnect only ADD the final\n // answer, never clobber what's there: set the body ONLY from the terminal \"Answered\"\n // item, and never overwrite or clear on narration/steps.\n const item = ev.item as {\n type?: string\n arbi?: { label?: string }\n content?: Array<{ text?: string }>\n }\n if (item?.type === 'message' && item.arbi?.label === 'Answered') {\n const text = Array.isArray(item.content)\n ? item.content.map((c) => c.text ?? '').join('')\n : ''\n if (text) setMessageContent(queryClient, conversationId, responseId, text)\n }\n },\n onAgentControlState: (event) => {\n if (disposed) return\n // Server-confirmed pause/resume: overrides the optimistic click state.\n session.setAgentControlState(responseId, event.state)\n },\n onProbeAnswer: (probe) => {\n if (disposed) return\n session.setAgentProbeAnswer(responseId, probe)\n },\n // The authoritative message, and the only frame that carries the answer with its citation\n // markers applied plus the `tools.model_citations` map they resolve through. The\n // \"Answered\" item above carries the model's raw text, which predates both, so without\n // this an attacher rendered a citation-free answer. Relying on the settle(true) refetch\n // is not enough: the cleanup path settles WITHOUT a refetch, and sets `disposed` first,\n // so a viewer who leaves as the run ends never gets the reconciliation.\n onMetadata: (metadata) => {\n if (disposed) return\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...messageData } = metadata\n updateMessageWithMetadata(queryClient, conversationId, responseId, messageData)\n },\n // onTextDone intentionally omitted: it fires for EVERY settled message item (narration\n // included) and, being label-blind, would overwrite the streamed body. The terminal\n // answer is applied above from the \"Answered\" item, then replaced by the authoritative\n // metadata content in onMetadata.\n onComplete: () => {\n if (disposed) return\n ended = true\n flushStreamingTokens(queryClient)\n settle(true)\n },\n onError: () => {\n if (disposed) return\n ended = true\n // A 404 = the run is no longer active here. Read the thread again to see whether it has\n // finished or is still running elsewhere.\n void endedEarly()\n },\n })\n .then(() => {\n // The stream can also just end, with no final frame: a stopped (cancelled) run's replay\n // stops without `response.completed`. Re-read the thread so the message shows its real\n // status, and attach again if the server still runs it.\n if (disposed || ended) return\n void endedEarly()\n })\n .catch(() => {\n if (disposed) return\n void endedEarly()\n })\n }\n\n connect()\n\n // Stop: close the stream for good (no re-attach, even if the server has not caught up with the\n // cancel yet), and re-read the thread so the message shows how it ended.\n const stop = () => {\n if (disposed) return\n disposed = true\n clearTimeout(retryTimer)\n window.removeEventListener('online', reconnectWhenOnline)\n controller.abort()\n settle(true)\n }\n const unregister = registerAttachedRun(conversationId, responseId, stop)\n\n return () => {\n unregister()\n // Disconnecting (run finished, or navigated away) must settle the streaming flags, not just\n // stop listening: otherwise the message is stuck as an empty streaming target. Clear without\n // a refetch here (a completing run already refetched via onComplete; a nav-away needs none).\n disposed = true\n clearTimeout(retryTimer)\n window.removeEventListener('online', reconnectWhenOnline)\n controller.abort()\n settle(false)\n }\n }, [conversationId, responseId, queryClient, session])\n}\n"],
|
|
5
|
+
"mappings": "AAsBA,SAAS,WAAW,cAAc;AAClC,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B,SAAS,eAAe;AACxB,SAAS,qBAAqB,2BAA2B;AACzD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA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BAAgB,YAAY,aAAa,OAAO,CAAC;AACvD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -101,6 +101,9 @@ function useConversation(options = {}) {
|
|
|
101
101
|
useEffect(() => {
|
|
102
102
|
if (agentId && workspaceId && !conversationId) session.setNewAgentChat({ agentId, workspaceId });
|
|
103
103
|
}, [session, agentId, workspaceId, conversationId]);
|
|
104
|
+
const chatAgentId = useArbiSessionState(
|
|
105
|
+
(s) => agentId ?? (conversationId ? s.agentChatOwners[conversationId] : s.newAgentChat?.workspaceId === workspaceId ? s.newAgentChat?.agentId : void 0)
|
|
106
|
+
) ?? void 0;
|
|
104
107
|
const { data: docs = [], isLoading: isLoadingDocuments } = useDocuments(workspaceId);
|
|
105
108
|
const ordinaryHistory = useConversations(workspaceId, { enabled: !agentId, live: true });
|
|
106
109
|
const agentHistory = useAgentChats(agentId);
|
|
@@ -154,7 +157,7 @@ function useConversation(options = {}) {
|
|
|
154
157
|
const [isUploading, setIsUploading] = useState(false);
|
|
155
158
|
const [uploadError, setUploadError] = useState(null);
|
|
156
159
|
const [historyError, setHistoryError] = useState(null);
|
|
157
|
-
const scope = `${workspaceId ?? ""}:${
|
|
160
|
+
const scope = `${workspaceId ?? ""}:${chatAgentId ?? ""}`;
|
|
158
161
|
const [currentScope, setCurrentScope] = useState(scope);
|
|
159
162
|
if (currentScope !== scope) {
|
|
160
163
|
setCurrentScope(scope);
|
|
@@ -194,24 +197,24 @@ function useConversation(options = {}) {
|
|
|
194
197
|
];
|
|
195
198
|
}, [stored, conversationId, messages, titleLength, runTitles, isWorkspaceOwner]);
|
|
196
199
|
const selectedIds = useMemo(
|
|
197
|
-
() => (
|
|
198
|
-
[docs, deselected,
|
|
200
|
+
() => (chatAgentId ? [] : docs).map((d) => d.external_id).filter((id) => !!id && !deselected.has(id)),
|
|
201
|
+
[docs, deselected, chatAgentId]
|
|
199
202
|
);
|
|
200
203
|
const documents = useMemo(
|
|
201
|
-
() =>
|
|
204
|
+
() => chatAgentId ? stagedFiles.map((file) => ({ ...file, isSelected: !deselected.has(file.id) })) : docs.filter((d) => !!d.external_id).map((d) => ({
|
|
202
205
|
id: d.external_id,
|
|
203
206
|
name: d.file_name ?? d.external_id,
|
|
204
207
|
isSelected: !deselected.has(d.external_id)
|
|
205
208
|
})),
|
|
206
|
-
[docs, deselected,
|
|
209
|
+
[docs, deselected, chatAgentId, stagedFiles]
|
|
207
210
|
);
|
|
208
211
|
const withStagedFiles = useCallback(
|
|
209
212
|
(text) => {
|
|
210
213
|
const staged = stagedFiles.filter((file) => !deselected.has(file.id));
|
|
211
|
-
if (!
|
|
214
|
+
if (!chatAgentId || staged.length === 0) return text;
|
|
212
215
|
return text + "\n\nSource files staged in your sandbox:\n" + staged.map((file) => `${file.name}: ${file.id}`).join("\n");
|
|
213
216
|
},
|
|
214
|
-
[
|
|
217
|
+
[chatAgentId, stagedFiles, deselected]
|
|
215
218
|
);
|
|
216
219
|
const { handleSendMessage, handleCreateBranch } = actions;
|
|
217
220
|
const assistantName = useAssistantName();
|
|
@@ -367,8 +370,8 @@ function useConversation(options = {}) {
|
|
|
367
370
|
try {
|
|
368
371
|
const uploaded = [];
|
|
369
372
|
for (const file of files) {
|
|
370
|
-
if (
|
|
371
|
-
const staged = await arbi.agents.stageFile(
|
|
373
|
+
if (chatAgentId) {
|
|
374
|
+
const staged = await arbi.agents.stageFile(chatAgentId, file, file.name);
|
|
372
375
|
setStagedFiles((all) => [
|
|
373
376
|
...all.filter((existing) => existing.id !== staged.path),
|
|
374
377
|
{ id: staged.path, name: staged.name }
|
|
@@ -387,7 +390,7 @@ function useConversation(options = {}) {
|
|
|
387
390
|
setIsUploading(false);
|
|
388
391
|
}
|
|
389
392
|
},
|
|
390
|
-
[arbi, queryClient,
|
|
393
|
+
[arbi, queryClient, chatAgentId, workspaceId]
|
|
391
394
|
);
|
|
392
395
|
const runningAnswer = generation?.streamingAssistantId;
|
|
393
396
|
const queue = runningAnswer && queuedMessages[runningAnswer] || [];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/chat/useConversation.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `useConversation`: the chat engine as one hook, the controller behind a full-page (or docked)\n * assistant. It returns what a chat surface needs and no markup; `@arbidocs/blocks/chat`'s\n * `ChatPage` takes it as its `chat` prop:\n *\n * ```tsx\n * const chat = useConversation({ workspaceId })\n * <ChatPage chat={chat} aside={<WorkflowLauncher \u2026 />} />\n * ```\n *\n * It is the same engine the ARBI app runs: the open conversation is the session's\n * (`ArbiSessionState.conversationId`, its viewed line `cursor`), the messages are the conversation\n * cache's, a turn goes through `useConversationActions` (send, branch, retry, stop, follow-ups\n * queued or steered into a running turn, comments to the people in a shared thread), and a run\n * started elsewhere is attached live (`useConnectRunStream`). So every surface gets the agent's\n * steps, the branches of an edited question, and interjections.\n *\n * A surface that must keep its own open conversation, beside another chat on the same page, mounts\n * inside its own session scope (`<ConversationScope>`).\n */\n\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport type { AgentStepEvent, AskRequest, ChatMessage } from '@arbidocs/sdk/browser'\nimport { useArbi } from '../useArbi'\nimport { useAgentChats, useIsWorkspaceOwner } from '../workforce'\nimport { useConversations } from '../hooks'\nimport { refreshDocuments, useDocuments } from '../documents/documents-data'\nimport { removeConversationFromLists } from '../conversation-list'\nimport { useArbiSessionState, useArbiSessionStore } from '../session'\nimport { toChatCitations, type ArbiChatCitation } from './citations'\nimport {\n cacheAssistantMode,\n cachedAssistantMode,\n cachedMentionCandidates,\n isCommentToPeople,\n} from './conversation-mentions'\nimport { useAssistantName } from '../host/assistant-copy'\nimport { useConversationActions } from './useConversationActions'\nimport { useConversationData } from './useConversationData'\nimport { useBranchNavigation } from './useBranchNavigation'\nimport { useConnectRunStream } from './useConnectRunStream'\nimport type { QueuedMessage } from './run-state'\nimport { useWorkflowRunTitles, type WorkflowRunRow } from './workflow-run-titles'\n\nexport type { ArbiChatCitation, ArbiChatPassage } from './citations'\n\nexport type ArbiChatRole = 'user' | 'assistant'\nexport type ArbiChatMessageStatus = 'streaming' | 'complete' | 'error'\n\nexport interface ArbiChatMessage {\n mentions?: AskRequest['mentions']\n authorId?: string\n id: string\n role: ArbiChatRole\n /** Markdown for an assistant message, plain text for a user message. */\n content: string\n status: ArbiChatMessageStatus\n /** Why an assistant message failed. */\n error?: string\n /** Agent steps (tool calls, reasoning) the answer took. */\n stepCount?: number\n /** The answer's agent steps, live while it runs. */\n steps?: AgentStepEvent[]\n /** The sources behind `[statement](#cite-N)` marks in `content`. */\n citations?: ArbiChatCitation[]\n /** The reader stopped the answer; `content` is what had streamed. */\n stopped?: boolean\n /** The backend id of a finished assistant answer: what a follow-up chains from. */\n responseId?: string\n /**\n * A user message the server sent to start a workflow's step (its `tools.workflow_step`): the\n * step's id. A chat shows it as that step, not as the raw instruction.\n */\n workflowStep?: string\n /**\n * One of several versions of this message (an edited question, an answer asked again): which\n * one is shown (0-based) and how many there are. `switchBranch` shows another.\n */\n branch?: { index: number; count: number }\n}\n\n/** The workflow step a stored message starts (its `tools.workflow_step` marker), if any. */\nexport function workflowStepOf(tools: object | null | undefined): string | undefined {\n const marker = (tools as Record<string, unknown> | null | undefined)?.workflow_step as\n { workflow_step?: unknown } | undefined\n return typeof marker?.workflow_step === 'string' ? marker.workflow_step : undefined\n}\n\nexport interface ArbiChatThread {\n id: string\n /** The backend title, else the first question; empty until there is one. */\n title: string\n /**\n * Whether the viewer may delete it. Sharing is one-way: a shared conversation is the workspace's,\n * so only a workspace owner deletes it; its creator deletes it only while it is private.\n */\n canDelete: boolean\n}\n\nexport interface ArbiChatDocument {\n id: string\n name: string\n isSelected: boolean\n}\n\nexport interface UseConversationOptions {\n /** Use an owned agent's independent session, history and sandbox files. */\n agentId?: string\n /** The workspace to chat in (default: the session's). */\n workspaceId?: string\n /** Assistant configuration or model id every turn uses (default: the person's last one). */\n model?: string\n /** Longest auto-title in characters (used until the backend has titled the conversation). Default 48. */\n titleLength?: number\n}\n\nexport interface ArbiConversation {\n assistantMode: 'always' | 'mentioned'\n isUpdatingAssistantMode: boolean\n isPostingComment: boolean\n setAssistantMode: (mode: 'always' | 'mentioned') => Promise<void>\n threads: ArbiChatThread[]\n /** The open conversation's id, or `new` for a chat not sent yet. */\n activeThreadId: string\n /** The viewed line of the open conversation. */\n messages: ArbiChatMessage[]\n /** An answer is running in the open conversation. */\n isRunning: boolean\n /** The last turn failed (the message list also carries the failed message). */\n error: string | null\n /** A stored conversation's messages are loading. */\n isLoadingThread: boolean\n /** The conversation list is loading. */\n isLoadingThreads: boolean\n /** Deleting a conversation or changing its mode failed. */\n historyError: string | null\n documents: ArbiChatDocument[]\n isLoadingDocuments: boolean\n isUploading: boolean\n uploadError: string | null\n /**\n * Send a question, or a comment to the people in a shared thread. While an answer runs, the\n * question waits in the running turn's queue (`queue`) or steers it.\n */\n send: (text: string, options?: { mentions?: AskRequest['mentions'] }) => Promise<void>\n /** Send `text` while the answer runs: the agent takes it into the running turn or queues it. */\n interject: (text: string) => Promise<void>\n /** Follow-ups waiting for the running answer. */\n queue: readonly QueuedMessage[]\n /** Ask `text` again in place of the message after `parentId` (an edit): a new branch. */\n branch: (parentId: string | null, text: string) => Promise<void>\n /** Show another version of a branched message (`ArbiChatMessage.branch`). */\n switchBranch: (messageId: string, index: number) => void\n /** Re-ask the question whose answer failed. */\n retry: () => Promise<void>\n /** Stop the running answer; what streamed so far stays, marked stopped. */\n stop: () => void\n selectThread: (id: string) => void\n newThread: () => void\n /** Deletes the conversation on the backend too. */\n deleteThread: (id: string) => void\n toggleDocument: (id: string) => void\n selectAllDocuments: () => void\n upload: (files: File[]) => Promise<void>\n}\n\n/** First words of a question as a title: whole words, no trailing punctuation, ellipsis when cut. */\nexport function titleFromQuestion(question: string, maxLength = 48): string {\n const flat = question.replace(/\\s+/g, ' ').trim()\n if (flat.length <= maxLength) return flat\n const cut = flat.slice(0, maxLength)\n const lastSpace = cut.lastIndexOf(' ')\n const words = lastSpace > maxLength / 2 ? cut.slice(0, lastSpace) : cut\n return `${words.replace(/[\\s,;:.\\-\u2013\u2014]+$/, '')}\u2026`\n}\n\nconst FAILED_MESSAGE = 'The assistant request failed.'\nconst UNFINISHED_MESSAGE = 'The answer did not finish. Try again.'\nconst NEW = 'new'\n/** No conversation rows (a stable empty list). */\nconst NO_ROWS: readonly WorkflowRunRow[] = []\n\nconst messageOf = (e: unknown, fallback: string) => (e instanceof Error ? e.message : fallback)\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/** A message of the conversation cache as the chat surface shows it. */\nfunction toChatMessage(m: ChatMessage, branch: ArbiChatMessage['branch']): ArbiChatMessage | null {\n if (m.role === 'system') return null\n const running = m.isLoading === true || m.status === 'in_progress' || m.status === 'queued'\n if (m.role === 'user') {\n if (!m.content.trim()) return null\n const workflowStep = workflowStepOf(m.tools)\n return {\n id: m.external_id,\n role: 'user',\n content: m.content,\n status: 'complete',\n ...(workflowStep ? { workflowStep } : {}),\n ...(m.created_by_ext_id ? { authorId: m.created_by_ext_id } : {}),\n ...(m.mentions?.length ? { mentions: m.mentions as AskRequest['mentions'] } : {}),\n ...(branch ? { branch } : {}),\n }\n }\n const failed = m.status === 'failed' || m.isError === true\n const stopped = m.status === 'cancelled'\n if (!m.content.trim() && !running && !failed && !stopped) return null\n const citations = toChatCitations({ tools: m.tools })\n const steps = m.agentSteps ?? []\n return {\n id: m.external_id,\n role: 'assistant',\n content: m.content,\n status: running ? 'streaming' : failed ? 'error' : 'complete',\n ...(stopped ? { stopped: true } : {}),\n ...(failed ? { error: m.status === 'failed' ? FAILED_MESSAGE : UNFINISHED_MESSAGE } : {}),\n ...(running || failed ? {} : { responseId: m.external_id }),\n ...(steps.length > 0 ? { steps, stepCount: steps.length } : {}),\n ...(citations.length > 0 ? { citations } : {}),\n ...(branch ? { branch } : {}),\n }\n}\n\nexport function useConversation(options: UseConversationOptions = {}): ArbiConversation {\n const { agentId, model, titleLength = 48 } = options\n const arbi = useArbi()\n const queryClient = useQueryClient()\n const session = useArbiSessionStore()\n const sessionWorkspaceId = useArbiSessionState((s) => s.workspaceId)\n const workspaceId = options.workspaceId ?? sessionWorkspaceId ?? undefined\n const conversationId = useArbiSessionState((s) => s.conversationId)\n const conversationKey = conversationId ?? NEW\n const generation = useArbiSessionState((s) => s.generating[conversationKey])\n const newConversationMode = useArbiSessionState((s) => s.newConversationAssistantMode)\n const queuedMessages = useArbiSessionState((s) => s.queuedMessages)\n const isRunning = !!generation?.isGenerating\n\n // The surface's workspace and model are the session's while it is mounted.\n useEffect(() => {\n if (workspaceId && session.getState().workspaceId !== workspaceId)\n session.setWorkspaceId(workspaceId)\n }, [session, workspaceId])\n useEffect(() => {\n if (model !== undefined) session.setChatModel(model)\n }, [session, model])\n // An agent chat not sent yet runs through the agent.\n useEffect(() => {\n if (agentId && workspaceId && !conversationId) session.setNewAgentChat({ agentId, workspaceId })\n }, [session, agentId, workspaceId, conversationId])\n\n const { data: docs = [], isLoading: isLoadingDocuments } = useDocuments(workspaceId)\n const ordinaryHistory = useConversations(workspaceId, { enabled: !agentId, live: true })\n const agentHistory = useAgentChats(agentId)\n const stored = useMemo(\n () =>\n agentId\n ? (agentHistory.data ?? [])\n .filter((chat) => chat.workspace_ext_id === workspaceId)\n .map((chat) => ({\n external_id: chat.conversation_ext_id,\n title: chat.title,\n updated_at: chat.updated_at,\n message_count: 1,\n status: null as string | null,\n assistant_mode: 'always' as 'always' | 'mentioned',\n // A chat with one's own agent is one's own and private.\n is_owner: true,\n is_shared: false,\n }))\n : (ordinaryHistory.data ?? []),\n [agentId, agentHistory.data, ordinaryHistory.data, workspaceId]\n )\n const isLoadingThreads = agentId ? agentHistory.isLoading : ordinaryHistory.isLoading\n // A saved workflow's untitled run is named after its workflow (and titled so once opened).\n const runTitles = useWorkflowRunTitles(\n agentId ? NO_ROWS : (ordinaryHistory.data ?? NO_ROWS),\n conversationId,\n workspaceId\n )\n\n const data = useConversationData()\n const {\n messageHistory,\n threads: lines,\n threadsLoading,\n threadsError,\n parentMessageId,\n setParentMessageId,\n } = data\n useConnectRunStream(conversationId, messageHistory)\n const { getBranchControlForMessage, switchBranch: showBranch } = useBranchNavigation(\n lines,\n parentMessageId,\n messageHistory,\n setParentMessageId\n )\n\n const actions = useConversationActions({\n selectedWorkspaceId: workspaceId ?? null,\n parentMessageId,\n conversationKey,\n isGenerating: isRunning,\n lastFailedMessage: generation?.lastFailedMessage ?? null,\n })\n\n const [deselected, setDeselected] = useState<ReadonlySet<string>>(new Set())\n const [stagedFiles, setStagedFiles] = useState<Array<{ id: string; name: string }>>([])\n const [isPostingComment, setIsPostingComment] = useState(false)\n const [isUpdatingAssistantMode, setIsUpdatingAssistantMode] = useState(false)\n const [isUploading, setIsUploading] = useState(false)\n const [uploadError, setUploadError] = useState<string | null>(null)\n const [historyError, setHistoryError] = useState<string | null>(null)\n\n // The document selection and staged files belong to one workspace and agent.\n const scope = `${workspaceId ?? ''}:${agentId ?? ''}`\n const [currentScope, setCurrentScope] = useState(scope)\n if (currentScope !== scope) {\n setCurrentScope(scope)\n setDeselected(new Set())\n setStagedFiles([])\n setUploadError(null)\n setHistoryError(null)\n }\n // Another workspace or agent starts on a new chat.\n const [chatScope, setChatScope] = useState(scope)\n useEffect(() => {\n if (chatScope === scope) return\n setChatScope(scope)\n session.startNewConversation()\n }, [chatScope, scope, session])\n\n const assistantMode: 'always' | 'mentioned' = conversationId\n ? cachedAssistantMode(queryClient, conversationId, 'always')\n : newConversationMode\n\n const messages = useMemo(\n () =>\n messageHistory\n .map((m) => {\n const point = getBranchControlForMessage(m.external_id)\n const branch =\n point && point.branches.length > 1\n ? { index: point.currentBranchIndex, count: point.branches.length }\n : undefined\n return toChatMessage(m, branch)\n })\n .filter((m): m is ArbiChatMessage => m !== null),\n [messageHistory, getBranchControlForMessage]\n )\n\n // The list: the chat being written, then the stored conversations, newest first.\n const isWorkspaceOwner = useIsWorkspaceOwner()\n const threads = useMemo((): ArbiChatThread[] => {\n const firstQuestion = messages.find((m) => m.role === 'user')?.content ?? ''\n const localTitle = firstQuestion ? titleFromQuestion(firstQuestion, titleLength) : ''\n const persisted = [...stored]\n .filter((c) => c.status != null || c.message_count > 0 || c.external_id === conversationId)\n .sort((a, b) => b.updated_at.localeCompare(a.updated_at))\n .map((c) => ({\n id: c.external_id,\n title:\n c.title ||\n runTitles[c.external_id] ||\n (c.external_id === conversationId ? localTitle : ''),\n canDelete: isWorkspaceOwner || (c.is_owner !== false && !c.is_shared),\n }))\n const isListed = persisted.some((t) => t.id === conversationId)\n return [\n ...(conversationId === null\n ? [{ id: NEW, title: localTitle, canDelete: true }]\n : isListed\n ? []\n : [{ id: conversationId, title: localTitle, canDelete: true }]),\n ...persisted,\n ]\n }, [stored, conversationId, messages, titleLength, runTitles, isWorkspaceOwner])\n\n const selectedIds = useMemo(\n () =>\n (agentId ? [] : docs)\n .map((d) => d.external_id)\n .filter((id): id is string => !!id && !deselected.has(id)),\n [docs, deselected, agentId]\n )\n const documents = useMemo<ArbiChatDocument[]>(\n () =>\n agentId\n ? stagedFiles.map((file) => ({ ...file, isSelected: !deselected.has(file.id) }))\n : docs\n .filter((d): d is typeof d & { external_id: string } => !!d.external_id)\n .map((d) => ({\n id: d.external_id,\n name: d.file_name ?? d.external_id,\n isSelected: !deselected.has(d.external_id),\n })),\n [docs, deselected, agentId, stagedFiles]\n )\n\n /** The question as the agent gets it: the files staged in its sandbox are named. */\n const withStagedFiles = useCallback(\n (text: string) => {\n const staged = stagedFiles.filter((file) => !deselected.has(file.id))\n if (!agentId || staged.length === 0) return text\n return (\n text +\n '\\n\\nSource files staged in your sandbox:\\n' +\n staged.map((file) => `${file.name}: ${file.id}`).join('\\n')\n )\n },\n [agentId, stagedFiles, deselected]\n )\n\n const { handleSendMessage, handleCreateBranch } = actions\n const assistantName = useAssistantName()\n const send = useCallback(\n async (text: string) => {\n const trimmed = text.trim()\n if (!trimmed || isUpdatingAssistantMode) return\n setHistoryError(null)\n // The turn is grounded on the documents selected here.\n session.setConversationDocuments(\n conversationKey,\n selectedIds.map((docId) => ({ docId, isPinned: false }))\n )\n const candidates = cachedMentionCandidates(\n queryClient,\n workspaceId,\n signedInUserId(arbi),\n assistantName\n )\n const isComment = isCommentToPeople(queryClient, conversationId, trimmed, candidates)\n session.setDraft(isComment ? trimmed : withStagedFiles(trimmed))\n if (isComment) setIsPostingComment(true)\n try {\n await handleSendMessage()\n } finally {\n if (isComment) setIsPostingComment(false)\n }\n },\n [\n isUpdatingAssistantMode,\n session,\n conversationKey,\n selectedIds,\n queryClient,\n workspaceId,\n arbi,\n conversationId,\n withStagedFiles,\n handleSendMessage,\n assistantName,\n ]\n )\n\n const branch = useCallback(\n (parentId: string | null, text: string) => handleCreateBranch(parentId, withStagedFiles(text)),\n [handleCreateBranch, withStagedFiles]\n )\n\n const switchBranch = useCallback(\n (messageId: string, index: number) => {\n const point = getBranchControlForMessage(messageId)\n if (point) showBranch(point, index)\n },\n [getBranchControlForMessage, showBranch]\n )\n\n const retry = useCallback(async () => {\n if (isRunning) return\n if (generation?.lastFailedMessage) {\n await actions.handleRetrySend()\n return\n }\n // A stored answer that failed: ask its question again in its place.\n const failedIndex = messageHistory.findLastIndex(\n (m) => m.role === 'assistant' && (m.status === 'failed' || m.isError)\n )\n const failed = messageHistory[failedIndex]\n const question = failed\n ? (messageHistory.find((m) => m.external_id === failed.parent_message_ext_id) ??\n messageHistory[failedIndex - 1])\n : undefined\n if (!question || question.role !== 'user') return\n await actions.handleRetryOrphanedMessage(\n question.content,\n question.parent_message_ext_id ?? null,\n question.external_id\n )\n }, [isRunning, generation?.lastFailedMessage, actions, messageHistory])\n\n const { handleAbortGeneration } = actions\n const stop = useCallback(() => void handleAbortGeneration(), [handleAbortGeneration])\n\n const setAssistantMode = useCallback(\n async (mode: 'always' | 'mentioned') => {\n if (isRunning || isPostingComment || isUpdatingAssistantMode) return\n if (!conversationId) {\n session.setNewConversationAssistantMode(mode)\n return\n }\n setIsUpdatingAssistantMode(true)\n setHistoryError(null)\n try {\n await arbi.conversations.setAssistantMode(conversationId, mode)\n await cacheAssistantMode(queryClient, conversationId, mode)\n void (agentId ? agentHistory.refetch() : ordinaryHistory.refetch())\n } catch (e) {\n setHistoryError(messageOf(e, 'The assistant mode could not be changed.'))\n } finally {\n setIsUpdatingAssistantMode(false)\n }\n },\n [\n isRunning,\n isPostingComment,\n isUpdatingAssistantMode,\n conversationId,\n session,\n arbi,\n queryClient,\n agentId,\n agentHistory,\n ordinaryHistory,\n ]\n )\n\n const newThread = useCallback(() => {\n setHistoryError(null)\n session.startNewConversation()\n }, [session])\n\n const selectThread = useCallback(\n (id: string) => {\n setHistoryError(null)\n if (id === NEW) {\n session.startNewConversation()\n return\n }\n if (agentId) session.setAgentChatOwner(id, agentId)\n session.setConversationId(id)\n },\n [session, agentId]\n )\n\n const deleteThread = useCallback(\n (id: string) => {\n if (id === NEW) {\n session.startNewConversation()\n return\n }\n void (async () => {\n try {\n await arbi.conversations.delete(id)\n removeConversationFromLists(queryClient, id)\n if (session.getState().conversationId === id) session.startNewConversation()\n } catch (e) {\n setHistoryError(messageOf(e, 'The conversation could not be deleted.'))\n }\n })()\n },\n [arbi, queryClient, session]\n )\n\n const toggleDocument = useCallback((id: string) => {\n setDeselected((prev) => {\n const next = new Set(prev)\n if (next.has(id)) next.delete(id)\n else next.add(id)\n return next\n })\n }, [])\n const selectAllDocuments = useCallback(() => setDeselected(new Set()), [])\n\n const upload = useCallback(\n async (files: File[]) => {\n if (files.length === 0) return\n setIsUploading(true)\n setUploadError(null)\n try {\n const uploaded: string[] = []\n for (const file of files) {\n if (agentId) {\n const staged = await arbi.agents.stageFile(agentId, file, file.name)\n setStagedFiles((all) => [\n ...all.filter((existing) => existing.id !== staged.path),\n { id: staged.path, name: staged.name },\n ])\n } else {\n // Into the chat's own workspace, named on the request: a scoped or docked chat's\n // workspace need not be the one open, and a switch meanwhile must not move the file.\n const result = await arbi.documents.upload([file], {\n ...(workspaceId ? { workspaceExtId: workspaceId } : {}),\n })\n uploaded.push(...(result.doc_ext_ids ?? []))\n }\n }\n // New documents are not deselected, so they join the selection by default.\n if (uploaded.length) await refreshDocuments(queryClient, arbi, uploaded)\n } catch (e) {\n setUploadError(messageOf(e, 'The upload failed.'))\n } finally {\n setIsUploading(false)\n }\n },\n [arbi, queryClient, agentId, workspaceId]\n )\n\n const runningAnswer = generation?.streamingAssistantId\n const queue = (runningAnswer && queuedMessages[runningAnswer]) || []\n const last = messages[messages.length - 1]\n\n return {\n assistantMode,\n isUpdatingAssistantMode,\n isPostingComment,\n setAssistantMode,\n threads,\n activeThreadId: conversationKey,\n messages,\n isRunning,\n error: generation?.error ?? (last?.status === 'error' ? (last.error ?? null) : null),\n isLoadingThread: !!conversationId && threadsLoading && !threadsError,\n isLoadingThreads,\n historyError:\n historyError ??\n (threadsError ? messageOf(threadsError, 'The conversation could not be loaded.') : null),\n documents,\n isLoadingDocuments,\n isUploading,\n uploadError,\n send,\n interject: send,\n queue,\n branch,\n switchBranch,\n retry,\n stop,\n selectThread,\n newThread,\n deleteThread,\n toggleDocument,\n selectAllDocuments,\n upload,\n }\n}\n"],
|
|
5
|
-
"mappings": "AAqBA,SAAS,aAAa,WAAW,SAAS,gBAAgB;AAC1D,SAAS,sBAAsB;AAE/B,SAAS,eAAe;AACxB,SAAS,eAAe,2BAA2B;AACnD,SAAS,wBAAwB;AACjC,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,mCAAmC;AAC5C,SAAS,qBAAqB,2BAA2B;AACzD,SAAS,uBAA8C;AACvD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,wBAAwB;AACjC,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AA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OAAO,IAAI;AAAA,cACvD,EAAE,IAAI,OAAO,MAAM,MAAM,OAAO,KAAK;AAAA,YACvC,CAAC;AAAA,UACH,OAAO;AAGL,kBAAM,SAAS,MAAM,KAAK,UAAU,OAAO,CAAC,IAAI,GAAG;AAAA,cACjD,GAAI,cAAc,EAAE,gBAAgB,YAAY,IAAI,CAAC;AAAA,YACvD,CAAC;AACD,qBAAS,KAAK,GAAI,OAAO,eAAe,CAAC,CAAE;AAAA,UAC7C;AAAA,QACF;AAEA,YAAI,SAAS,OAAQ,OAAM,iBAAiB,aAAa,MAAM,QAAQ;AAAA,MACzE,SAAS,GAAG;AACV,uBAAe,UAAU,GAAG,oBAAoB,CAAC;AAAA,MACnD,UAAE;AACA,uBAAe,KAAK;AAAA,MACtB;AAAA,IACF;AAAA,IACA,CAAC,MAAM,aAAa,SAAS,WAAW;AAAA,EAC1C;AAEA,QAAM,gBAAgB,YAAY;AAClC,QAAM,QAAS,iBAAiB,eAAe,aAAa,KAAM,CAAC;AACnE,QAAM,OAAO,SAAS,SAAS,SAAS,CAAC;AAEzC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA,OAAO,YAAY,UAAU,MAAM,WAAW,UAAW,KAAK,SAAS,OAAQ;AAAA,IAC/E,iBAAiB,CAAC,CAAC,kBAAkB,kBAAkB,CAAC;AAAA,IACxD;AAAA,IACA,cACE,iBACC,eAAe,UAAU,cAAc,uCAAuC,IAAI;AAAA,IACrF;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["/**\n * `useConversation`: the chat engine as one hook, the controller behind a full-page (or docked)\n * assistant. It returns what a chat surface needs and no markup; `@arbidocs/blocks/chat`'s\n * `ChatPage` takes it as its `chat` prop:\n *\n * ```tsx\n * const chat = useConversation({ workspaceId })\n * <ChatPage chat={chat} aside={<WorkflowLauncher \u2026 />} />\n * ```\n *\n * It is the same engine the ARBI app runs: the open conversation is the session's\n * (`ArbiSessionState.conversationId`, its viewed line `cursor`), the messages are the conversation\n * cache's, a turn goes through `useConversationActions` (send, branch, retry, stop, follow-ups\n * queued or steered into a running turn, comments to the people in a shared thread), and a run\n * started elsewhere is attached live (`useConnectRunStream`). So every surface gets the agent's\n * steps, the branches of an edited question, and interjections.\n *\n * A surface that must keep its own open conversation, beside another chat on the same page, mounts\n * inside its own session scope (`<ConversationScope>`).\n */\n\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport type { AgentStepEvent, AskRequest, ChatMessage } from '@arbidocs/sdk/browser'\nimport { useArbi } from '../useArbi'\nimport { useAgentChats, useIsWorkspaceOwner } from '../workforce'\nimport { useConversations } from '../hooks'\nimport { refreshDocuments, useDocuments } from '../documents/documents-data'\nimport { removeConversationFromLists } from '../conversation-list'\nimport { useArbiSessionState, useArbiSessionStore } from '../session'\nimport { toChatCitations, type ArbiChatCitation } from './citations'\nimport {\n cacheAssistantMode,\n cachedAssistantMode,\n cachedMentionCandidates,\n isCommentToPeople,\n} from './conversation-mentions'\nimport { useAssistantName } from '../host/assistant-copy'\nimport { useConversationActions } from './useConversationActions'\nimport { useConversationData } from './useConversationData'\nimport { useBranchNavigation } from './useBranchNavigation'\nimport { useConnectRunStream } from './useConnectRunStream'\nimport type { QueuedMessage } from './run-state'\nimport { useWorkflowRunTitles, type WorkflowRunRow } from './workflow-run-titles'\n\nexport type { ArbiChatCitation, ArbiChatPassage } from './citations'\n\nexport type ArbiChatRole = 'user' | 'assistant'\nexport type ArbiChatMessageStatus = 'streaming' | 'complete' | 'error'\n\nexport interface ArbiChatMessage {\n mentions?: AskRequest['mentions']\n authorId?: string\n id: string\n role: ArbiChatRole\n /** Markdown for an assistant message, plain text for a user message. */\n content: string\n status: ArbiChatMessageStatus\n /** Why an assistant message failed. */\n error?: string\n /** Agent steps (tool calls, reasoning) the answer took. */\n stepCount?: number\n /** The answer's agent steps, live while it runs. */\n steps?: AgentStepEvent[]\n /** The sources behind `[statement](#cite-N)` marks in `content`. */\n citations?: ArbiChatCitation[]\n /** The reader stopped the answer; `content` is what had streamed. */\n stopped?: boolean\n /** The backend id of a finished assistant answer: what a follow-up chains from. */\n responseId?: string\n /**\n * A user message the server sent to start a workflow's step (its `tools.workflow_step`): the\n * step's id. A chat shows it as that step, not as the raw instruction.\n */\n workflowStep?: string\n /**\n * One of several versions of this message (an edited question, an answer asked again): which\n * one is shown (0-based) and how many there are. `switchBranch` shows another.\n */\n branch?: { index: number; count: number }\n}\n\n/** The workflow step a stored message starts (its `tools.workflow_step` marker), if any. */\nexport function workflowStepOf(tools: object | null | undefined): string | undefined {\n const marker = (tools as Record<string, unknown> | null | undefined)?.workflow_step as\n { workflow_step?: unknown } | undefined\n return typeof marker?.workflow_step === 'string' ? marker.workflow_step : undefined\n}\n\nexport interface ArbiChatThread {\n id: string\n /** The backend title, else the first question; empty until there is one. */\n title: string\n /**\n * Whether the viewer may delete it. Sharing is one-way: a shared conversation is the workspace's,\n * so only a workspace owner deletes it; its creator deletes it only while it is private.\n */\n canDelete: boolean\n}\n\nexport interface ArbiChatDocument {\n id: string\n name: string\n isSelected: boolean\n}\n\nexport interface UseConversationOptions {\n /** Use an owned agent's independent session, history and sandbox files. */\n agentId?: string\n /** The workspace to chat in (default: the session's). */\n workspaceId?: string\n /** Assistant configuration or model id every turn uses (default: the person's last one). */\n model?: string\n /** Longest auto-title in characters (used until the backend has titled the conversation). Default 48. */\n titleLength?: number\n}\n\nexport interface ArbiConversation {\n assistantMode: 'always' | 'mentioned'\n isUpdatingAssistantMode: boolean\n isPostingComment: boolean\n setAssistantMode: (mode: 'always' | 'mentioned') => Promise<void>\n threads: ArbiChatThread[]\n /** The open conversation's id, or `new` for a chat not sent yet. */\n activeThreadId: string\n /** The viewed line of the open conversation. */\n messages: ArbiChatMessage[]\n /** An answer is running in the open conversation. */\n isRunning: boolean\n /** The last turn failed (the message list also carries the failed message). */\n error: string | null\n /** A stored conversation's messages are loading. */\n isLoadingThread: boolean\n /** The conversation list is loading. */\n isLoadingThreads: boolean\n /** Deleting a conversation or changing its mode failed. */\n historyError: string | null\n documents: ArbiChatDocument[]\n isLoadingDocuments: boolean\n isUploading: boolean\n uploadError: string | null\n /**\n * Send a question, or a comment to the people in a shared thread. While an answer runs, the\n * question waits in the running turn's queue (`queue`) or steers it.\n */\n send: (text: string, options?: { mentions?: AskRequest['mentions'] }) => Promise<void>\n /** Send `text` while the answer runs: the agent takes it into the running turn or queues it. */\n interject: (text: string) => Promise<void>\n /** Follow-ups waiting for the running answer. */\n queue: readonly QueuedMessage[]\n /** Ask `text` again in place of the message after `parentId` (an edit): a new branch. */\n branch: (parentId: string | null, text: string) => Promise<void>\n /** Show another version of a branched message (`ArbiChatMessage.branch`). */\n switchBranch: (messageId: string, index: number) => void\n /** Re-ask the question whose answer failed. */\n retry: () => Promise<void>\n /** Stop the running answer; what streamed so far stays, marked stopped. */\n stop: () => void\n selectThread: (id: string) => void\n newThread: () => void\n /** Deletes the conversation on the backend too. */\n deleteThread: (id: string) => void\n toggleDocument: (id: string) => void\n selectAllDocuments: () => void\n upload: (files: File[]) => Promise<void>\n}\n\n/** First words of a question as a title: whole words, no trailing punctuation, ellipsis when cut. */\nexport function titleFromQuestion(question: string, maxLength = 48): string {\n const flat = question.replace(/\\s+/g, ' ').trim()\n if (flat.length <= maxLength) return flat\n const cut = flat.slice(0, maxLength)\n const lastSpace = cut.lastIndexOf(' ')\n const words = lastSpace > maxLength / 2 ? cut.slice(0, lastSpace) : cut\n return `${words.replace(/[\\s,;:.\\-\u2013\u2014]+$/, '')}\u2026`\n}\n\nconst FAILED_MESSAGE = 'The assistant request failed.'\nconst UNFINISHED_MESSAGE = 'The answer did not finish. Try again.'\nconst NEW = 'new'\n/** No conversation rows (a stable empty list). */\nconst NO_ROWS: readonly WorkflowRunRow[] = []\n\nconst messageOf = (e: unknown, fallback: string) => (e instanceof Error ? e.message : fallback)\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/** A message of the conversation cache as the chat surface shows it. */\nfunction toChatMessage(m: ChatMessage, branch: ArbiChatMessage['branch']): ArbiChatMessage | null {\n if (m.role === 'system') return null\n const running = m.isLoading === true || m.status === 'in_progress' || m.status === 'queued'\n if (m.role === 'user') {\n if (!m.content.trim()) return null\n const workflowStep = workflowStepOf(m.tools)\n return {\n id: m.external_id,\n role: 'user',\n content: m.content,\n status: 'complete',\n ...(workflowStep ? { workflowStep } : {}),\n ...(m.created_by_ext_id ? { authorId: m.created_by_ext_id } : {}),\n ...(m.mentions?.length ? { mentions: m.mentions as AskRequest['mentions'] } : {}),\n ...(branch ? { branch } : {}),\n }\n }\n const failed = m.status === 'failed' || m.isError === true\n const stopped = m.status === 'cancelled'\n if (!m.content.trim() && !running && !failed && !stopped) return null\n const citations = toChatCitations({ tools: m.tools })\n const steps = m.agentSteps ?? []\n return {\n id: m.external_id,\n role: 'assistant',\n content: m.content,\n status: running ? 'streaming' : failed ? 'error' : 'complete',\n ...(stopped ? { stopped: true } : {}),\n ...(failed ? { error: m.status === 'failed' ? FAILED_MESSAGE : UNFINISHED_MESSAGE } : {}),\n ...(running || failed ? {} : { responseId: m.external_id }),\n ...(steps.length > 0 ? { steps, stepCount: steps.length } : {}),\n ...(citations.length > 0 ? { citations } : {}),\n ...(branch ? { branch } : {}),\n }\n}\n\nexport function useConversation(options: UseConversationOptions = {}): ArbiConversation {\n const { agentId, model, titleLength = 48 } = options\n const arbi = useArbi()\n const queryClient = useQueryClient()\n const session = useArbiSessionStore()\n const sessionWorkspaceId = useArbiSessionState((s) => s.workspaceId)\n const workspaceId = options.workspaceId ?? sessionWorkspaceId ?? undefined\n const conversationId = useArbiSessionState((s) => s.conversationId)\n const conversationKey = conversationId ?? NEW\n const generation = useArbiSessionState((s) => s.generating[conversationKey])\n const newConversationMode = useArbiSessionState((s) => s.newConversationAssistantMode)\n const queuedMessages = useArbiSessionState((s) => s.queuedMessages)\n const isRunning = !!generation?.isGenerating\n\n // The surface's workspace and model are the session's while it is mounted.\n useEffect(() => {\n if (workspaceId && session.getState().workspaceId !== workspaceId)\n session.setWorkspaceId(workspaceId)\n }, [session, workspaceId])\n useEffect(() => {\n if (model !== undefined) session.setChatModel(model)\n }, [session, model])\n // An agent chat not sent yet runs through the agent.\n useEffect(() => {\n if (agentId && workspaceId && !conversationId) session.setNewAgentChat({ agentId, workspaceId })\n }, [session, agentId, workspaceId, conversationId])\n\n // The agent whose sandbox the chat's files go to: the surface's, else the open chat's agent.\n const chatAgentId =\n useArbiSessionState(\n (s) =>\n agentId ??\n (conversationId\n ? s.agentChatOwners[conversationId]\n : s.newAgentChat?.workspaceId === workspaceId\n ? s.newAgentChat?.agentId\n : undefined)\n ) ?? undefined\n\n const { data: docs = [], isLoading: isLoadingDocuments } = useDocuments(workspaceId)\n const ordinaryHistory = useConversations(workspaceId, { enabled: !agentId, live: true })\n const agentHistory = useAgentChats(agentId)\n const stored = useMemo(\n () =>\n agentId\n ? (agentHistory.data ?? [])\n .filter((chat) => chat.workspace_ext_id === workspaceId)\n .map((chat) => ({\n external_id: chat.conversation_ext_id,\n title: chat.title,\n updated_at: chat.updated_at,\n message_count: 1,\n status: null as string | null,\n assistant_mode: 'always' as 'always' | 'mentioned',\n // A chat with one's own agent is one's own and private.\n is_owner: true,\n is_shared: false,\n }))\n : (ordinaryHistory.data ?? []),\n [agentId, agentHistory.data, ordinaryHistory.data, workspaceId]\n )\n const isLoadingThreads = agentId ? agentHistory.isLoading : ordinaryHistory.isLoading\n // A saved workflow's untitled run is named after its workflow (and titled so once opened).\n const runTitles = useWorkflowRunTitles(\n agentId ? NO_ROWS : (ordinaryHistory.data ?? NO_ROWS),\n conversationId,\n workspaceId\n )\n\n const data = useConversationData()\n const {\n messageHistory,\n threads: lines,\n threadsLoading,\n threadsError,\n parentMessageId,\n setParentMessageId,\n } = data\n useConnectRunStream(conversationId, messageHistory)\n const { getBranchControlForMessage, switchBranch: showBranch } = useBranchNavigation(\n lines,\n parentMessageId,\n messageHistory,\n setParentMessageId\n )\n\n const actions = useConversationActions({\n selectedWorkspaceId: workspaceId ?? null,\n parentMessageId,\n conversationKey,\n isGenerating: isRunning,\n lastFailedMessage: generation?.lastFailedMessage ?? null,\n })\n\n const [deselected, setDeselected] = useState<ReadonlySet<string>>(new Set())\n const [stagedFiles, setStagedFiles] = useState<Array<{ id: string; name: string }>>([])\n const [isPostingComment, setIsPostingComment] = useState(false)\n const [isUpdatingAssistantMode, setIsUpdatingAssistantMode] = useState(false)\n const [isUploading, setIsUploading] = useState(false)\n const [uploadError, setUploadError] = useState<string | null>(null)\n const [historyError, setHistoryError] = useState<string | null>(null)\n\n // The document selection and staged files belong to one workspace and agent.\n const scope = `${workspaceId ?? ''}:${chatAgentId ?? ''}`\n const [currentScope, setCurrentScope] = useState(scope)\n if (currentScope !== scope) {\n setCurrentScope(scope)\n setDeselected(new Set())\n setStagedFiles([])\n setUploadError(null)\n setHistoryError(null)\n }\n // Another workspace or agent starts on a new chat.\n const [chatScope, setChatScope] = useState(scope)\n useEffect(() => {\n if (chatScope === scope) return\n setChatScope(scope)\n session.startNewConversation()\n }, [chatScope, scope, session])\n\n const assistantMode: 'always' | 'mentioned' = conversationId\n ? cachedAssistantMode(queryClient, conversationId, 'always')\n : newConversationMode\n\n const messages = useMemo(\n () =>\n messageHistory\n .map((m) => {\n const point = getBranchControlForMessage(m.external_id)\n const branch =\n point && point.branches.length > 1\n ? { index: point.currentBranchIndex, count: point.branches.length }\n : undefined\n return toChatMessage(m, branch)\n })\n .filter((m): m is ArbiChatMessage => m !== null),\n [messageHistory, getBranchControlForMessage]\n )\n\n // The list: the chat being written, then the stored conversations, newest first.\n const isWorkspaceOwner = useIsWorkspaceOwner()\n const threads = useMemo((): ArbiChatThread[] => {\n const firstQuestion = messages.find((m) => m.role === 'user')?.content ?? ''\n const localTitle = firstQuestion ? titleFromQuestion(firstQuestion, titleLength) : ''\n const persisted = [...stored]\n .filter((c) => c.status != null || c.message_count > 0 || c.external_id === conversationId)\n .sort((a, b) => b.updated_at.localeCompare(a.updated_at))\n .map((c) => ({\n id: c.external_id,\n title:\n c.title ||\n runTitles[c.external_id] ||\n (c.external_id === conversationId ? localTitle : ''),\n canDelete: isWorkspaceOwner || (c.is_owner !== false && !c.is_shared),\n }))\n const isListed = persisted.some((t) => t.id === conversationId)\n return [\n ...(conversationId === null\n ? [{ id: NEW, title: localTitle, canDelete: true }]\n : isListed\n ? []\n : [{ id: conversationId, title: localTitle, canDelete: true }]),\n ...persisted,\n ]\n }, [stored, conversationId, messages, titleLength, runTitles, isWorkspaceOwner])\n\n const selectedIds = useMemo(\n () =>\n (chatAgentId ? [] : docs)\n .map((d) => d.external_id)\n .filter((id): id is string => !!id && !deselected.has(id)),\n [docs, deselected, chatAgentId]\n )\n const documents = useMemo<ArbiChatDocument[]>(\n () =>\n chatAgentId\n ? stagedFiles.map((file) => ({ ...file, isSelected: !deselected.has(file.id) }))\n : docs\n .filter((d): d is typeof d & { external_id: string } => !!d.external_id)\n .map((d) => ({\n id: d.external_id,\n name: d.file_name ?? d.external_id,\n isSelected: !deselected.has(d.external_id),\n })),\n [docs, deselected, chatAgentId, stagedFiles]\n )\n\n /** The question as the agent gets it: the files staged in its sandbox are named. */\n const withStagedFiles = useCallback(\n (text: string) => {\n const staged = stagedFiles.filter((file) => !deselected.has(file.id))\n if (!chatAgentId || staged.length === 0) return text\n return (\n text +\n '\\n\\nSource files staged in your sandbox:\\n' +\n staged.map((file) => `${file.name}: ${file.id}`).join('\\n')\n )\n },\n [chatAgentId, stagedFiles, deselected]\n )\n\n const { handleSendMessage, handleCreateBranch } = actions\n const assistantName = useAssistantName()\n const send = useCallback(\n async (text: string) => {\n const trimmed = text.trim()\n if (!trimmed || isUpdatingAssistantMode) return\n setHistoryError(null)\n // The turn is grounded on the documents selected here.\n session.setConversationDocuments(\n conversationKey,\n selectedIds.map((docId) => ({ docId, isPinned: false }))\n )\n const candidates = cachedMentionCandidates(\n queryClient,\n workspaceId,\n signedInUserId(arbi),\n assistantName\n )\n const isComment = isCommentToPeople(queryClient, conversationId, trimmed, candidates)\n session.setDraft(isComment ? trimmed : withStagedFiles(trimmed))\n if (isComment) setIsPostingComment(true)\n try {\n await handleSendMessage()\n } finally {\n if (isComment) setIsPostingComment(false)\n }\n },\n [\n isUpdatingAssistantMode,\n session,\n conversationKey,\n selectedIds,\n queryClient,\n workspaceId,\n arbi,\n conversationId,\n withStagedFiles,\n handleSendMessage,\n assistantName,\n ]\n )\n\n const branch = useCallback(\n (parentId: string | null, text: string) => handleCreateBranch(parentId, withStagedFiles(text)),\n [handleCreateBranch, withStagedFiles]\n )\n\n const switchBranch = useCallback(\n (messageId: string, index: number) => {\n const point = getBranchControlForMessage(messageId)\n if (point) showBranch(point, index)\n },\n [getBranchControlForMessage, showBranch]\n )\n\n const retry = useCallback(async () => {\n if (isRunning) return\n if (generation?.lastFailedMessage) {\n await actions.handleRetrySend()\n return\n }\n // A stored answer that failed: ask its question again in its place.\n const failedIndex = messageHistory.findLastIndex(\n (m) => m.role === 'assistant' && (m.status === 'failed' || m.isError)\n )\n const failed = messageHistory[failedIndex]\n const question = failed\n ? (messageHistory.find((m) => m.external_id === failed.parent_message_ext_id) ??\n messageHistory[failedIndex - 1])\n : undefined\n if (!question || question.role !== 'user') return\n await actions.handleRetryOrphanedMessage(\n question.content,\n question.parent_message_ext_id ?? null,\n question.external_id\n )\n }, [isRunning, generation?.lastFailedMessage, actions, messageHistory])\n\n const { handleAbortGeneration } = actions\n const stop = useCallback(() => void handleAbortGeneration(), [handleAbortGeneration])\n\n const setAssistantMode = useCallback(\n async (mode: 'always' | 'mentioned') => {\n if (isRunning || isPostingComment || isUpdatingAssistantMode) return\n if (!conversationId) {\n session.setNewConversationAssistantMode(mode)\n return\n }\n setIsUpdatingAssistantMode(true)\n setHistoryError(null)\n try {\n await arbi.conversations.setAssistantMode(conversationId, mode)\n await cacheAssistantMode(queryClient, conversationId, mode)\n void (agentId ? agentHistory.refetch() : ordinaryHistory.refetch())\n } catch (e) {\n setHistoryError(messageOf(e, 'The assistant mode could not be changed.'))\n } finally {\n setIsUpdatingAssistantMode(false)\n }\n },\n [\n isRunning,\n isPostingComment,\n isUpdatingAssistantMode,\n conversationId,\n session,\n arbi,\n queryClient,\n agentId,\n agentHistory,\n ordinaryHistory,\n ]\n )\n\n const newThread = useCallback(() => {\n setHistoryError(null)\n session.startNewConversation()\n }, [session])\n\n const selectThread = useCallback(\n (id: string) => {\n setHistoryError(null)\n if (id === NEW) {\n session.startNewConversation()\n return\n }\n if (agentId) session.setAgentChatOwner(id, agentId)\n session.setConversationId(id)\n },\n [session, agentId]\n )\n\n const deleteThread = useCallback(\n (id: string) => {\n if (id === NEW) {\n session.startNewConversation()\n return\n }\n void (async () => {\n try {\n await arbi.conversations.delete(id)\n removeConversationFromLists(queryClient, id)\n if (session.getState().conversationId === id) session.startNewConversation()\n } catch (e) {\n setHistoryError(messageOf(e, 'The conversation could not be deleted.'))\n }\n })()\n },\n [arbi, queryClient, session]\n )\n\n const toggleDocument = useCallback((id: string) => {\n setDeselected((prev) => {\n const next = new Set(prev)\n if (next.has(id)) next.delete(id)\n else next.add(id)\n return next\n })\n }, [])\n const selectAllDocuments = useCallback(() => setDeselected(new Set()), [])\n\n const upload = useCallback(\n async (files: File[]) => {\n if (files.length === 0) return\n setIsUploading(true)\n setUploadError(null)\n try {\n const uploaded: string[] = []\n for (const file of files) {\n if (chatAgentId) {\n const staged = await arbi.agents.stageFile(chatAgentId, file, file.name)\n setStagedFiles((all) => [\n ...all.filter((existing) => existing.id !== staged.path),\n { id: staged.path, name: staged.name },\n ])\n } else {\n // Into the chat's own workspace, named on the request: a scoped or docked chat's\n // workspace need not be the one open, and a switch meanwhile must not move the file.\n const result = await arbi.documents.upload([file], {\n ...(workspaceId ? { workspaceExtId: workspaceId } : {}),\n })\n uploaded.push(...(result.doc_ext_ids ?? []))\n }\n }\n // New documents are not deselected, so they join the selection by default.\n if (uploaded.length) await refreshDocuments(queryClient, arbi, uploaded)\n } catch (e) {\n setUploadError(messageOf(e, 'The upload failed.'))\n } finally {\n setIsUploading(false)\n }\n },\n [arbi, queryClient, chatAgentId, workspaceId]\n )\n\n const runningAnswer = generation?.streamingAssistantId\n const queue = (runningAnswer && queuedMessages[runningAnswer]) || []\n const last = messages[messages.length - 1]\n\n return {\n assistantMode,\n isUpdatingAssistantMode,\n isPostingComment,\n setAssistantMode,\n threads,\n activeThreadId: conversationKey,\n messages,\n isRunning,\n error: generation?.error ?? (last?.status === 'error' ? (last.error ?? null) : null),\n isLoadingThread: !!conversationId && threadsLoading && !threadsError,\n isLoadingThreads,\n historyError:\n historyError ??\n (threadsError ? messageOf(threadsError, 'The conversation could not be loaded.') : null),\n documents,\n isLoadingDocuments,\n isUploading,\n uploadError,\n send,\n interject: send,\n queue,\n branch,\n switchBranch,\n retry,\n stop,\n selectThread,\n newThread,\n deleteThread,\n toggleDocument,\n selectAllDocuments,\n upload,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAqBA,SAAS,aAAa,WAAW,SAAS,gBAAgB;AAC1D,SAAS,sBAAsB;AAE/B,SAAS,eAAe;AACxB,SAAS,eAAe,2BAA2B;AACnD,SAAS,wBAAwB;AACjC,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,mCAAmC;AAC5C,SAAS,qBAAqB,2BAA2B;AACzD,SAAS,uBAA8C;AACvD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,wBAAwB;AACjC,SAAS,8BAA8B;AAC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AW;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["branch"]
|
|
7
7
|
}
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
import { notify } from "../shell/index.js";
|
|
12
12
|
import { arbiQueryKeys } from "../hooks.js";
|
|
13
13
|
import { useArbi } from "../useArbi.js";
|
|
14
|
+
import { requestAgentStatus } from "./request-agent-status.js";
|
|
14
15
|
import { useArbiHost } from "../host/config.js";
|
|
15
16
|
import { selectDraft, useArbiSessionStore } from "../session/index.js";
|
|
16
17
|
import {
|
|
@@ -524,10 +525,10 @@ function useConversationActions({
|
|
|
524
525
|
session.setAgentControlState(streamingAssistantId, "pausing");
|
|
525
526
|
} else if (isResume) {
|
|
526
527
|
session.setAgentControlState(streamingAssistantId, "resuming");
|
|
527
|
-
} else if (isReport) {
|
|
528
|
-
session.setAgentProbePending(streamingAssistantId, true);
|
|
529
528
|
}
|
|
530
|
-
if (
|
|
529
|
+
if (isReport) {
|
|
530
|
+
await requestAgentStatus(arbi, session, streamingAssistantId, currentMessage);
|
|
531
|
+
} else if (isPause || isResume) {
|
|
531
532
|
await arbi.assistant.interject(streamingAssistantId, currentMessage);
|
|
532
533
|
} else {
|
|
533
534
|
const queuedClientId = `queued-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|