@arbidocs/react 0.5.146 → 0.5.147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/artifacts/index.cjs +14 -14
  2. package/dist/calls/livekit/index.cjs +48 -48
  3. package/dist/chat/conversation-cache.js +5 -0
  4. package/dist/chat/conversation-cache.js.map +2 -2
  5. package/dist/chat/useConversation.js +10 -5
  6. package/dist/chat/useConversation.js.map +2 -2
  7. package/dist/chat/useConversationActions.js +4 -0
  8. package/dist/chat/useConversationActions.js.map +2 -2
  9. package/dist/chat/useConversationSettings.js +4 -10
  10. package/dist/chat/useConversationSettings.js.map +2 -2
  11. package/dist/{chunk-FE6ZSNZE.cjs → chunk-5FQB5F2F.cjs} +9 -4
  12. package/dist/chunk-5FQB5F2F.cjs.map +1 -0
  13. package/dist/{chunk-2F24LLVZ.cjs → chunk-MHYTO2EX.cjs} +38 -38
  14. package/dist/{chunk-2F24LLVZ.cjs.map → chunk-MHYTO2EX.cjs.map} +1 -1
  15. package/dist/{chunk-26SZ3DS4.cjs → chunk-MJIXYLI4.cjs} +66 -66
  16. package/dist/{chunk-26SZ3DS4.cjs.map → chunk-MJIXYLI4.cjs.map} +1 -1
  17. package/dist/{chunk-ZZZYVNFW.cjs → chunk-VBUEDJMK.cjs} +57 -57
  18. package/dist/{chunk-ZZZYVNFW.cjs.map → chunk-VBUEDJMK.cjs.map} +1 -1
  19. package/dist/{chunk-FDYZA6NO.cjs → chunk-XBY4RLC6.cjs} +4 -4
  20. package/dist/{chunk-FDYZA6NO.cjs.map → chunk-XBY4RLC6.cjs.map} +1 -1
  21. package/dist/{chunk-VO7OWQP6.cjs → chunk-ZFTWH6B6.cjs} +44 -44
  22. package/dist/{chunk-VO7OWQP6.cjs.map → chunk-ZFTWH6B6.cjs.map} +1 -1
  23. package/dist/databases.js +9 -6
  24. package/dist/databases.js.map +2 -2
  25. package/dist/datasets/index.js +25 -21
  26. package/dist/datasets/index.js.map +2 -2
  27. package/dist/datasets/pages.js +208 -0
  28. package/dist/datasets/pages.js.map +7 -0
  29. package/dist/datasets/registry.js.map +2 -2
  30. package/dist/datasets/sources/database.js +21 -23
  31. package/dist/datasets/sources/database.js.map +2 -2
  32. package/dist/document-tools/core.cjs +98 -98
  33. package/dist/document-tools/core.d.ts +2 -2
  34. package/dist/document-tools/index.cjs +100 -100
  35. package/dist/document-tools/index.d.ts +1 -1
  36. package/dist/documents/documents-writes.js +45 -14
  37. package/dist/documents/documents-writes.js.map +2 -2
  38. package/dist/documents/index.js +8 -0
  39. package/dist/documents/index.js.map +2 -2
  40. package/dist/documents/tag-when-processed.js +47 -0
  41. package/dist/documents/tag-when-processed.js.map +7 -0
  42. package/dist/host/config.js.map +1 -1
  43. package/dist/index.cjs +1880 -1583
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.ts +319 -97
  46. package/dist/index.js +27 -5
  47. package/dist/index.js.map +2 -2
  48. package/dist/notifications/notification-types.js +7 -0
  49. package/dist/notifications/notification-types.js.map +2 -2
  50. package/dist/notifications/server-notifications.js +66 -10
  51. package/dist/notifications/server-notifications.js.map +2 -2
  52. package/dist/{query-keys.d-d2M4FAq2.d.ts → query-keys.d-pgq-4jyZ.d.ts} +7 -2
  53. package/dist/query-keys.js +7 -2
  54. package/dist/query-keys.js.map +2 -2
  55. package/dist/table-views.js +166 -0
  56. package/dist/table-views.js.map +7 -0
  57. package/package.json +3 -3
  58. package/dist/account/table-views.js +0 -16
  59. package/dist/account/table-views.js.map +0 -7
  60. package/dist/chunk-FE6ZSNZE.cjs.map +0 -1
  61. package/dist/datasets/store.js +0 -194
  62. package/dist/datasets/store.js.map +0 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/chat/conversation-cache.ts"],
4
- "sourcesContent": ["/**\n * A conversation's threads in the query cache (`arbiQueryKeys.conversationThreads(id)`), and the\n * writers every chat engine and event uses on them: a turn's user and assistant messages, streamed\n * text (buffered per animation frame), settled output items, the resolving commit (held behind\n * the narration dwell), failure, loading state and pending questions.\n */\n\nimport type { QueryClient } from '@tanstack/react-query'\nimport type { components } from '@arbidocs/client'\nimport {\n reduceOutputItem,\n createIndexAssigner,\n type ChatMessage as Message,\n type OutputItemDone,\n type Thread,\n type ThreadsResponse,\n type UserInputRequestEvent,\n} from '@arbidocs/sdk/browser'\nimport { arbiQueryKeys } from '../hooks'\n\ntype MessageResponse = components['schemas']['MessageResponse']\n\n/** The query key of a conversation's threads. */\nexport function getThreadsQueryKey(conversationId: string) {\n return arbiQueryKeys.conversationThreads(conversationId)\n}\n\n/** Every conversation's cached threads (a filter for `invalidateQueries`, `getQueriesData`, \u2026). */\nexport const allConversationThreads = {\n predicate: ({ queryKey }: { queryKey: readonly unknown[] }) =>\n queryKey[0] === 'arbi' && queryKey[1] === 'conversations' && queryKey[3] === 'threads',\n}\n\n/**\n * Whether the cached thread says a message is still being generated on the server\n */\nexport function isMessageRunning(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): boolean {\n const data = queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(conversationId))\n return (data?.threads ?? []).some((t: Thread) =>\n t.history.some(\n (m: Message) =>\n m.external_id === messageId && (m.status === 'in_progress' || m.status === 'queued')\n )\n )\n}\n\n/**\n * Add a user message to the conversation cache\n */\nexport function addUserMessageToCache(\n queryClient: QueryClient,\n conversationId: string,\n userMessage: Message,\n options: {\n parentId?: string | null\n parentMessageId?: string | null\n currentParentMessageId?: string | null\n }\n): void {\n const { parentId, parentMessageId, currentParentMessageId } = options\n\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) {\n return {\n conversation_ext_id: conversationId,\n threads: [\n {\n history: [userMessage],\n leaf_message_ext_id: userMessage.external_id,\n },\n ],\n }\n }\n\n const threads = [...(oldData.threads || [])]\n\n // The server's parent is authoritative. A follow-up sent while a turn generates names\n // that turn, but the server queues each one behind the follow-ups already waiting, so\n // it may answer it after a later turn. Placing it under the client's guess made ordered\n // follow-ups siblings (\"Branch 1 of 2\") instead of one line.\n const serverParentId = userMessage.parent_message_ext_id\n // A server parent that already has a reply is a real branch point.\n const serverParentKnown =\n !!serverParentId &&\n threads.some((t) => t.history.some((msg) => msg.external_id === serverParentId))\n // A follow-up queued behind another one is chained after that one's answer, which has not\n // streamed in yet. Until it does, the follow-up continues the thread ending at the queued\n // message. The client's guess (the running turn) would wrongly branch it off that turn.\n const queuedLeafIndex = threads.findIndex((t) =>\n t.history.some(\n (msg) => msg.external_id === t.leaf_message_ext_id && msg.status === 'queued'\n )\n )\n const continueIndex =\n serverParentId && !serverParentKnown\n ? queuedLeafIndex\n : threads.findIndex((t) => t.leaf_message_ext_id === serverParentId)\n if (serverParentId && continueIndex !== -1) {\n threads[continueIndex] = {\n ...threads[continueIndex],\n history: [...threads[continueIndex].history, userMessage],\n leaf_message_ext_id: userMessage.external_id,\n }\n return { ...oldData, threads }\n }\n\n const branchFrom = serverParentKnown ? serverParentId : parentId\n const isBranching = serverParentKnown || (parentId && parentId !== currentParentMessageId)\n\n if (isBranching) {\n // Branching: create new thread with shared history up to parent\n let sharedHistory: Message[] = []\n const parentThread = threads.find((thread) =>\n thread.history.some((msg) => msg.external_id === branchFrom)\n )\n if (parentThread) {\n const parentIndex = parentThread.history.findIndex(\n (msg) => msg.external_id === branchFrom\n )\n if (parentIndex !== -1) {\n sharedHistory = parentThread.history.slice(0, parentIndex + 1)\n }\n }\n threads.push({\n history: [...sharedHistory, userMessage],\n leaf_message_ext_id: userMessage.external_id,\n })\n } else if (parentMessageId) {\n // Appending to selected thread\n const threadIndex = threads.findIndex((t) => t.leaf_message_ext_id === parentMessageId)\n if (threadIndex !== -1) {\n threads[threadIndex] = {\n ...threads[threadIndex],\n history: [...threads[threadIndex].history, userMessage],\n leaf_message_ext_id: userMessage.external_id,\n }\n } else {\n threads.push({\n history: [userMessage],\n leaf_message_ext_id: userMessage.external_id,\n })\n }\n } else {\n // New conversation or appending to current thread\n if (threads.length > 0) {\n threads[threads.length - 1] = {\n ...threads[threads.length - 1],\n history: [...threads[threads.length - 1].history, userMessage],\n leaf_message_ext_id: userMessage.external_id,\n }\n } else {\n threads.push({\n history: [userMessage],\n leaf_message_ext_id: userMessage.external_id,\n })\n }\n }\n\n return { ...oldData, threads }\n }\n )\n}\n\n/**\n * Update an existing user message in the cache (e.g., status change from queued to completed).\n * Returns true if the message was found and updated, false otherwise.\n */\nexport function updateUserMessageInCache(\n queryClient: QueryClient,\n conversationId: string,\n userMessage: Message\n): boolean {\n let found = false\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n const updated = {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === userMessage.external_id) {\n found = true\n return { ...msg, ...userMessage }\n }\n return msg\n }),\n })),\n }\n return updated\n }\n )\n return found\n}\n\n/** Update only the transient state of a cached user message. */\nexport function updateUserMessageStateInCache(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n status: Message['status'],\n isLoading: boolean\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((message: Message) =>\n message.external_id === messageId ? { ...message, status, isLoading } : message\n ),\n })),\n }\n }\n )\n}\n\n/** Settle the oldest queued prompt matching an interjection step's content. */\nexport function completeQueuedUserMessageByContent(\n queryClient: QueryClient,\n conversationId: string,\n content: string\n): boolean {\n let completed = false\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((message: Message) => {\n if (\n !completed &&\n message.role === 'user' &&\n message.status === 'queued' &&\n message.content === content\n ) {\n completed = true\n return { ...message, status: 'completed', isLoading: false }\n }\n return message\n }),\n })),\n }\n }\n )\n return completed\n}\n\n/**\n * The text of a steering interjection that a run picked up, or null for any other item.\n *\n * The backend reports a queued prompt it steered into the run as a reasoning item of\n * kind `interjection` (`arbi.step`); the \"Your message\" label is the fallback for a\n * backend that predates that field.\n */\nexport function getInterjectionText(item: unknown): string | null {\n const candidate = item as {\n type?: string\n arbi?: { label?: string; step?: string }\n summary?: unknown\n } | null\n if (\n candidate?.type !== 'reasoning' ||\n (candidate.arbi?.step !== 'interjection' && candidate.arbi?.label !== 'Your message')\n ) {\n return null\n }\n const text = Array.isArray(candidate.summary)\n ? (candidate.summary as Array<{ text?: string }>).map((c) => c.text ?? '').join('')\n : ''\n return text || null\n}\n\n/**\n * Whether the thread that ends at `leafId` contains `messageId`, i.e. `leafId` is\n * `messageId` itself or a later turn in the same line.\n */\nexport function threadEndingAtContains(\n queryClient: QueryClient,\n conversationId: string,\n leafId: string,\n messageId: string\n): boolean {\n const data = queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(conversationId))\n const thread = data?.threads?.find((t: Thread) => t.leaf_message_ext_id === leafId)\n return !!thread?.history.some((m: Message) => m.external_id === messageId)\n}\n\n/**\n * When the run's assistant message is already in the cache, the moment it was created (ms),\n * so a reattached live timer keeps counting from the run's real start instead of from the\n * attach. Undefined when the row isn't loaded yet or has no usable timestamp.\n */\nexport function getRunStartedAt(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): number | undefined {\n const data = queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(conversationId))\n const message = data?.threads\n .flatMap((thread: Thread) => thread.history)\n .find((m: Message) => m.external_id === messageId)\n const startedAt = message?.created_at ? Date.parse(message.created_at) : NaN\n // Never in the future: a server clock ahead of this one would show a negative timer.\n return Number.isFinite(startedAt) ? Math.min(startedAt, Date.now()) : undefined\n}\n\n/**\n * Ensure an assistant message row exists in the cache for a run we're ATTACHING to\n * (foregrounding a background run in the conversation view). Unlike\n * `addAssistantMessageToCache`, this is idempotent: if the run's assistant message\n * is already present (loaded from history), it just flips `isLoading` on; otherwise\n * it appends a loading placeholder to the last thread so the live steps/answer have\n * a row to accumulate under. No-op when the threads cache hasn't loaded yet.\n */\nexport function ensureAssistantMessageLoading(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n const exists = oldData.threads.some((t: Thread) =>\n t.history.some((m: Message) => m.external_id === messageId)\n )\n if (exists) {\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId ? { ...msg, isLoading: true } : msg\n ),\n })),\n }\n }\n\n const placeholder: Message = {\n role: 'assistant',\n content: '',\n external_id: messageId,\n created_at: new Date().toISOString(),\n config_ext_id: null,\n created_by_ext_id: '',\n conversation_ext_id: conversationId,\n tokens: 0,\n status: 'in_progress',\n isLoading: true,\n }\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread, index: number) =>\n index === oldData.threads.length - 1\n ? {\n ...thread,\n history: [...thread.history, placeholder],\n leaf_message_ext_id: placeholder.external_id,\n }\n : thread\n ),\n }\n }\n )\n}\n\n/**\n * Replace an assistant message's content outright. Used when attaching to a\n * background run (`response.output_text.done` carries the whole answer, not\n * deltas), and at the one moment a live stream's body legitimately loses text:\n * the answer item settles and replaces the interim narration lines accumulated\n * during the turn (see handleOutputItemDone).\n */\nexport function setMessageContent(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n content: string\n): void {\n discardStreamingTokensForMessage(conversationId, messageId)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId ? { ...msg, content } : msg\n ),\n })),\n }\n }\n )\n}\n\n/**\n * Record that a narration item just settled: everything streamed so far is now\n * superseded prose, and whatever arrives next is the live segment.\n *\n * Buffered tokens are flushed first \u2014 the boundary is a character offset into\n * `content`, so it is only correct once every delta for the settled item has\n * actually landed in the cache.\n *\n * Also guarantees the block separator. Items are concatenated into one string,\n * so a paragraph break between two of them depended entirely on the model\n * ending its prose with newlines. When it did not, the next item ran on\n * mid-line (\"\u2026in parallel.Step 2: Read the relevant document\") \u2014 the boundary\n * has to supply the break itself.\n */\nexport function markNarrationSettled(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n flushStreamingTokens(queryClient)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id !== messageId) return msg\n const settled = (msg.content ?? '').replace(/\\s+$/, '')\n if (!settled) return msg\n const content = `${settled}\\n\\n`\n return { ...msg, content, settledNarrationLength: content.length }\n }),\n })),\n }\n }\n )\n}\n\n/**\n * Take a settled narration item's text out of a streaming answer's body. The item's deltas were\n * appended verbatim, so its text is in the body as streamed, normally at the end (the server\n * settles a narration item before anything else streams). The text stays in the steps trace.\n */\nexport function removeSettledNarration(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n /** The settled item's `content` parts. */\n itemContent: unknown\n): void {\n const text = Array.isArray(itemContent)\n ? (itemContent as Array<{ text?: string }>).map((c) => c.text ?? '').join('')\n : ''\n if (!text.trim()) return\n flushStreamingTokens(queryClient)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id !== messageId) return msg\n const body = msg.content ?? ''\n const at = body.lastIndexOf(text)\n if (at === -1) return msg\n const rest = body.slice(0, at) + body.slice(at + text.length)\n const content = rest.trim() ? rest : ''\n // The dimmed prefix cannot reach past the text that is left.\n const settled = Math.min(msg.settledNarrationLength ?? 0, content.length)\n return { ...msg, content, settledNarrationLength: settled || undefined }\n }),\n })),\n }\n }\n )\n}\n\n/**\n * Add an assistant message placeholder to the cache (for streaming), placed right after the\n * user message it answers.\n *\n * Follow-ups sent while a turn runs are saved at once, each with its own answer row (status\n * `queued`), so when a queued turn starts its user message may no longer be the thread's leaf:\n * later follow-ups already sit below it. The answer then goes right after its user message, not\n * at the end, and a stored queued row (loaded by a refetch) is started in place, not duplicated.\n *\n * @returns false when the user message was named but is not in the cache, so the answer could\n * only be appended to the last thread; the caller re-reads the thread to correct it.\n */\nexport function addAssistantMessageToCache(\n queryClient: QueryClient,\n conversationId: string,\n assistantMessage: Message,\n /** The user message this answers. Its thread gets the answer; else the last thread. */\n userMessageId?: string | null\n): boolean {\n let placed = true\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n const answerId = assistantMessage.external_id\n\n // The server stored this answer row already (queued): start it where it is.\n const stored = oldData.threads.some((t: Thread) =>\n t.history.some((m: Message) => m.external_id === answerId)\n )\n if (stored) {\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((m: Message) =>\n m.external_id === answerId\n ? { ...m, status: assistantMessage.status, isLoading: assistantMessage.isLoading }\n : m\n ),\n })),\n }\n }\n\n // The user message ends a thread: the answer becomes that thread's new leaf.\n const leafIndex = userMessageId\n ? oldData.threads.findIndex((t: Thread) => t.leaf_message_ext_id === userMessageId)\n : -1\n // Follow-ups are queued after the user message: insert the answer right after it.\n let holderIndex = -1\n if (userMessageId && leafIndex === -1) {\n oldData.threads.forEach((t: Thread, index: number) => {\n if (t.history.some((m: Message) => m.external_id === userMessageId)) holderIndex = index\n })\n }\n if (userMessageId && leafIndex === -1 && holderIndex === -1) placed = false\n const appendIndex = leafIndex !== -1 ? leafIndex : oldData.threads.length - 1\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread, index: number) => {\n if (holderIndex !== -1) {\n if (index !== holderIndex) return thread\n const at = thread.history.findIndex((m: Message) => m.external_id === userMessageId)\n const history = [...thread.history]\n history.splice(at + 1, 0, assistantMessage)\n return { ...thread, history }\n }\n if (index === appendIndex) {\n return {\n ...thread,\n history: [...thread.history, assistantMessage],\n leaf_message_ext_id: answerId,\n }\n }\n return thread\n }),\n }\n }\n )\n return placed\n}\n\n/**\n * Internal helper that synchronously writes a chunk of text onto an assistant\n * message's content. Called by the rAF flusher below and by tests that want\n * deterministic behavior.\n */\nfunction applyTokenChunkToCache(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n chunk: string\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === messageId) {\n return { ...msg, content: msg.content + chunk }\n }\n return msg\n }),\n })),\n }\n }\n )\n}\n\n/**\n * Per-stream pending token buffer. We coalesce every token that arrives in the\n * same frame into a single string, then commit it to React Query once on the\n * next animation frame. This turns a 20\u201330 Hz stream of full-tree clones into\n * ~60 Hz at most, and ensures <Message> only re-renders once per frame even\n * when the model emits many deltas in quick succession.\n */\ninterface PendingTokenEntry {\n conversationId: string\n messageId: string\n buffer: string\n}\n\nconst pendingTokens = new Map<string, PendingTokenEntry>()\nlet rafHandle: number | null = null\nlet rafSchedule: ((cb: () => void) => number) | null = null\nlet rafCancel: ((handle: number) => void) | null = null\n\nfunction getRafSchedule(): (cb: () => void) => number {\n if (rafSchedule) return rafSchedule\n if (typeof globalThis.requestAnimationFrame === 'function') {\n rafSchedule = (cb) => globalThis.requestAnimationFrame(cb)\n rafCancel = (h) => globalThis.cancelAnimationFrame(h)\n } else {\n // SSR / test fallback \u2014 use a microtask-ish timeout.\n rafSchedule = (cb) => {\n const id = setTimeout(cb, 16) as unknown as number\n return id\n }\n rafCancel = (h) => clearTimeout(h as unknown as ReturnType<typeof setTimeout>)\n }\n return rafSchedule\n}\n\nfunction flushPendingTokens(queryClient: QueryClient): void {\n rafHandle = null\n if (pendingTokens.size === 0) return\n // Snapshot and clear before writing, so tokens that arrive while we flush\n // are scheduled for the next frame rather than dropped.\n const entries = Array.from(pendingTokens.values())\n pendingTokens.clear()\n for (const entry of entries) {\n if (entry.buffer.length === 0) continue\n applyTokenChunkToCache(queryClient, entry.conversationId, entry.messageId, entry.buffer)\n }\n}\n\n/**\n * Append streaming token content to an assistant message.\n *\n * Tokens are buffered and flushed once per animation frame. Within a single\n * frame all deltas targeting the same message coalesce into one cache write,\n * so the React tree is diffed at most ~60 times/sec regardless of the model's\n * emit rate. A terminal event should call `flushStreamingTokens()` before\n * committing final metadata so no buffered text is lost.\n */\nexport function appendTokenToMessage(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n tokenContent: string\n): void {\n if (!tokenContent) return\n const key = `${conversationId}::${messageId}`\n const existing = pendingTokens.get(key)\n if (existing) {\n existing.buffer += tokenContent\n } else {\n pendingTokens.set(key, { conversationId, messageId, buffer: tokenContent })\n }\n if (rafHandle === null) {\n const schedule = getRafSchedule()\n rafHandle = schedule(() => flushPendingTokens(queryClient))\n }\n}\n\n/**\n * Force any buffered tokens to be committed to the cache immediately.\n * Call this from terminal handlers (metadata arrival, error, abort) so that\n * the final message reflects every token the server sent before the commit.\n */\nexport function flushStreamingTokens(queryClient: QueryClient): void {\n if (rafHandle !== null && rafCancel) {\n rafCancel(rafHandle)\n rafHandle = null\n }\n flushPendingTokens(queryClient)\n}\n\n/**\n * Drop any buffered tokens for a specific message without writing them.\n * Used when a stream resets content (agent-step transitions) so stale\n * deltas from the previous phase don't clobber the fresh buffer.\n */\nexport function discardStreamingTokensForMessage(conversationId: string, messageId: string): void {\n pendingTokens.delete(`${conversationId}::${messageId}`)\n}\n\n/**\n * Test-only hook: clear all pending buffers and cancel the scheduled flush.\n * @internal\n */\nexport function __resetStreamingTokenBufferForTests(): void {\n if (rafHandle !== null && rafCancel) {\n rafCancel(rafHandle)\n }\n rafHandle = null\n pendingTokens.clear()\n}\n\n/**\n * Assistant messages whose body swap is waiting out the narration dwell,\n * keyed `conversationId::messageId` \u2192 timer handle.\n *\n * Two things read this, and both are the point:\n * - `commitFinalMessage` itself, so a second `response.completed` for the same\n * message replaces the pending swap instead of racing it;\n * - `clearLoadingState`, which runs when the stream socket closes and would\n * otherwise un-fade the body a beat before the swap lands \u2014 splitting the\n * single resolving reflow back into two.\n */\nconst pendingFinalCommits = new Map<string, ReturnType<typeof setTimeout>>()\n\nconst finalCommitKey = (conversationId: string, messageId: string) =>\n `${conversationId}::${messageId}`\n\n/** Is this message's resolving commit still queued behind the dwell? */\nexport function hasPendingFinalCommit(conversationId: string, messageId: string): boolean {\n return pendingFinalCommits.has(finalCommitKey(conversationId, messageId))\n}\n\nfunction cancelPendingFinalCommit(conversationId: string, messageId: string): void {\n const key = finalCommitKey(conversationId, messageId)\n const handle = pendingFinalCommits.get(key)\n if (handle !== undefined) {\n clearTimeout(handle)\n pendingFinalCommits.delete(key)\n }\n}\n\n/**\n * Resolve a streamed assistant message: the server's answer replaces everything\n * the model said, the citations computed against that exact string arrive with\n * it, and `isLoading` clears \u2014 all in ONE write, so the window moves once.\n * Committing the content swap and the un-fading separately is what made it\n * jitter.\n *\n * `notBefore` (epoch ms, 0 = now) is the narration dwell: freshly-settled prose\n * is guaranteed its reading window before the swap is allowed to remove it.\n *\n * What waits is only the DISPLAY. Everything the rest of the app reasons about \u2014\n * `status` above all \u2014 lands immediately, because the leaf assistant message's\n * status is how the app knows whether a run is still in flight: hold it at\n * `in_progress` after the stream has closed and the conversation attaches a run\n * stream to its own finished turn (Conversation.tsx `attachResponseId`), which\n * spins into an infinite update loop. The early write is invisible: the body is\n * unchanged, the footer is still hidden behind `isLoading`, and the citation\n * markers the payload brings do not appear in the streamed text, so nothing\n * renders differently until the swap.\n */\nexport function commitFinalMessage(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n metadata: MessageResponse,\n notBefore = 0\n): void {\n cancelPendingFinalCommit(conversationId, messageId)\n cancelPendingFinalCommit(conversationId, metadata.external_id)\n const delay = Math.max(0, notBefore - Date.now())\n if (delay === 0) {\n updateMessageWithMetadata(queryClient, conversationId, messageId, metadata)\n return\n }\n // Buffered deltas are flushed rather than dropped, so the body the user is\n // reading is the complete one and does not twitch while it waits.\n flushStreamingTokens(queryClient)\n // Keyed by the SERVER's id: the early write rebuilds the message from the\n // payload, so that is the id it carries while the swap is pending \u2014 and the id\n // clearLoadingState will look up.\n const key = finalCommitKey(conversationId, metadata.external_id)\n applyMetadata(queryClient, conversationId, messageId, metadata, { holdBody: true })\n pendingFinalCommits.set(\n key,\n setTimeout(() => {\n pendingFinalCommits.delete(key)\n // The message now carries the server's id; the swap targets that.\n swapInFinalBody(queryClient, conversationId, metadata.external_id, metadata.content ?? '')\n }, delay)\n )\n}\n\n/** The one visible move: the answer takes the window and stops being provisional. */\nfunction swapInFinalBody(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n content: string\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId ? { ...msg, content, isLoading: false } : msg\n ),\n })),\n }\n }\n )\n}\n\n/**\n * Test-only hook: drop every deferred commit without running it.\n * @internal\n */\nexport function __resetPendingFinalCommitsForTests(): void {\n for (const handle of pendingFinalCommits.values()) clearTimeout(handle)\n pendingFinalCommits.clear()\n}\n\n/**\n * Update an assistant message with final metadata from server\n */\nexport function updateMessageWithMetadata(\n queryClient: QueryClient,\n conversationId: string,\n streamingMessageId: string,\n metadata: MessageResponse\n): void {\n applyMetadata(queryClient, conversationId, streamingMessageId, metadata, { holdBody: false })\n}\n\n/**\n * Rebuild a streaming assistant message from the server's final payload.\n *\n * `holdBody` keeps the body exactly as the reader currently sees it (and keeps it\n * provisional) while letting every other fact land \u2014 see commitFinalMessage for\n * why the facts must not wait.\n */\nfunction applyMetadata(\n queryClient: QueryClient,\n conversationId: string,\n streamingMessageId: string,\n metadata: MessageResponse,\n { holdBody }: { holdBody: boolean }\n): void {\n // Final content comes from server metadata \u2014 drop any buffered tokens so\n // we don't re-append what's about to be overwritten.\n if (!holdBody) discardStreamingTokensForMessage(conversationId, streamingMessageId)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n const serverAssistantId = metadata.external_id\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === streamingMessageId) {\n // Always use server metadata content \u2014 it includes citation markers\n // with offset_start/offset_end calculated against this exact string.\n // This REBUILDS the message from the server payload, so every\n // client-side field has to be carried over explicitly or it is\n // destroyed here at the end of the turn.\n return {\n ...metadata,\n isLoading: holdBody ? true : false,\n content: holdBody ? msg.content : metadata.content,\n agentSteps: msg.agentSteps,\n pendingUserInput: msg.pendingUserInput,\n // While the body is held for the narration dwell, the dimmed\n // prose must stay dimmed: dropping the boundary here would\n // un-fade it a beat before the swap, splitting the one resolving\n // reflow in two.\n settledNarrationLength: msg.settledNarrationLength,\n }\n }\n return msg\n }),\n leaf_message_ext_id:\n thread.leaf_message_ext_id === streamingMessageId\n ? serverAssistantId\n : thread.leaf_message_ext_id,\n })),\n }\n }\n )\n}\n\n/**\n * Mark a specific assistant message as failed in the conversation cache.\n * Called when WebSocket response_complete arrives with status='failed'.\n */\nexport function markMessageAsFailed(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n // Flush any buffered tokens first so the failed message still reflects\n // whatever the model produced before the failure.\n flushStreamingTokens(queryClient)\n // A failure supersedes a queued resolving commit \u2014 letting it fire afterwards\n // would quietly un-fail the message.\n cancelPendingFinalCommit(conversationId, messageId)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId\n ? { ...msg, status: 'failed' as const, isLoading: false }\n : msg\n ),\n })),\n }\n }\n )\n}\n\n/**\n * Clear loading state on all messages in a conversation.\n *\n * A message whose resolving commit is still queued behind the narration dwell is\n * left alone: clearing `isLoading` early would un-fade a body that still holds\n * the narration, and the real commit would then reflow it a second time \u2014 the\n * two-step ending this design exists to remove. The pending commit clears\n * `isLoading` itself when it lands.\n */\nexport function clearLoadingState(queryClient: QueryClient, conversationId: string): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.isLoading && !hasPendingFinalCommit(conversationId, msg.external_id ?? '')\n ? { ...msg, isLoading: false }\n : msg\n ),\n })),\n }\n }\n )\n}\n\n/**\n * Append an agent step event to a message's agentSteps array\n */\nexport function applyOutputItemToMessage(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n ev: OutputItemDone\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id !== messageId) return msg\n const existing = msg.agentSteps || []\n // The id->index map is rebuilt from the current steps each call: the\n // cache is immutable, so there is nowhere to keep it, and it is O(n)\n // over a handful of steps. The reducer is the one home for protocol\n // logic \u2014 this function just persists its result.\n const { assign, resolve } = createIndexAssigner(existing)\n const updated = reduceOutputItem(existing, ev, assign, resolve)\n return updated === existing ? msg : { ...msg, agentSteps: updated }\n }),\n })),\n }\n }\n )\n\n // A sub-agent that just settled has persisted its own branch server-side\n // (task message + reply) \u2014 a whole new thread this conversation's cached\n // `threads` list has never seen. The map above only patches steps on\n // EXISTING messages, so without this the branch stays invisible (no open-\n // thread affordance, no branch badge) until something else happens to\n // refetch. `staleTime` on useConversationThreads is long specifically because\n // WebSocket/SSE traffic is expected to keep it fresh \u2014 this is that update.\n const arbi = ev.item?.arbi\n if (\n (arbi?.subagent_status === 'done' || arbi?.subagent_status === 'failed') &&\n arbi.task_message_ext_id\n ) {\n queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n }\n}\n\n/**\n * Persist the turn's final token/\u00A3 budget snapshot (from\n * response.completed) onto the assistant message. Distinct from\n * applyOutputItemToMessage's agentSteps: steps only ever cover\n * function_call/reasoning items, so they never carry the true final total \u2014\n * see the finalContextUsage doc comment on Message in types/ui.ts.\n */\nexport function applyFinalContextToMessage(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n context: Message['finalContextUsage']\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId ? { ...msg, finalContextUsage: context } : msg\n ),\n })),\n }\n }\n )\n}\n\nexport function setUserInputRequest(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n request: UserInputRequestEvent\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === messageId) {\n return { ...msg, pendingUserInput: request }\n }\n return msg\n }),\n })),\n }\n }\n )\n}\n\n/**\n * Reset the content of a message (clear the body).\n */\nexport function resetMessageContent(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n setMessageContent(queryClient, conversationId, messageId, '')\n}\n\n/**\n * Clear the pending user input request on a message\n */\nexport function clearUserInputRequest(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === messageId) {\n return { ...msg, pendingUserInput: null }\n }\n return msg\n }),\n })),\n }\n }\n )\n}\n"],
5
- "mappings": "AASA;AAAA,EACE;AAAA,EACA;AAAA,OAMK;AACP,SAAS,qBAAqB;AAKvB,SAAS,mBAAmB,gBAAwB;AACzD,SAAO,cAAc,oBAAoB,cAAc;AACzD;AAGO,MAAM,yBAAyB;AAAA,EACpC,WAAW,CAAC,EAAE,SAAS,MACrB,SAAS,CAAC,MAAM,UAAU,SAAS,CAAC,MAAM,mBAAmB,SAAS,CAAC,MAAM;AACjF;AAKO,SAAS,iBACd,aACA,gBACA,WACS;AACT,QAAM,OAAO,YAAY,aAA8B,mBAAmB,cAAc,CAAC;AACzF,UAAQ,MAAM,WAAW,CAAC,GAAG;AAAA,IAAK,CAAC,MACjC,EAAE,QAAQ;AAAA,MACR,CAAC,MACC,EAAE,gBAAgB,cAAc,EAAE,WAAW,iBAAiB,EAAE,WAAW;AAAA,IAC/E;AAAA,EACF;AACF;AAKO,SAAS,sBACd,aACA,gBACA,aACA,SAKM;AACN,QAAM,EAAE,UAAU,iBAAiB,uBAAuB,IAAI;AAE9D,cAAY;AAAA,IACV,mBAAmB,cAAc;AAAA,IACjC,CAAC,YAAyC;AACxC,UAAI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aACA,gBACA,WACM;AACN,oBAAkB,aAAa,gBAAgB,WAAW,EAAE;AAC9D;AAKO,SAAS,sBACd,aACA,gBACA,WACM;AACN,cAAY;AAAA,IACV,mBAAmB,cAAc;AAAA,IACjC,CAAC,YAAyC;AACxC,UAAI,CAAC,QAAS,QAAO;AAErB,aAAO;AAAA,QACL,GAAG;AAAA,QACH,SAAS,QAAQ,QAAQ,IAAI,CAAC,YAAoB;AAAA,UAChD,GAAG;AAAA,UACH,SAAS,OAAO,QAAQ,IAAI,CAAC,QAAiB;AAC5C,gBAAI,IAAI,gBAAgB,WAAW;AACjC,qBAAO,EAAE,GAAG,KAAK,kBAAkB,KAAK;AAAA,YAC1C;AACA,mBAAO;AAAA,UACT,CAAC;AAAA,QACH,EAAE;AAAA,MACJ;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/**\n * A conversation's threads in the query cache (`arbiQueryKeys.conversationThreads(id)`), and the\n * writers every chat engine and event uses on them: a turn's user and assistant messages, streamed\n * text (buffered per animation frame), settled output items, the resolving commit (held behind\n * the narration dwell), failure, loading state and pending questions.\n */\n\nimport type { QueryClient } from '@tanstack/react-query'\nimport type { components } from '@arbidocs/client'\nimport {\n reduceOutputItem,\n createIndexAssigner,\n type ChatMessage as Message,\n type OutputItemDone,\n type Thread,\n type ThreadsResponse,\n type UserInputRequestEvent,\n} from '@arbidocs/sdk/browser'\nimport { arbiQueryKeys } from '../hooks'\n\ntype MessageResponse = components['schemas']['MessageResponse']\n\n/** The query key of a conversation's threads. */\nexport function getThreadsQueryKey(conversationId: string) {\n return arbiQueryKeys.conversationThreads(conversationId)\n}\n\n/** Every conversation's cached threads (a filter for `invalidateQueries`, `getQueriesData`, \u2026). */\nexport const allConversationThreads = {\n predicate: ({ queryKey }: { queryKey: readonly unknown[] }) =>\n queryKey[0] === 'arbi' && queryKey[1] === 'conversations' && queryKey[3] === 'threads',\n}\n\n/**\n * Whether the conversation's cached threads are loaded and hold no message yet (a task's thread\n * opened before anyone wrote in it). Not loaded is not empty: nothing says so.\n */\nexport function isConversationEmpty(queryClient: QueryClient, conversationId: string): boolean {\n const data = queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(conversationId))\n return !!data && (data.threads ?? []).every((t: Thread) => t.history.length === 0)\n}\n\n/**\n * Whether the cached thread says a message is still being generated on the server\n */\nexport function isMessageRunning(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): boolean {\n const data = queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(conversationId))\n return (data?.threads ?? []).some((t: Thread) =>\n t.history.some(\n (m: Message) =>\n m.external_id === messageId && (m.status === 'in_progress' || m.status === 'queued')\n )\n )\n}\n\n/**\n * Add a user message to the conversation cache\n */\nexport function addUserMessageToCache(\n queryClient: QueryClient,\n conversationId: string,\n userMessage: Message,\n options: {\n parentId?: string | null\n parentMessageId?: string | null\n currentParentMessageId?: string | null\n }\n): void {\n const { parentId, parentMessageId, currentParentMessageId } = options\n\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) {\n return {\n conversation_ext_id: conversationId,\n threads: [\n {\n history: [userMessage],\n leaf_message_ext_id: userMessage.external_id,\n },\n ],\n }\n }\n\n const threads = [...(oldData.threads || [])]\n\n // The server's parent is authoritative. A follow-up sent while a turn generates names\n // that turn, but the server queues each one behind the follow-ups already waiting, so\n // it may answer it after a later turn. Placing it under the client's guess made ordered\n // follow-ups siblings (\"Branch 1 of 2\") instead of one line.\n const serverParentId = userMessage.parent_message_ext_id\n // A server parent that already has a reply is a real branch point.\n const serverParentKnown =\n !!serverParentId &&\n threads.some((t) => t.history.some((msg) => msg.external_id === serverParentId))\n // A follow-up queued behind another one is chained after that one's answer, which has not\n // streamed in yet. Until it does, the follow-up continues the thread ending at the queued\n // message. The client's guess (the running turn) would wrongly branch it off that turn.\n const queuedLeafIndex = threads.findIndex((t) =>\n t.history.some(\n (msg) => msg.external_id === t.leaf_message_ext_id && msg.status === 'queued'\n )\n )\n const continueIndex =\n serverParentId && !serverParentKnown\n ? queuedLeafIndex\n : threads.findIndex((t) => t.leaf_message_ext_id === serverParentId)\n if (serverParentId && continueIndex !== -1) {\n threads[continueIndex] = {\n ...threads[continueIndex],\n history: [...threads[continueIndex].history, userMessage],\n leaf_message_ext_id: userMessage.external_id,\n }\n return { ...oldData, threads }\n }\n\n const branchFrom = serverParentKnown ? serverParentId : parentId\n const isBranching = serverParentKnown || (parentId && parentId !== currentParentMessageId)\n\n if (isBranching) {\n // Branching: create new thread with shared history up to parent\n let sharedHistory: Message[] = []\n const parentThread = threads.find((thread) =>\n thread.history.some((msg) => msg.external_id === branchFrom)\n )\n if (parentThread) {\n const parentIndex = parentThread.history.findIndex(\n (msg) => msg.external_id === branchFrom\n )\n if (parentIndex !== -1) {\n sharedHistory = parentThread.history.slice(0, parentIndex + 1)\n }\n }\n threads.push({\n history: [...sharedHistory, userMessage],\n leaf_message_ext_id: userMessage.external_id,\n })\n } else if (parentMessageId) {\n // Appending to selected thread\n const threadIndex = threads.findIndex((t) => t.leaf_message_ext_id === parentMessageId)\n if (threadIndex !== -1) {\n threads[threadIndex] = {\n ...threads[threadIndex],\n history: [...threads[threadIndex].history, userMessage],\n leaf_message_ext_id: userMessage.external_id,\n }\n } else {\n threads.push({\n history: [userMessage],\n leaf_message_ext_id: userMessage.external_id,\n })\n }\n } else {\n // New conversation or appending to current thread\n if (threads.length > 0) {\n threads[threads.length - 1] = {\n ...threads[threads.length - 1],\n history: [...threads[threads.length - 1].history, userMessage],\n leaf_message_ext_id: userMessage.external_id,\n }\n } else {\n threads.push({\n history: [userMessage],\n leaf_message_ext_id: userMessage.external_id,\n })\n }\n }\n\n return { ...oldData, threads }\n }\n )\n}\n\n/**\n * Update an existing user message in the cache (e.g., status change from queued to completed).\n * Returns true if the message was found and updated, false otherwise.\n */\nexport function updateUserMessageInCache(\n queryClient: QueryClient,\n conversationId: string,\n userMessage: Message\n): boolean {\n let found = false\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n const updated = {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === userMessage.external_id) {\n found = true\n return { ...msg, ...userMessage }\n }\n return msg\n }),\n })),\n }\n return updated\n }\n )\n return found\n}\n\n/** Update only the transient state of a cached user message. */\nexport function updateUserMessageStateInCache(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n status: Message['status'],\n isLoading: boolean\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((message: Message) =>\n message.external_id === messageId ? { ...message, status, isLoading } : message\n ),\n })),\n }\n }\n )\n}\n\n/** Settle the oldest queued prompt matching an interjection step's content. */\nexport function completeQueuedUserMessageByContent(\n queryClient: QueryClient,\n conversationId: string,\n content: string\n): boolean {\n let completed = false\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((message: Message) => {\n if (\n !completed &&\n message.role === 'user' &&\n message.status === 'queued' &&\n message.content === content\n ) {\n completed = true\n return { ...message, status: 'completed', isLoading: false }\n }\n return message\n }),\n })),\n }\n }\n )\n return completed\n}\n\n/**\n * The text of a steering interjection that a run picked up, or null for any other item.\n *\n * The backend reports a queued prompt it steered into the run as a reasoning item of\n * kind `interjection` (`arbi.step`); the \"Your message\" label is the fallback for a\n * backend that predates that field.\n */\nexport function getInterjectionText(item: unknown): string | null {\n const candidate = item as {\n type?: string\n arbi?: { label?: string; step?: string }\n summary?: unknown\n } | null\n if (\n candidate?.type !== 'reasoning' ||\n (candidate.arbi?.step !== 'interjection' && candidate.arbi?.label !== 'Your message')\n ) {\n return null\n }\n const text = Array.isArray(candidate.summary)\n ? (candidate.summary as Array<{ text?: string }>).map((c) => c.text ?? '').join('')\n : ''\n return text || null\n}\n\n/**\n * Whether the thread that ends at `leafId` contains `messageId`, i.e. `leafId` is\n * `messageId` itself or a later turn in the same line.\n */\nexport function threadEndingAtContains(\n queryClient: QueryClient,\n conversationId: string,\n leafId: string,\n messageId: string\n): boolean {\n const data = queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(conversationId))\n const thread = data?.threads?.find((t: Thread) => t.leaf_message_ext_id === leafId)\n return !!thread?.history.some((m: Message) => m.external_id === messageId)\n}\n\n/**\n * When the run's assistant message is already in the cache, the moment it was created (ms),\n * so a reattached live timer keeps counting from the run's real start instead of from the\n * attach. Undefined when the row isn't loaded yet or has no usable timestamp.\n */\nexport function getRunStartedAt(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): number | undefined {\n const data = queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(conversationId))\n const message = data?.threads\n .flatMap((thread: Thread) => thread.history)\n .find((m: Message) => m.external_id === messageId)\n const startedAt = message?.created_at ? Date.parse(message.created_at) : NaN\n // Never in the future: a server clock ahead of this one would show a negative timer.\n return Number.isFinite(startedAt) ? Math.min(startedAt, Date.now()) : undefined\n}\n\n/**\n * Ensure an assistant message row exists in the cache for a run we're ATTACHING to\n * (foregrounding a background run in the conversation view). Unlike\n * `addAssistantMessageToCache`, this is idempotent: if the run's assistant message\n * is already present (loaded from history), it just flips `isLoading` on; otherwise\n * it appends a loading placeholder to the last thread so the live steps/answer have\n * a row to accumulate under. No-op when the threads cache hasn't loaded yet.\n */\nexport function ensureAssistantMessageLoading(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n const exists = oldData.threads.some((t: Thread) =>\n t.history.some((m: Message) => m.external_id === messageId)\n )\n if (exists) {\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId ? { ...msg, isLoading: true } : msg\n ),\n })),\n }\n }\n\n const placeholder: Message = {\n role: 'assistant',\n content: '',\n external_id: messageId,\n created_at: new Date().toISOString(),\n config_ext_id: null,\n created_by_ext_id: '',\n conversation_ext_id: conversationId,\n tokens: 0,\n status: 'in_progress',\n isLoading: true,\n }\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread, index: number) =>\n index === oldData.threads.length - 1\n ? {\n ...thread,\n history: [...thread.history, placeholder],\n leaf_message_ext_id: placeholder.external_id,\n }\n : thread\n ),\n }\n }\n )\n}\n\n/**\n * Replace an assistant message's content outright. Used when attaching to a\n * background run (`response.output_text.done` carries the whole answer, not\n * deltas), and at the one moment a live stream's body legitimately loses text:\n * the answer item settles and replaces the interim narration lines accumulated\n * during the turn (see handleOutputItemDone).\n */\nexport function setMessageContent(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n content: string\n): void {\n discardStreamingTokensForMessage(conversationId, messageId)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId ? { ...msg, content } : msg\n ),\n })),\n }\n }\n )\n}\n\n/**\n * Record that a narration item just settled: everything streamed so far is now\n * superseded prose, and whatever arrives next is the live segment.\n *\n * Buffered tokens are flushed first \u2014 the boundary is a character offset into\n * `content`, so it is only correct once every delta for the settled item has\n * actually landed in the cache.\n *\n * Also guarantees the block separator. Items are concatenated into one string,\n * so a paragraph break between two of them depended entirely on the model\n * ending its prose with newlines. When it did not, the next item ran on\n * mid-line (\"\u2026in parallel.Step 2: Read the relevant document\") \u2014 the boundary\n * has to supply the break itself.\n */\nexport function markNarrationSettled(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n flushStreamingTokens(queryClient)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id !== messageId) return msg\n const settled = (msg.content ?? '').replace(/\\s+$/, '')\n if (!settled) return msg\n const content = `${settled}\\n\\n`\n return { ...msg, content, settledNarrationLength: content.length }\n }),\n })),\n }\n }\n )\n}\n\n/**\n * Take a settled narration item's text out of a streaming answer's body. The item's deltas were\n * appended verbatim, so its text is in the body as streamed, normally at the end (the server\n * settles a narration item before anything else streams). The text stays in the steps trace.\n */\nexport function removeSettledNarration(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n /** The settled item's `content` parts. */\n itemContent: unknown\n): void {\n const text = Array.isArray(itemContent)\n ? (itemContent as Array<{ text?: string }>).map((c) => c.text ?? '').join('')\n : ''\n if (!text.trim()) return\n flushStreamingTokens(queryClient)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id !== messageId) return msg\n const body = msg.content ?? ''\n const at = body.lastIndexOf(text)\n if (at === -1) return msg\n const rest = body.slice(0, at) + body.slice(at + text.length)\n const content = rest.trim() ? rest : ''\n // The dimmed prefix cannot reach past the text that is left.\n const settled = Math.min(msg.settledNarrationLength ?? 0, content.length)\n return { ...msg, content, settledNarrationLength: settled || undefined }\n }),\n })),\n }\n }\n )\n}\n\n/**\n * Add an assistant message placeholder to the cache (for streaming), placed right after the\n * user message it answers.\n *\n * Follow-ups sent while a turn runs are saved at once, each with its own answer row (status\n * `queued`), so when a queued turn starts its user message may no longer be the thread's leaf:\n * later follow-ups already sit below it. The answer then goes right after its user message, not\n * at the end, and a stored queued row (loaded by a refetch) is started in place, not duplicated.\n *\n * @returns false when the user message was named but is not in the cache, so the answer could\n * only be appended to the last thread; the caller re-reads the thread to correct it.\n */\nexport function addAssistantMessageToCache(\n queryClient: QueryClient,\n conversationId: string,\n assistantMessage: Message,\n /** The user message this answers. Its thread gets the answer; else the last thread. */\n userMessageId?: string | null\n): boolean {\n let placed = true\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n const answerId = assistantMessage.external_id\n\n // The server stored this answer row already (queued): start it where it is.\n const stored = oldData.threads.some((t: Thread) =>\n t.history.some((m: Message) => m.external_id === answerId)\n )\n if (stored) {\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((m: Message) =>\n m.external_id === answerId\n ? { ...m, status: assistantMessage.status, isLoading: assistantMessage.isLoading }\n : m\n ),\n })),\n }\n }\n\n // The user message ends a thread: the answer becomes that thread's new leaf.\n const leafIndex = userMessageId\n ? oldData.threads.findIndex((t: Thread) => t.leaf_message_ext_id === userMessageId)\n : -1\n // Follow-ups are queued after the user message: insert the answer right after it.\n let holderIndex = -1\n if (userMessageId && leafIndex === -1) {\n oldData.threads.forEach((t: Thread, index: number) => {\n if (t.history.some((m: Message) => m.external_id === userMessageId)) holderIndex = index\n })\n }\n if (userMessageId && leafIndex === -1 && holderIndex === -1) placed = false\n const appendIndex = leafIndex !== -1 ? leafIndex : oldData.threads.length - 1\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread, index: number) => {\n if (holderIndex !== -1) {\n if (index !== holderIndex) return thread\n const at = thread.history.findIndex((m: Message) => m.external_id === userMessageId)\n const history = [...thread.history]\n history.splice(at + 1, 0, assistantMessage)\n return { ...thread, history }\n }\n if (index === appendIndex) {\n return {\n ...thread,\n history: [...thread.history, assistantMessage],\n leaf_message_ext_id: answerId,\n }\n }\n return thread\n }),\n }\n }\n )\n return placed\n}\n\n/**\n * Internal helper that synchronously writes a chunk of text onto an assistant\n * message's content. Called by the rAF flusher below and by tests that want\n * deterministic behavior.\n */\nfunction applyTokenChunkToCache(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n chunk: string\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === messageId) {\n return { ...msg, content: msg.content + chunk }\n }\n return msg\n }),\n })),\n }\n }\n )\n}\n\n/**\n * Per-stream pending token buffer. We coalesce every token that arrives in the\n * same frame into a single string, then commit it to React Query once on the\n * next animation frame. This turns a 20\u201330 Hz stream of full-tree clones into\n * ~60 Hz at most, and ensures <Message> only re-renders once per frame even\n * when the model emits many deltas in quick succession.\n */\ninterface PendingTokenEntry {\n conversationId: string\n messageId: string\n buffer: string\n}\n\nconst pendingTokens = new Map<string, PendingTokenEntry>()\nlet rafHandle: number | null = null\nlet rafSchedule: ((cb: () => void) => number) | null = null\nlet rafCancel: ((handle: number) => void) | null = null\n\nfunction getRafSchedule(): (cb: () => void) => number {\n if (rafSchedule) return rafSchedule\n if (typeof globalThis.requestAnimationFrame === 'function') {\n rafSchedule = (cb) => globalThis.requestAnimationFrame(cb)\n rafCancel = (h) => globalThis.cancelAnimationFrame(h)\n } else {\n // SSR / test fallback \u2014 use a microtask-ish timeout.\n rafSchedule = (cb) => {\n const id = setTimeout(cb, 16) as unknown as number\n return id\n }\n rafCancel = (h) => clearTimeout(h as unknown as ReturnType<typeof setTimeout>)\n }\n return rafSchedule\n}\n\nfunction flushPendingTokens(queryClient: QueryClient): void {\n rafHandle = null\n if (pendingTokens.size === 0) return\n // Snapshot and clear before writing, so tokens that arrive while we flush\n // are scheduled for the next frame rather than dropped.\n const entries = Array.from(pendingTokens.values())\n pendingTokens.clear()\n for (const entry of entries) {\n if (entry.buffer.length === 0) continue\n applyTokenChunkToCache(queryClient, entry.conversationId, entry.messageId, entry.buffer)\n }\n}\n\n/**\n * Append streaming token content to an assistant message.\n *\n * Tokens are buffered and flushed once per animation frame. Within a single\n * frame all deltas targeting the same message coalesce into one cache write,\n * so the React tree is diffed at most ~60 times/sec regardless of the model's\n * emit rate. A terminal event should call `flushStreamingTokens()` before\n * committing final metadata so no buffered text is lost.\n */\nexport function appendTokenToMessage(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n tokenContent: string\n): void {\n if (!tokenContent) return\n const key = `${conversationId}::${messageId}`\n const existing = pendingTokens.get(key)\n if (existing) {\n existing.buffer += tokenContent\n } else {\n pendingTokens.set(key, { conversationId, messageId, buffer: tokenContent })\n }\n if (rafHandle === null) {\n const schedule = getRafSchedule()\n rafHandle = schedule(() => flushPendingTokens(queryClient))\n }\n}\n\n/**\n * Force any buffered tokens to be committed to the cache immediately.\n * Call this from terminal handlers (metadata arrival, error, abort) so that\n * the final message reflects every token the server sent before the commit.\n */\nexport function flushStreamingTokens(queryClient: QueryClient): void {\n if (rafHandle !== null && rafCancel) {\n rafCancel(rafHandle)\n rafHandle = null\n }\n flushPendingTokens(queryClient)\n}\n\n/**\n * Drop any buffered tokens for a specific message without writing them.\n * Used when a stream resets content (agent-step transitions) so stale\n * deltas from the previous phase don't clobber the fresh buffer.\n */\nexport function discardStreamingTokensForMessage(conversationId: string, messageId: string): void {\n pendingTokens.delete(`${conversationId}::${messageId}`)\n}\n\n/**\n * Test-only hook: clear all pending buffers and cancel the scheduled flush.\n * @internal\n */\nexport function __resetStreamingTokenBufferForTests(): void {\n if (rafHandle !== null && rafCancel) {\n rafCancel(rafHandle)\n }\n rafHandle = null\n pendingTokens.clear()\n}\n\n/**\n * Assistant messages whose body swap is waiting out the narration dwell,\n * keyed `conversationId::messageId` \u2192 timer handle.\n *\n * Two things read this, and both are the point:\n * - `commitFinalMessage` itself, so a second `response.completed` for the same\n * message replaces the pending swap instead of racing it;\n * - `clearLoadingState`, which runs when the stream socket closes and would\n * otherwise un-fade the body a beat before the swap lands \u2014 splitting the\n * single resolving reflow back into two.\n */\nconst pendingFinalCommits = new Map<string, ReturnType<typeof setTimeout>>()\n\nconst finalCommitKey = (conversationId: string, messageId: string) =>\n `${conversationId}::${messageId}`\n\n/** Is this message's resolving commit still queued behind the dwell? */\nexport function hasPendingFinalCommit(conversationId: string, messageId: string): boolean {\n return pendingFinalCommits.has(finalCommitKey(conversationId, messageId))\n}\n\nfunction cancelPendingFinalCommit(conversationId: string, messageId: string): void {\n const key = finalCommitKey(conversationId, messageId)\n const handle = pendingFinalCommits.get(key)\n if (handle !== undefined) {\n clearTimeout(handle)\n pendingFinalCommits.delete(key)\n }\n}\n\n/**\n * Resolve a streamed assistant message: the server's answer replaces everything\n * the model said, the citations computed against that exact string arrive with\n * it, and `isLoading` clears \u2014 all in ONE write, so the window moves once.\n * Committing the content swap and the un-fading separately is what made it\n * jitter.\n *\n * `notBefore` (epoch ms, 0 = now) is the narration dwell: freshly-settled prose\n * is guaranteed its reading window before the swap is allowed to remove it.\n *\n * What waits is only the DISPLAY. Everything the rest of the app reasons about \u2014\n * `status` above all \u2014 lands immediately, because the leaf assistant message's\n * status is how the app knows whether a run is still in flight: hold it at\n * `in_progress` after the stream has closed and the conversation attaches a run\n * stream to its own finished turn (Conversation.tsx `attachResponseId`), which\n * spins into an infinite update loop. The early write is invisible: the body is\n * unchanged, the footer is still hidden behind `isLoading`, and the citation\n * markers the payload brings do not appear in the streamed text, so nothing\n * renders differently until the swap.\n */\nexport function commitFinalMessage(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n metadata: MessageResponse,\n notBefore = 0\n): void {\n cancelPendingFinalCommit(conversationId, messageId)\n cancelPendingFinalCommit(conversationId, metadata.external_id)\n const delay = Math.max(0, notBefore - Date.now())\n if (delay === 0) {\n updateMessageWithMetadata(queryClient, conversationId, messageId, metadata)\n return\n }\n // Buffered deltas are flushed rather than dropped, so the body the user is\n // reading is the complete one and does not twitch while it waits.\n flushStreamingTokens(queryClient)\n // Keyed by the SERVER's id: the early write rebuilds the message from the\n // payload, so that is the id it carries while the swap is pending \u2014 and the id\n // clearLoadingState will look up.\n const key = finalCommitKey(conversationId, metadata.external_id)\n applyMetadata(queryClient, conversationId, messageId, metadata, { holdBody: true })\n pendingFinalCommits.set(\n key,\n setTimeout(() => {\n pendingFinalCommits.delete(key)\n // The message now carries the server's id; the swap targets that.\n swapInFinalBody(queryClient, conversationId, metadata.external_id, metadata.content ?? '')\n }, delay)\n )\n}\n\n/** The one visible move: the answer takes the window and stops being provisional. */\nfunction swapInFinalBody(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n content: string\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId ? { ...msg, content, isLoading: false } : msg\n ),\n })),\n }\n }\n )\n}\n\n/**\n * Test-only hook: drop every deferred commit without running it.\n * @internal\n */\nexport function __resetPendingFinalCommitsForTests(): void {\n for (const handle of pendingFinalCommits.values()) clearTimeout(handle)\n pendingFinalCommits.clear()\n}\n\n/**\n * Update an assistant message with final metadata from server\n */\nexport function updateMessageWithMetadata(\n queryClient: QueryClient,\n conversationId: string,\n streamingMessageId: string,\n metadata: MessageResponse\n): void {\n applyMetadata(queryClient, conversationId, streamingMessageId, metadata, { holdBody: false })\n}\n\n/**\n * Rebuild a streaming assistant message from the server's final payload.\n *\n * `holdBody` keeps the body exactly as the reader currently sees it (and keeps it\n * provisional) while letting every other fact land \u2014 see commitFinalMessage for\n * why the facts must not wait.\n */\nfunction applyMetadata(\n queryClient: QueryClient,\n conversationId: string,\n streamingMessageId: string,\n metadata: MessageResponse,\n { holdBody }: { holdBody: boolean }\n): void {\n // Final content comes from server metadata \u2014 drop any buffered tokens so\n // we don't re-append what's about to be overwritten.\n if (!holdBody) discardStreamingTokensForMessage(conversationId, streamingMessageId)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n const serverAssistantId = metadata.external_id\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === streamingMessageId) {\n // Always use server metadata content \u2014 it includes citation markers\n // with offset_start/offset_end calculated against this exact string.\n // This REBUILDS the message from the server payload, so every\n // client-side field has to be carried over explicitly or it is\n // destroyed here at the end of the turn.\n return {\n ...metadata,\n isLoading: holdBody ? true : false,\n content: holdBody ? msg.content : metadata.content,\n agentSteps: msg.agentSteps,\n pendingUserInput: msg.pendingUserInput,\n // While the body is held for the narration dwell, the dimmed\n // prose must stay dimmed: dropping the boundary here would\n // un-fade it a beat before the swap, splitting the one resolving\n // reflow in two.\n settledNarrationLength: msg.settledNarrationLength,\n }\n }\n return msg\n }),\n leaf_message_ext_id:\n thread.leaf_message_ext_id === streamingMessageId\n ? serverAssistantId\n : thread.leaf_message_ext_id,\n })),\n }\n }\n )\n}\n\n/**\n * Mark a specific assistant message as failed in the conversation cache.\n * Called when WebSocket response_complete arrives with status='failed'.\n */\nexport function markMessageAsFailed(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n // Flush any buffered tokens first so the failed message still reflects\n // whatever the model produced before the failure.\n flushStreamingTokens(queryClient)\n // A failure supersedes a queued resolving commit \u2014 letting it fire afterwards\n // would quietly un-fail the message.\n cancelPendingFinalCommit(conversationId, messageId)\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId\n ? { ...msg, status: 'failed' as const, isLoading: false }\n : msg\n ),\n })),\n }\n }\n )\n}\n\n/**\n * Clear loading state on all messages in a conversation.\n *\n * A message whose resolving commit is still queued behind the narration dwell is\n * left alone: clearing `isLoading` early would un-fade a body that still holds\n * the narration, and the real commit would then reflow it a second time \u2014 the\n * two-step ending this design exists to remove. The pending commit clears\n * `isLoading` itself when it lands.\n */\nexport function clearLoadingState(queryClient: QueryClient, conversationId: string): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.isLoading && !hasPendingFinalCommit(conversationId, msg.external_id ?? '')\n ? { ...msg, isLoading: false }\n : msg\n ),\n })),\n }\n }\n )\n}\n\n/**\n * Append an agent step event to a message's agentSteps array\n */\nexport function applyOutputItemToMessage(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n ev: OutputItemDone\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id !== messageId) return msg\n const existing = msg.agentSteps || []\n // The id->index map is rebuilt from the current steps each call: the\n // cache is immutable, so there is nowhere to keep it, and it is O(n)\n // over a handful of steps. The reducer is the one home for protocol\n // logic \u2014 this function just persists its result.\n const { assign, resolve } = createIndexAssigner(existing)\n const updated = reduceOutputItem(existing, ev, assign, resolve)\n return updated === existing ? msg : { ...msg, agentSteps: updated }\n }),\n })),\n }\n }\n )\n\n // A sub-agent that just settled has persisted its own branch server-side\n // (task message + reply) \u2014 a whole new thread this conversation's cached\n // `threads` list has never seen. The map above only patches steps on\n // EXISTING messages, so without this the branch stays invisible (no open-\n // thread affordance, no branch badge) until something else happens to\n // refetch. `staleTime` on useConversationThreads is long specifically because\n // WebSocket/SSE traffic is expected to keep it fresh \u2014 this is that update.\n const arbi = ev.item?.arbi\n if (\n (arbi?.subagent_status === 'done' || arbi?.subagent_status === 'failed') &&\n arbi.task_message_ext_id\n ) {\n queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n }\n}\n\n/**\n * Persist the turn's final token/\u00A3 budget snapshot (from\n * response.completed) onto the assistant message. Distinct from\n * applyOutputItemToMessage's agentSteps: steps only ever cover\n * function_call/reasoning items, so they never carry the true final total \u2014\n * see the finalContextUsage doc comment on Message in types/ui.ts.\n */\nexport function applyFinalContextToMessage(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n context: Message['finalContextUsage']\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) =>\n msg.external_id === messageId ? { ...msg, finalContextUsage: context } : msg\n ),\n })),\n }\n }\n )\n}\n\nexport function setUserInputRequest(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string,\n request: UserInputRequestEvent\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === messageId) {\n return { ...msg, pendingUserInput: request }\n }\n return msg\n }),\n })),\n }\n }\n )\n}\n\n/**\n * Reset the content of a message (clear the body).\n */\nexport function resetMessageContent(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n setMessageContent(queryClient, conversationId, messageId, '')\n}\n\n/**\n * Clear the pending user input request on a message\n */\nexport function clearUserInputRequest(\n queryClient: QueryClient,\n conversationId: string,\n messageId: string\n): void {\n queryClient.setQueryData(\n getThreadsQueryKey(conversationId),\n (oldData: ThreadsResponse | undefined) => {\n if (!oldData) return oldData\n\n return {\n ...oldData,\n threads: oldData.threads.map((thread: Thread) => ({\n ...thread,\n history: thread.history.map((msg: Message) => {\n if (msg.external_id === messageId) {\n return { ...msg, pendingUserInput: null }\n }\n return msg\n }),\n })),\n }\n }\n )\n}\n"],
5
+ "mappings": "AASA;AAAA,EACE;AAAA,EACA;AAAA,OAMK;AACP,SAAS,qBAAqB;AAKvB,SAAS,mBAAmB,gBAAwB;AACzD,SAAO,cAAc,oBAAoB,cAAc;AACzD;AAGO,MAAM,yBAAyB;AAAA,EACpC,WAAW,CAAC,EAAE,SAAS,MACrB,SAAS,CAAC,MAAM,UAAU,SAAS,CAAC,MAAM,mBAAmB,SAAS,CAAC,MAAM;AACjF;AAMO,SAAS,oBAAoB,aAA0B,gBAAiC;AAC7F,QAAM,OAAO,YAAY,aAA8B,mBAAmB,cAAc,CAAC;AACzF,SAAO,CAAC,CAAC,SAAS,KAAK,WAAW,CAAC,GAAG,MAAM,CAAC,MAAc,EAAE,QAAQ,WAAW,CAAC;AACnF;AAKO,SAAS,iBACd,aACA,gBACA,WACS;AACT,QAAM,OAAO,YAAY,aAA8B,mBAAmB,cAAc,CAAC;AACzF,UAAQ,MAAM,WAAW,CAAC,GAAG;AAAA,IAAK,CAAC,MACjC,EAAE,QAAQ;AAAA,MACR,CAAC,MACC,EAAE,gBAAgB,cAAc,EAAE,WAAW,iBAAiB,EAAE,WAAW;AAAA,IAC/E;AAAA,EACF;AACF;AAKO,SAAS,sBACd,aACA,gBACA,aACA,SAKM;AACN,QAAM,EAAE,UAAU,iBAAiB,uBAAuB,IAAI;AAE9D,cAAY;AAAA,IACV,mBAAmB,cAAc;AAAA,IACjC,CAAC,YAAyC;AACxC,UAAI,CAAC,SAAS;AACZ,eAAO;AAAA,UACL,qBAAqB;AAAA,UACrB,SAAS;AAAA,YACP;AAAA,cACE,SAAS,CAAC,WAAW;AAAA,cACrB,qBAAqB,YAAY;AAAA,YACnC;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAEA,YAAM,UAAU,C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,aAAO;AAAA,QACL,GAAG;AAAA,QACH,SAAS,QAAQ,QAAQ,IAAI,CAAC,YAAoB;AAAA,UAChD,GAAG;AAAA,UACH,SAAS,OAAO,QAAQ,IAAI,CAAC,QAAiB;AAC5C,gBAAI,IAAI,gBAAgB,WAAW;AACjC,qBAAO,EAAE,GAAG,KAAK,kBAAkB,KAAK;AAAA,YAC1C;AACA,mBAAO;AAAA,UACT,CAAC;AAAA,QACH,EAAE;AAAA,MACJ;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  import { useCallback, useEffect, useMemo, useState } from "react";
2
2
  import { useQueryClient } from "@tanstack/react-query";
3
3
  import { useArbi } from "../useArbi.js";
4
- import { useAgentChats } from "../workforce.js";
4
+ import { useAgentChats, useIsWorkspaceOwner } from "../workforce.js";
5
5
  import { useConversations } from "../hooks.js";
6
6
  import { refreshDocuments, useDocuments } from "../documents/documents-data.js";
7
7
  import { removeConversationFromLists } from "../conversation-list.js";
@@ -111,7 +111,10 @@ function useConversation(options = {}) {
111
111
  updated_at: chat.updated_at,
112
112
  message_count: 1,
113
113
  status: null,
114
- assistant_mode: "always"
114
+ assistant_mode: "always",
115
+ // A chat with one's own agent is one's own and private.
116
+ is_owner: true,
117
+ is_shared: false
115
118
  })) : ordinaryHistory.data ?? [],
116
119
  [agentId, agentHistory.data, ordinaryHistory.data, workspaceId]
117
120
  );
@@ -175,19 +178,21 @@ function useConversation(options = {}) {
175
178
  }).filter((m) => m !== null),
176
179
  [messageHistory, getBranchControlForMessage]
177
180
  );
181
+ const isWorkspaceOwner = useIsWorkspaceOwner();
178
182
  const threads = useMemo(() => {
179
183
  const firstQuestion = messages.find((m) => m.role === "user")?.content ?? "";
180
184
  const localTitle = firstQuestion ? titleFromQuestion(firstQuestion, titleLength) : "";
181
185
  const persisted = [...stored].filter((c) => c.status != null || c.message_count > 0 || c.external_id === conversationId).sort((a, b) => b.updated_at.localeCompare(a.updated_at)).map((c) => ({
182
186
  id: c.external_id,
183
- title: c.title || runTitles[c.external_id] || (c.external_id === conversationId ? localTitle : "")
187
+ title: c.title || runTitles[c.external_id] || (c.external_id === conversationId ? localTitle : ""),
188
+ canDelete: isWorkspaceOwner || c.is_owner !== false && !c.is_shared
184
189
  }));
185
190
  const isListed = persisted.some((t) => t.id === conversationId);
186
191
  return [
187
- ...conversationId === null ? [{ id: NEW, title: localTitle }] : isListed ? [] : [{ id: conversationId, title: localTitle }],
192
+ ...conversationId === null ? [{ id: NEW, title: localTitle, canDelete: true }] : isListed ? [] : [{ id: conversationId, title: localTitle, canDelete: true }],
188
193
  ...persisted
189
194
  ];
190
- }, [stored, conversationId, messages, titleLength, runTitles]);
195
+ }, [stored, conversationId, messages, titleLength, runTitles, isWorkspaceOwner]);
191
196
  const selectedIds = useMemo(
192
197
  () => (agentId ? [] : docs).map((d) => d.external_id).filter((id) => !!id && !deselected.has(id)),
193
198
  [docs, deselected, agentId]
@@ -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 } 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 { getThreadsQueryKey } from './conversation-cache'\nimport {\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\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 }))\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 threads = useMemo(() => {\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 }))\n const isListed = persisted.some((t) => t.id === conversationId)\n return [\n ...(conversationId === null\n ? [{ id: NEW, title: localTitle }]\n : isListed\n ? []\n : [{ id: conversationId, title: localTitle }]),\n ...persisted,\n ]\n }, [stored, conversationId, messages, titleLength, runTitles])\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 queryClient.setQueryData<{ assistant_mode?: string }>(\n getThreadsQueryKey(conversationId),\n (old) => (old ? { ...old, assistant_mode: mode } : old)\n )\n void queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\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
-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/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 { getThreadsQueryKey } from './conversation-cache'\nimport {\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 queryClient.setQueryData<{ assistant_mode?: string }>(\n getThreadsQueryKey(conversationId),\n (old) => (old ? { ...old, assistant_mode: mode } : old)\n )\n void queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\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;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AAA,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;",
6
6
  "names": ["branch"]
7
7
  }
@@ -25,6 +25,7 @@ import {
25
25
  clearLoadingState,
26
26
  flushStreamingTokens,
27
27
  getThreadsQueryKey,
28
+ isConversationEmpty,
28
29
  updateUserMessageStateInCache
29
30
  } from "./conversation-cache.js";
30
31
  import {
@@ -251,6 +252,9 @@ function useConversationActions({
251
252
  // A new chat about a document is bound by its first turn, on the server (every device).
252
253
  ...!convId && threadDocumentId ? { bindDocumentId: threadDocumentId } : {},
253
254
  previousResponseId: parentId,
255
+ // The first turn of an existing conversation with no message yet (a task's thread) runs in
256
+ // it: without its id the server starts a new conversation for the turn.
257
+ ...convId && !parentId && !options?.branch && isConversationEmpty(queryClient, convId) ? { conversationId: convId } : {},
254
258
  agentId: agentExtId,
255
259
  model: resolvedConfigId,
256
260
  mentions: route.mentions,