@arbidocs/react 0.5.172 → 0.5.174
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat/ChatBubble.js +1 -6
- package/dist/chat/ChatBubble.js.map +2 -2
- package/dist/chat/useConversationActions.js +4 -1
- package/dist/chat/useConversationActions.js.map +2 -2
- package/dist/chat/useMessageTimer.js +4 -2
- package/dist/chat/useMessageTimer.js.map +2 -2
- package/dist/{chunk-W4W75MSO.cjs → chunk-UR5F4DNJ.cjs} +43 -45
- package/dist/chunk-UR5F4DNJ.cjs.map +1 -0
- package/dist/directmessages/DmComposer.js +5 -2
- package/dist/directmessages/DmComposer.js.map +2 -2
- package/dist/entities/EntityPill.js +2 -1
- package/dist/entities/EntityPill.js.map +2 -2
- package/dist/entities/UserEntity.js +11 -2
- package/dist/entities/UserEntity.js.map +2 -2
- package/dist/icons/ArbiBotHeadIcon.js +28 -41
- package/dist/icons/ArbiBotHeadIcon.js.map +2 -2
- package/dist/index.cjs +232 -229
- package/dist/index.cjs.map +1 -1
- package/dist/{index.d-BaZUctD1.d.ts → index.d-DIQCjS20.d.ts} +9 -2
- package/dist/index.d.ts +7 -11
- package/dist/ui/index.cjs +156 -152
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +2 -0
- package/dist/ui/index.js.map +2 -2
- package/package.json +3 -3
- package/dist/chunk-W4W75MSO.cjs.map +0 -1
package/dist/chat/ChatBubble.js
CHANGED
|
@@ -22,7 +22,6 @@ const ChatBubble = memo(function ChatBubble2({
|
|
|
22
22
|
id,
|
|
23
23
|
isLastOfRun = true,
|
|
24
24
|
senderName,
|
|
25
|
-
senderBadge,
|
|
26
25
|
avatar,
|
|
27
26
|
classNames,
|
|
28
27
|
renderMessage = (m) => m,
|
|
@@ -60,7 +59,7 @@ const ChatBubble = memo(function ChatBubble2({
|
|
|
60
59
|
"data-testid": testId,
|
|
61
60
|
className: cn(
|
|
62
61
|
"relative flex w-full min-w-0 items-start gap-2",
|
|
63
|
-
floating && "
|
|
62
|
+
floating && "bg-transparent",
|
|
64
63
|
floating && (compact ? "items-center px-3.5 py-2" : "px-4 py-3.5"),
|
|
65
64
|
!floating && (isLastOfRun ? "mb-2" : "mb-0.5")
|
|
66
65
|
),
|
|
@@ -76,10 +75,6 @@ const ChatBubble = memo(function ChatBubble2({
|
|
|
76
75
|
floating ? "min-w-0 flex-1" : cn("px-3.5 py-2 shadow-sm transition-shadow", bubbleRadius, bubbleSurface)
|
|
77
76
|
),
|
|
78
77
|
children: [
|
|
79
|
-
floating && !compact && senderName && /* @__PURE__ */ jsxs("div", { className: "mb-1 flex items-center gap-2 text-[11px] font-medium tracking-[0.01em] text-muted-foreground", children: [
|
|
80
|
-
senderName,
|
|
81
|
-
senderBadge
|
|
82
|
-
] }),
|
|
83
78
|
compact ? /* @__PURE__ */ jsx("div", { className: "truncate text-[13px] leading-5 text-muted-foreground", title: message, children: message }) : (message || !attachments) && /* @__PURE__ */ jsx(
|
|
84
79
|
"div",
|
|
85
80
|
{
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/chat/ChatBubble.tsx"],
|
|
4
|
-
"sourcesContent": ["/**\n * Chat Bubble Component\n * iMessage / WhatsApp-style message bubble with read receipts and\n * consecutive-message grouping.\n *\n * Promoted from the ARBI app. To keep `@arbidocs/react` light (peers react /\n * react-dom only), the two host-owned concerns \u2014 rendering the message body\n * (the app's heavy markdown renderer) and formatting the timestamp \u2014 are\n * injected via the optional `renderMessage` / `formatTimestamp` props. Both\n * default to plain text so the component works standalone; the ARBI app shim\n * wires in `<MarkdownRenderer>` and `formatFriendlyDate` for identical output.\n */\n\nimport { memo, useState, type ReactNode } from 'react'\nimport { Trash2, Check, CheckCheck, Link } from 'lucide-react'\nimport { cn } from '../lib/utils'\n\n/** Animated typing indicator (three bouncing dots) */\nexport const TypingIndicator = memo(function TypingIndicator() {\n return (\n <div className=\"flex w-full justify-start mb-2\" data-testid=\"dm-typing-indicator\">\n <div className=\"bg-card border border-primary rounded-2xl rounded-bl-md px-4 py-2.5\">\n <div className=\"flex gap-1 items-center\">\n <span className=\"w-1.5 h-1.5 rounded-full bg-muted-foreground animate-bounce [animation-delay:0ms]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-muted-foreground animate-bounce [animation-delay:150ms]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-muted-foreground animate-bounce [animation-delay:300ms]\" />\n </div>\n </div>\n </div>\n )\n})\n\nexport interface ChatBubbleProps {\n appearance?: 'standard' | 'floating'\n /** Single-line query preview once its answer has arrived. */\n compact?: boolean\n message: string\n timestamp: string\n isSent: boolean\n deleted?: boolean\n read?: boolean\n onDelete?: () => void\n /**\n * Copy a shareable deep link to this exact message. Optional \u2014 the host\n * builds the URL (it knows the workspace/deployment domain, the light\n * package doesn't), this just renders the affordance and calls back.\n */\n onCopyLink?: () => void\n /** Stable DOM anchor for scroll-to-message (a notification deep link, a\n * \"jump to this message\" action). Typically the message's external id. */\n id?: string\n /** Last bubble in a same-sender run; shows the timestamp and read receipt. */\n isLastOfRun?: boolean\n /**\n * Who sent it. Rendered in the meta row on the last bubble of a run, so a\n * thread that needs attribution (a group, or a rail-less list where the peer\n * isn't in a header) gets it without a row per message.\n */\n senderName?: string\n senderBadge?: ReactNode\n /** Sender identity, shown on the same side for both participants. */\n avatar?: ReactNode\n /** Per-slot brand overrides, so a consumer pins its accent in one place. */\n classNames?: {\n /** The current user's own bubble. */\n ownBubble?: string\n /** The peer's bubble. */\n peerBubble?: string\n }\n /**\n * Render the message body. Injected by the host so the light package doesn't\n * depend on the app's markdown renderer. Defaults to plain text.\n */\n renderMessage?: (message: string) => ReactNode\n /**\n * Format the timestamp shown on the last bubble of a run. Defaults to the\n * raw string.\n */\n formatTimestamp?: (timestamp: string) => string\n /**\n * Rendered inside the bubble under the text \u2014 e.g. a message's attached\n * files. The host owns fetching and decrypting them. A message with\n * attachments and no text shows only these.\n */\n attachments?: ReactNode\n /** Marks the message row, including the deleted tombstone. */\n 'data-testid'?: string\n}\n\nexport const ChatBubble = memo(function ChatBubble({\n appearance = 'standard',\n compact = false,\n message,\n timestamp,\n isSent,\n deleted,\n read,\n onDelete,\n onCopyLink,\n id,\n isLastOfRun = true,\n senderName,\n
|
|
5
|
-
"mappings": "AAsBQ,SACE,KADF;AATR,SAAS,MAAM,gBAAgC;AAC/C,SAAS,QAAQ,OAAO,YAAY,YAAY;AAChD,SAAS,UAAU;AAGZ,MAAM,kBAAkB,KAAK,SAASA,mBAAkB;AAC7D,SACE,oBAAC,SAAI,WAAU,kCAAiC,eAAY,uBAC1D,8BAAC,SAAI,WAAU,uEACb,+BAAC,SAAI,WAAU,2BACb;AAAA,wBAAC,UAAK,WAAU,qFAAoF;AAAA,IACpG,oBAAC,UAAK,WAAU,uFAAsF;AAAA,IACtG,oBAAC,UAAK,WAAU,uFAAsF;AAAA,KACxG,GACF,GACF;AAEJ,CAAC;AA2DM,MAAM,aAAa,KAAK,SAASC,YAAW;AAAA,EACjD,aAAa;AAAA,EACb,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA
|
|
4
|
+
"sourcesContent": ["/**\n * Chat Bubble Component\n * iMessage / WhatsApp-style message bubble with read receipts and\n * consecutive-message grouping.\n *\n * Promoted from the ARBI app. To keep `@arbidocs/react` light (peers react /\n * react-dom only), the two host-owned concerns \u2014 rendering the message body\n * (the app's heavy markdown renderer) and formatting the timestamp \u2014 are\n * injected via the optional `renderMessage` / `formatTimestamp` props. Both\n * default to plain text so the component works standalone; the ARBI app shim\n * wires in `<MarkdownRenderer>` and `formatFriendlyDate` for identical output.\n */\n\nimport { memo, useState, type ReactNode } from 'react'\nimport { Trash2, Check, CheckCheck, Link } from 'lucide-react'\nimport { cn } from '../lib/utils'\n\n/** Animated typing indicator (three bouncing dots) */\nexport const TypingIndicator = memo(function TypingIndicator() {\n return (\n <div className=\"flex w-full justify-start mb-2\" data-testid=\"dm-typing-indicator\">\n <div className=\"bg-card border border-primary rounded-2xl rounded-bl-md px-4 py-2.5\">\n <div className=\"flex gap-1 items-center\">\n <span className=\"w-1.5 h-1.5 rounded-full bg-muted-foreground animate-bounce [animation-delay:0ms]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-muted-foreground animate-bounce [animation-delay:150ms]\" />\n <span className=\"w-1.5 h-1.5 rounded-full bg-muted-foreground animate-bounce [animation-delay:300ms]\" />\n </div>\n </div>\n </div>\n )\n})\n\nexport interface ChatBubbleProps {\n appearance?: 'standard' | 'floating'\n /** Single-line query preview once its answer has arrived. */\n compact?: boolean\n message: string\n timestamp: string\n isSent: boolean\n deleted?: boolean\n read?: boolean\n onDelete?: () => void\n /**\n * Copy a shareable deep link to this exact message. Optional \u2014 the host\n * builds the URL (it knows the workspace/deployment domain, the light\n * package doesn't), this just renders the affordance and calls back.\n */\n onCopyLink?: () => void\n /** Stable DOM anchor for scroll-to-message (a notification deep link, a\n * \"jump to this message\" action). Typically the message's external id. */\n id?: string\n /** Last bubble in a same-sender run; shows the timestamp and read receipt. */\n isLastOfRun?: boolean\n /**\n * Who sent it. Rendered in the meta row on the last bubble of a run, so a\n * thread that needs attribution (a group, or a rail-less list where the peer\n * isn't in a header) gets it without a row per message.\n */\n senderName?: string\n senderBadge?: ReactNode\n /** Sender identity, shown on the same side for both participants. */\n avatar?: ReactNode\n /** Per-slot brand overrides, so a consumer pins its accent in one place. */\n classNames?: {\n /** The current user's own bubble. */\n ownBubble?: string\n /** The peer's bubble. */\n peerBubble?: string\n }\n /**\n * Render the message body. Injected by the host so the light package doesn't\n * depend on the app's markdown renderer. Defaults to plain text.\n */\n renderMessage?: (message: string) => ReactNode\n /**\n * Format the timestamp shown on the last bubble of a run. Defaults to the\n * raw string.\n */\n formatTimestamp?: (timestamp: string) => string\n /**\n * Rendered inside the bubble under the text \u2014 e.g. a message's attached\n * files. The host owns fetching and decrypting them. A message with\n * attachments and no text shows only these.\n */\n attachments?: ReactNode\n /** Marks the message row, including the deleted tombstone. */\n 'data-testid'?: string\n}\n\nexport const ChatBubble = memo(function ChatBubble({\n appearance = 'standard',\n compact = false,\n message,\n timestamp,\n isSent,\n deleted,\n read,\n onDelete,\n onCopyLink,\n id,\n isLastOfRun = true,\n senderName,\n avatar,\n classNames,\n renderMessage = (m) => m,\n formatTimestamp = (t) => t,\n attachments,\n 'data-testid': testId,\n}: ChatBubbleProps) {\n const [isHovered, setIsHovered] = useState(false)\n const [isFocused, setIsFocused] = useState(false)\n const showActions = isHovered || isFocused\n\n // No \"edited\" indicator: `updated_at` is also bumped by read-state\n // patches, so we can't tell a real content edit from a recipient\n // marking the message as read. The created_at timestamp is the only\n // honest signal we can show here.\n\n if (deleted) {\n return (\n <div id={id} data-testid={testId} className=\"flex w-full justify-start mb-2\">\n <div className=\"text-sm text-muted-foreground italic px-3 py-1\">Message deleted</div>\n </div>\n )\n }\n\n const floating = appearance === 'floating'\n const bubbleRadius = 'rounded-lg'\n\n // Own messages sit on a soft brand tint rather than full `primary`: a\n // saturated block per message shouts on a long thread, and a light surface\n // means markdown needs no colour inversion.\n //\n // The tint is `ai-accent-soft`, NOT `accent`. Plenty of themes set `accent`\n // equal to `muted` and a hair off `background` \u2014 ARBI's differ by 3% \u2014 so an\n // accent bubble there is invisible against the thread. `ai-accent-soft` is\n // part of the AI-accent contract every consuming app defines explicitly, so\n // it is a tint by construction.\n const bubbleSurface = isSent\n ? cn('bg-ai-accent-soft text-foreground chat-bubble-sent', classNames?.ownBubble)\n : cn('border border-border bg-card text-card-foreground', classNames?.peerBubble)\n\n const copyLinkButton = onCopyLink && (\n <button\n onClick={onCopyLink}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n className={cn(\n 'self-end p-1 transition-opacity focus:outline-none focus-visible:ring-1 focus-visible:ring-ring rounded',\n showActions ? 'opacity-100 text-foreground' : 'opacity-0 text-muted-foreground'\n )}\n aria-label=\"Copy link to this message\"\n >\n <Link className=\"w-3.5 h-3.5\" />\n </button>\n )\n\n return (\n <div\n id={id}\n data-testid={testId}\n className={cn(\n 'relative flex w-full min-w-0 items-start gap-2',\n floating && 'bg-transparent',\n floating && (compact ? 'items-center px-3.5 py-2' : 'px-4 py-3.5'),\n !floating && (isLastOfRun ? 'mb-2' : 'mb-0.5')\n )}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n >\n {avatar && <div className={cn('shrink-0', !compact && 'pt-1')}>{avatar}</div>}\n\n <div className=\"flex min-w-0 flex-1 flex-col\">\n <div\n className={cn(\n 'break-words',\n floating\n ? 'min-w-0 flex-1'\n : cn('px-3.5 py-2 shadow-sm transition-shadow', bubbleRadius, bubbleSurface)\n )}\n >\n {compact ? (\n <div className=\"truncate text-[13px] leading-5 text-muted-foreground\" title={message}>\n {message}\n </div>\n ) : (\n (message || !attachments) && (\n <div\n className={cn(\n 'text-sm [&_.markdown-content]:space-y-1.5 [&_pre]:max-w-full [&_pre]:overflow-x-auto',\n floating && 'leading-[1.65] [&_.markdown-content]:leading-[1.65]',\n floating && isSent && 'text-[13px] text-muted-foreground'\n )}\n >\n {renderMessage(message)}\n </div>\n )\n )}\n {attachments && <div className={cn(message && 'mt-1.5')}>{attachments}</div>}\n\n {/* Sender + timestamp + read receipt, only on the last bubble of the\n run \u2014 a meta row per message is noise in a 1:1 thread. */}\n {!floating && isLastOfRun && (\n <div className={cn('flex items-center gap-1.5 mt-0.5', 'justify-start')}>\n {senderName && (\n <span className=\"text-xs font-medium leading-none opacity-90\">{senderName}</span>\n )}\n <span className=\"text-xs leading-none opacity-70\">{formatTimestamp(timestamp)}</span>\n {isSent &&\n (read ? (\n <CheckCheck className=\"w-3.5 h-3.5 flex-shrink-0 opacity-80\" />\n ) : (\n <Check className=\"w-3.5 h-3.5 flex-shrink-0 opacity-60\" />\n ))}\n </div>\n )}\n </div>\n </div>\n\n {/* Message actions share the same position in either direction. */}\n {(onDelete || copyLinkButton) && (\n <div\n className={cn(\n 'absolute right-1 top-1 flex items-center gap-0.5 rounded',\n showActions && 'bg-background/90'\n )}\n >\n {onDelete && (\n <button\n onClick={onDelete}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n className={cn(\n 'self-end p-1 transition-opacity focus:outline-none focus-visible:ring-1 focus-visible:ring-ring rounded',\n showActions ? 'opacity-100 text-destructive' : 'opacity-0 text-muted-foreground'\n )}\n aria-label=\"Delete message\"\n >\n <Trash2 className=\"w-3.5 h-3.5\" />\n </button>\n )}\n {copyLinkButton}\n </div>\n )}\n </div>\n )\n})\n"],
|
|
5
|
+
"mappings": "AAsBQ,SACE,KADF;AATR,SAAS,MAAM,gBAAgC;AAC/C,SAAS,QAAQ,OAAO,YAAY,YAAY;AAChD,SAAS,UAAU;AAGZ,MAAM,kBAAkB,KAAK,SAASA,mBAAkB;AAC7D,SACE,oBAAC,SAAI,WAAU,kCAAiC,eAAY,uBAC1D,8BAAC,SAAI,WAAU,uEACb,+BAAC,SAAI,WAAU,2BACb;AAAA,wBAAC,UAAK,WAAU,qFAAoF;AAAA,IACpG,oBAAC,UAAK,WAAU,uFAAsF;AAAA,IACtG,oBAAC,UAAK,WAAU,uFAAsF;AAAA,KACxG,GACF,GACF;AAEJ,CAAC;AA2DM,MAAM,aAAa,KAAK,SAASC,YAAW;AAAA,EACjD,aAAa;AAAA,EACb,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA,gBAAgB,CAAC,MAAM;AAAA,EACvB,kBAAkB,CAAC,MAAM;AAAA,EACzB;AAAA,EACA,eAAe;AACjB,GAAoB;AAClB,QAAM,CAAC,WAAW,YAAY,I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C,WAAW;AAAA,oBACT;AAAA,oBACA,YAAY;AAAA,oBACZ,YAAY,UAAU;AAAA,kBACxB;AAAA,kBAEC,wBAAc,OAAO;AAAA;AAAA,cACxB;AAAA,cAGH,eAAe,oBAAC,SAAI,WAAW,GAAG,WAAW,QAAQ,GAAI,uBAAY;AAAA,cAIrE,CAAC,YAAY,eACZ,qBAAC,SAAI,WAAW,GAAG,oCAAoC,eAAe,GACnE;AAAA,8BACC,oBAAC,UAAK,WAAU,+CAA+C,sBAAW;AAAA,gBAE5E,oBAAC,UAAK,WAAU,mCAAmC,0BAAgB,SAAS,GAAE;AAAA,gBAC7E,WACE,OACC,oBAAC,cAAW,WAAU,wCAAuC,IAE7D,oBAAC,SAAM,WAAU,wCAAuC;AAAA,iBAE9D;AAAA;AAAA;AAAA,QAEJ,GACF;AAAA,SAGE,YAAY,mBACZ;AAAA,UAAC;AAAA;AAAA,YACC,WAAW;AAAA,cACT;AAAA,cACA,eAAe;AAAA,YACjB;AAAA,YAEC;AAAA,0BACC;AAAA,gBAAC;AAAA;AAAA,kBACC,SAAS;AAAA,kBACT,SAAS,MAAM,aAAa,IAAI;AAAA,kBAChC,QAAQ,MAAM,aAAa,KAAK;AAAA,kBAChC,WAAW;AAAA,oBACT;AAAA,oBACA,cAAc,iCAAiC;AAAA,kBACjD;AAAA,kBACA,cAAW;AAAA,kBAEX,8BAAC,UAAO,WAAU,eAAc;AAAA;AAAA,cAClC;AAAA,cAED;AAAA;AAAA;AAAA,QACH;AAAA;AAAA;AAAA,EAEJ;AAEJ,CAAC;",
|
|
6
6
|
"names": ["TypingIndicator", "ChatBubble"]
|
|
7
7
|
}
|
|
@@ -368,13 +368,16 @@ function useConversationActions({
|
|
|
368
368
|
if (streamState.queuedFailed) failQueuedContinuation(queryClient, session, streamState);
|
|
369
369
|
return;
|
|
370
370
|
}
|
|
371
|
-
if (streamState.serverError && !streamState.userMessageId && !streamState.
|
|
371
|
+
if (streamState.serverError && !streamState.userMessageId && !streamState.hasStreamStarted && !queuedContinuation) {
|
|
372
372
|
if (ownsActiveGeneration()) {
|
|
373
373
|
session.setConversationError(
|
|
374
374
|
streamState.conversationId,
|
|
375
375
|
streamState.serverError,
|
|
376
376
|
content
|
|
377
377
|
);
|
|
378
|
+
const chat = session.getState();
|
|
379
|
+
const open = chat.conversationId ?? "new";
|
|
380
|
+
if (open === streamState.conversationId && !chat.drafts[open]) session.setDraft(content);
|
|
378
381
|
void queryClient.invalidateQueries({
|
|
379
382
|
queryKey: getThreadsQueryKey(streamState.conversationId)
|
|
380
383
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/chat/useConversationActions.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The chat engine's actions on a conversation: send (a turn, or a comment to the people in a\n * thread), branch, retry, stop, and the run-control commands typed while a turn runs. A turn goes\n * through `arbi.assistant.ask`, its frames through the stream handlers, and its state lives in the\n * session (`ArbiSessionState`) and the conversation cache.\n */\n\nimport { flushDocumentForTurn } from './turn-flush'\nimport { pendingChatModelSave } from '../config/config-hooks'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { useQueryClient, type QueryClient } from '@tanstack/react-query'\nimport {\n ArbiApiError,\n STOP_REPEAT_WINDOW_MS,\n getRunToCancel,\n quotaFromStreamError,\n type ConversationResponse as Conversation,\n type ThreadsResponse,\n} from '@arbidocs/sdk/browser'\nimport type { components } from '@arbidocs/client'\nimport { notify } from '../shell'\nimport { arbiQueryKeys } from '../hooks'\nimport { useArbi } from '../useArbi'\nimport { requestAgentStatus } from './request-agent-status'\nimport { useArbiHost } from '../host/config'\nimport { selectDraft, useArbiSessionStore } from '../session'\nimport type { ArbiSessionStore } from '../session/store'\nimport {\n invalidateConversationLists,\n isConversationShared,\n patchConversation,\n patchConversationList,\n removeConversationFromLists,\n} from '../conversation-list'\nimport {\n allConversationThreads,\n clearLoadingState,\n flushStreamingTokens,\n getThreadsQueryKey,\n isConversationEmpty,\n updateUserMessageStateInCache,\n} from './conversation-cache'\nimport {\n assistantLabels,\n cachedAssistantMode,\n cachedMentionCandidates,\n isCommentToPeople,\n} from './conversation-mentions'\nimport { useAssistantName } from '../host/assistant-copy'\nimport { hasMessageBody, toMessageMentions, extractMentions } from './mentions'\nimport { takeDocumentForTurn } from './open-document'\nimport { agentChatOwnerOf, creatorOf } from './agent-chat-owner'\nimport { bindThreadDocument, boundDocumentOf } from './thread-binding'\nimport { resolveReplyTarget } from './reply-target'\nimport {\n confirmConversationWorkspace,\n conversationWorkspaceOf,\n watchConversationWorkspaces,\n} from './conversation-workspace'\nimport { useStreamHandlers, type StreamState } from './stream-handlers'\nimport {\n AGENT_CONTROL_COMMANDS,\n cachedQuotaUsedUp,\n disconnectAttachedRun,\n refuseChatWhenOffline,\n waitForResponseId,\n} from './turn-control'\n\ntype MessageInput = components['schemas']['MessageInput']\ntype MessageMention = components['schemas']['MessageMention']\n\n/** How long a dropped turn holds its generating state while the thread is re-read. */\nconst RECONCILE_TIMEOUT_MS = 5000\n\nexport interface SendMessageOptions {\n /** An explicit edit/fork, rather than appending a human message to the shared thread. */\n branch?: boolean\n queuedContinuation?: boolean\n queueOwnerAssistantId?: string\n queuedClientId?: string\n /**\n * Bypasses the normal single-pinned-document tools computation (the chat's documents and its\n * pin, see `buildTurnRequest`) for this one send.\n * The app's general \"pin a document\" feature is deliberately one-at-a-time\n * (`selectFullContextDocument`) \u2014 a pinned TEXT doc's full content goes\n * straight into the AGENT's chat prompt, so more than one at a time risks\n * blowing that context window. Generate image is a different resource\n * entirely: reference images never touch the agent's chat context \u2014 they go\n * to the separate ImageGen model in its own request \u2014 so multiple\n * references (e.g. \"combine these two logos\") don't compound against that\n * budget, even though they still cost real tokens against ImageGen's own\n * call. This lets that caller build its own tools object with every\n * selected reference doc instead of touching the single global pin.\n */\n toolsOverride?: MessageInput['tools']\n /**\n * Send in this conversation and workspace rather than the open ones: a follow-up captured when\n * its turn started (a deferred interjection), sent after the view may have moved on.\n */\n target?: TurnTarget\n}\n\n/** The conversation and workspace a turn belongs to, captured when it starts. */\nexport interface TurnTarget {\n workspaceId: string\n conversationId: string\n}\n\n/**\n * The draft a send leaves behind. A shared chat addresses ARBI again, except after a comment to\n * people: then the box is left empty, which a shared chat reads as a comment to the thread.\n */\nfunction draftAfterSend(\n queryClient: QueryClient,\n session: ArbiSessionStore,\n wasComment: boolean,\n assistantName: string\n): string {\n const shared = isConversationShared(queryClient, session.getState().conversationId)\n return shared && !wasComment ? `@${assistantName} ` : ''\n}\n\n/**\n * A queued follow-up the backend refused before its turn started: mark its bubble failed and\n * take it out of the queue, so it does not sit there as if it were still waiting.\n */\nfunction failQueuedContinuation(\n queryClient: QueryClient,\n session: ArbiSessionStore,\n streamState: {\n conversationId: string\n queuedUserMessageId: string | null\n queueOwnerAssistantId: string | null\n queuedClientId: string | null\n }\n): void {\n if (streamState.queuedUserMessageId) {\n updateUserMessageStateInCache(\n queryClient,\n streamState.conversationId,\n streamState.queuedUserMessageId,\n 'failed',\n false\n )\n }\n if (streamState.queuedClientId) {\n session.removeQueuedMessage(streamState.queuedClientId)\n }\n notify.error('Queued message failed to send')\n}\n\n/** The signed-in user's id, or null before the session is known. */\nfunction signedInUserId(arbi: { user: { identity: () => { externalId: string } | null } }) {\n try {\n return arbi.user.identity()?.externalId ?? null\n } catch {\n return null\n }\n}\n\n/** What the actions act on: the open workspace and conversation, as the session holds them. */\nexport interface ConversationActionsInput {\n selectedWorkspaceId: string | null\n /** The cursor when the view rendered (the stream handlers place a branch against it). */\n parentMessageId: string | null\n /** The open conversation's key (`new` for a new chat). */\n conversationKey: string\n isGenerating: boolean\n lastFailedMessage: string | null\n}\n\n/** The actions on the open conversation. */\nexport function useConversationActions({\n selectedWorkspaceId,\n parentMessageId,\n conversationKey,\n isGenerating,\n lastFailedMessage,\n}: ConversationActionsInput) {\n const queryClient = useQueryClient()\n const session = useArbiSessionStore()\n const currentConversationId = conversationKey === 'new' ? null : conversationKey\n const invalidateUserWorkspaces = useCallback(\n () => void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() }),\n [queryClient]\n )\n\n const arbi = useArbi()\n // Each conversation stays in the workspace it was opened in, though the surface switches.\n useState(() => watchConversationWorkspaces(queryClient, session))\n const createHandlers = useStreamHandlers()\n const chatHost = useArbiHost().chat\n const assistantName = useAssistantName()\n const mentionCandidates = useCallback(\n () =>\n cachedMentionCandidates(\n queryClient,\n session.getState().workspaceId,\n signedInUserId(arbi),\n assistantName\n ),\n [queryClient, session, arbi, assistantName]\n )\n // The local stream a Stop is closing. Stop cancels the run on the server before it aborts the\n // stream, so the connection can drop first with a network error that is not an abort.\n const stoppedStreamRef = useRef<AbortController | null>(null)\n // True while a Stop's server cancel is in flight, so a second press does not cancel again.\n const stopInFlightRef = useRef(false)\n // When the last Stop was pressed. A press within STOP_REPEAT_WINDOW_MS of it is a double tap.\n const lastStopAtRef = useRef(0)\n // True while a Retry deletes and resends, so a second press does not do it again.\n const retryInFlightRef = useRef(false)\n // Lets sendMessage resubmit a deferred interjection as a new turn without a\n // self-reference (it is a useCallback that would otherwise close over a stale\n // or not-yet-defined copy of itself). Kept current just below its definition.\n const sendMessageRef = useRef<\n | ((content: string, parentId?: string | null, options?: SendMessageOptions) => Promise<void>)\n | null\n >(null)\n\n /**\n * Shared posts, and posts in a `mentioned` thread, run ARBI only when addressed; posts in an\n * ordinary solo chat address it implicitly.\n */\n const routeMessage = useCallback(\n (content: string, conversationId?: string | null) => {\n const state = session.getState()\n const convId = conversationId === undefined ? state.conversationId : conversationId\n const { newConversationAssistantMode } = state\n const candidates = mentionCandidates()\n const mentioned = extractMentions(content, candidates)\n const assistantMode = cachedAssistantMode(queryClient, convId, newConversationAssistantMode)\n const isComment = isCommentToPeople(queryClient, convId, content, candidates)\n const mentions = toMessageMentions(mentioned) as MessageMention[]\n // A message not taken as a comment addresses ARBI. In an existing `mentioned` thread that is\n // only one that @mentions it; what is left is the first message of a thread not created\n // yet, whose turn creates it in `mentioned` mode.\n if (\n !isComment &&\n assistantMode === 'mentioned' &&\n !mentions.some((m) => m.type === 'assistant')\n ) {\n mentions.push({ type: 'assistant' })\n }\n return {\n mentions,\n assistantMode,\n isComment,\n }\n },\n [queryClient, session, mentionCandidates]\n )\n\n /** Post a comment (no assistant run) and land the thread on it. */\n const postComment = useCallback(\n async (\n content: string,\n parentId: string | null,\n mentions: MessageMention[],\n branch = false\n ) => {\n const convId = session.getState().conversationId\n try {\n const saved = await arbi.conversations.postMessage({\n content,\n mentions,\n // Only an explicit edit creates a branch. Ordinary comments append to the\n // server's latest message, so simultaneous sends stay visible together. Else\n // (nothing yet) start a thread. The mode only applies to a conversation it creates.\n ...(branch && parentId\n ? { previous_message_ext_id: parentId }\n : convId\n ? { conversation_ext_id: convId }\n : {}),\n assistant_mode: 'mentioned',\n })\n const conversationId = saved.conversation_ext_id\n const nowIso = new Date().toISOString()\n if (!convId) {\n // A comment starts the thread without a turn to carry its binding: bind it right after.\n const bindTo = session.getState().newChatDocumentId\n session.moveConversation('new', conversationId)\n if (bindTo) session.setNewChatDocumentId(null)\n patchConversationList(queryClient, session.getState().workspaceId, (old) => [\n {\n external_id: conversationId,\n title: content.slice(0, 40),\n created_by_ext_id: saved.created_by_ext_id,\n updated_by_ext_id: null,\n created_at: nowIso,\n updated_at: nowIso,\n // A mention of someone who cannot see it yet shares it server-side: refetched below.\n is_shared: false,\n message_count: 1,\n last_message_status: 'completed',\n assistant_mode: 'mentioned',\n } as Conversation,\n ...old,\n ])\n if (bindTo)\n bindThreadDocument(arbi, queryClient, conversationId, bindTo).catch(() =>\n notify.error('Could not attach the document to this thread')\n )\n invalidateUserWorkspaces()\n } else {\n patchConversation(queryClient, conversationId, (c) => ({\n ...c,\n message_count: c.message_count + 1,\n updated_at: nowIso,\n }))\n }\n // Mentioning someone shares the conversation on the server, which this cache cannot know.\n if (mentions.some((m) => m.type === 'user')) {\n await invalidateConversationLists(queryClient)\n }\n await queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n session.setCursor(saved.external_id)\n } catch (error) {\n notify.error(\n (error instanceof ArbiApiError && error.detail) || 'Failed to post the message'\n )\n // Give the text back rather than lose it.\n if (!selectDraft(session.getState())) session.setDraft(content)\n }\n },\n [arbi, session, queryClient, invalidateUserWorkspaces]\n )\n\n const sendMessage = useCallback(\n async (content: string, requestedParentId?: string | null, options?: SendMessageOptions) => {\n // Never reply to a failed or deleted message: the server refuses it, so every Retry and every\n // new message would fail again. A queued follow-up names the running turn on purpose. With\n // nothing above to reply to, the parent stays: only a fresh conversation could take it.\n const target = options?.target\n const parentId =\n options?.queuedContinuation || !requestedParentId\n ? requestedParentId\n : (resolveReplyTarget(\n queryClient,\n (target ? target.conversationId : session.getState().conversationId) || 'new',\n requestedParentId\n ) ?? requestedParentId)\n const route = routeMessage(content, target?.conversationId)\n if (route.isComment && !options?.queuedContinuation && !target) {\n await postComment(content, parentId ?? null, route.mentions, options?.branch)\n return\n }\n // A model picked just now is still being saved: the turn runs on it, not on the config before.\n const modelSave = pendingChatModelSave(session)\n if (modelSave) await modelSave.catch(() => undefined)\n const state = session.getState()\n const convId = target ? target.conversationId : state.conversationId\n const convKey = convId || 'new'\n // The turn's workspace, captured now: the conversation's own (a docked or scoped chat keeps\n // its conversation across a switch), else the surface's for a new conversation. Named on the\n // request, so neither a switch nor the session's open workspace can move it.\n const turnWorkspaceId =\n target?.workspaceId ?? conversationWorkspaceOf(queryClient, convId) ?? selectedWorkspaceId\n const agentChat = state.newAgentChat\n // An existing conversation's agent: as recorded, else its creator when that is one of the\n // person's own agents (an agent chat runs under the agent's session; the record does not\n // survive a sign-out, or another device).\n let agentExtId = convId\n ? state.agentChatOwners[convId]\n : agentChat?.workspaceId === turnWorkspaceId\n ? agentChat.agentId\n : undefined\n // Only a conversation an agent created is looked up (an ordinary send never waits on it).\n if (convId && !agentExtId && creatorOf(queryClient, convId)?.startsWith('agt-')) {\n agentExtId = await agentChatOwnerOf(queryClient, () => arbi.agents.list(), convId)\n if (agentExtId) session.setAgentChatOwner(convId, agentExtId)\n }\n const queuedContinuation = options?.queuedContinuation === true\n // First message of a brand-new conversation bumps the workspace's\n // conversation_count \u2014 used to tick the \"Ask ARBI\" onboarding step.\n const isNewConversation = !convId\n\n const documentIds = (state.conversationDocuments[convKey] || []).map((doc) => doc.docId)\n // The chat's facts ride every message of it (snapshot semantics, like its documents).\n const factIds = [...(state.conversationFacts[convKey] || [])]\n\n const newConfigId = state.chatModel\n\n // Frontend is the single source of truth for which config a request\n // uses (Option B): send the same config the model selector resolves &\n // displays (see useConversationSettings) \u2014 explicit per-conversation\n // choice (`newConfigId`) wins, otherwise the user's persisted\n // `last_config`, so a selected config (e.g. one with ARTIFACTS_ENABLED)\n // actually drives the chat instead of being silently dropped to an\n // empty config. `newConfigId` alone is insufficient \u2014 it is transient\n // and cleared on every new conversation. Read `last_config` from the\n // shared settings cache by partial key match: openapi-react-query\n // suffixes the query key with request options and the settings hook is\n // token-gated, so the hook value can momentarily be undefined here even\n // though the data is cached app-wide.\n const cachedSettings = queryClient\n .getQueriesData<{ last_config?: string }>({ queryKey: arbiQueryKeys.userSettings() })\n .map(([, data]) => data)\n .find((data) => data?.last_config)\n const lastConfigId = cachedSettings?.last_config\n const resolvedConfigId = newConfigId || (agentExtId ? undefined : lastConfigId)\n\n // PA mode delegates the turn to the personal agent (`buildTurnRequest` prefixes `/pa ` so\n // the backend routes it straight to the delegation stream).\n const isPaMode = !agentExtId && state.paMode\n\n // Drafting mode: the thread's own document is named (a reference, never its content): the one\n // the thread is bound to (started from it, or attached in it), else one made in this thread\n // and open. A document merely open beside a chat is not: a new chat starts unbound. While an\n // earlier version of it is on screen the viewer returns to the live document. For a Word\n // document the server binds the live document: the assistant reads what it needs on demand\n // and edits it as tracked changes. For an html/react artifact it gets the source and a\n // targeted edit tool. PA-mode turns are delegated to a separate agent and never touch\n // artifacts.\n const threadDocumentId = boundDocumentOf(queryClient, { ...state, conversationId: convId })\n const activeArtifactExtId = isPaMode\n ? null\n : takeDocumentForTurn({\n boundDocumentId: threadDocumentId,\n conversationId: convId,\n workspaceId: turnWorkspaceId,\n })\n\n // An editor holding unsaved changes to that document saves them first: ARBI works on what\n // the person sees.\n const flushing = flushDocumentForTurn(activeArtifactExtId)\n if (flushing) await flushing\n\n // A workflow launch can leave structured tools for its one send; consume them here.\n const pendingTools = state.pendingTools\n if (pendingTools) session.setPendingTools(null)\n const toolsOverride = options?.toolsOverride ?? pendingTools ?? undefined\n\n const request = {\n question: content,\n workspaceId: turnWorkspaceId!,\n docIds: documentIds,\n pinnedDocumentId: state.pinnedDocumentId,\n factIds,\n tools: toolsOverride,\n personalAgent: isPaMode,\n activeArtifactExtId,\n // A new chat about a document is bound by its first turn, on the server (every device).\n ...(!convId && threadDocumentId ? { bindDocumentId: threadDocumentId } : {}),\n previousResponseId: parentId,\n // The first turn of an existing conversation with no message yet (a task's thread) runs in\n // it: without its id the server starts a new conversation for the turn.\n ...(convId && !parentId && !options?.branch && isConversationEmpty(queryClient, convId)\n ? { conversationId: convId }\n : {}),\n agentId: agentExtId,\n model: resolvedConfigId,\n mentions: route.mentions,\n // A brand-new conversation starts in the mode picked in the composer.\n ...(!convId && route.assistantMode === 'mentioned'\n ? { assistantMode: 'mentioned' as const }\n : {}),\n }\n\n const abortController = new AbortController()\n if (!queuedContinuation) {\n session.setConversationGenerating(convKey, true, abortController)\n }\n\n // Optimistically mark this conversation in-progress the instant we start a\n // turn. Without this, Conversation's \"reconcile stale isGenerating\" effect\n // runs on the setConversationGenerating(true) above, sees the conversation\n // list's last_message_status still 'completed' from the PREVIOUS turn (the\n // stream_start patch below only lands ~50ms later), and immediately clears\n // isGenerating \u2014 which race-hid the live status bar on every follow-up\n // turn (first turns were exempt: the new conversation isn't in the list\n // yet). Patching here closes that window. No-op for a brand-new\n // conversation (convKey === 'new' isn't in the list).\n if (!queuedContinuation) {\n patchConversation(queryClient, convKey, { last_message_status: 'in_progress' })\n }\n\n // Mutable stream state \u2014 shared by all SSE handlers via closure\n const streamState: StreamState = {\n conversationId: convKey,\n workspaceId: turnWorkspaceId,\n assistantId: null,\n // 0 = nothing narrated yet, so nothing is owed a reading window.\n lastNarrationSettledAt: 0,\n // True once the model has pivoted to a tool call and not yet resumed\n // prose. Prose arriving while this is set opens a NEW narration, so the\n // one before it closes: paragraph break, and everything above becomes\n // superseded. Item boundaries alone cannot say this \u2014 the backend splits\n // a single sentence across several items.\n pivotedSinceProse: false,\n // Steering that landed too late to steer this turn; resubmitted as a new\n // turn once this one completes (see after the ask below).\n deferredInterjections: [],\n queuedContinuation,\n queuedUserMessageId: null,\n hasStreamStarted: false,\n queuedFailed: false,\n abortController,\n isStopped: () => stoppedStreamRef.current === abortController,\n queueOwnerAssistantId: options?.queueOwnerAssistantId ?? null,\n queuedClientId: options?.queuedClientId ?? null,\n // Set when a create_fact / label_facts tool runs this turn, so the Facts\n // table + label vocabulary refresh on completion (see handleComplete).\n factsTouched: false,\n threadDocumentId,\n // Set by the handlers: the server stored the question / reported its own failure.\n userMessageId: null,\n serverError: null,\n }\n\n // A follow-up sent for another conversation than the one on screen places itself under its own\n // parent, not under the screen's cursor.\n const handlers = createHandlers({\n streamState,\n parentMessageId: target ? (parentId ?? null) : parentMessageId,\n parentId,\n })\n // The server's word on the turn's workspace binds the conversation to it.\n const confirmTurnWorkspace = () => {\n if (streamState.workspaceId)\n confirmConversationWorkspace(\n queryClient,\n streamState.conversationId,\n streamState.workspaceId\n )\n }\n const onUserMessageInWorkspace = handlers.onUserMessage\n handlers.onUserMessage = (message) => {\n onUserMessageInWorkspace(message)\n confirmTurnWorkspace()\n }\n if (agentExtId) {\n const onUserMessage = handlers.onUserMessage\n handlers.onUserMessage = (message) => {\n if (message.conversation_ext_id) {\n session.setAgentChatOwner(message.conversation_ext_id, agentExtId)\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.agentChats(agentExtId) })\n }\n onUserMessage(message)\n }\n }\n\n const ownsActiveGeneration = () => {\n const activeGeneration = session.getState().generating[streamState.conversationId]\n return (\n activeGeneration?.abortController === abortController ||\n (!!streamState.assistantId &&\n activeGeneration?.streamingAssistantId === streamState.assistantId)\n )\n }\n\n try {\n performance.mark('arbi:send-message:start')\n await arbi.assistant.ask(request, {\n signal: abortController.signal,\n onMessageQueued: handlers.onMessageQueued,\n onUserMessage: handlers.onUserMessage,\n onStreamStart: handlers.onStreamStart,\n onToken: handlers.onToken,\n onMetadata: handlers.onMetadata,\n onError: handlers.onError,\n onComplete: handlers.onComplete,\n // `response.output_item.added` is deliberately NOT consumed: an item\n // opening told us only that SOME block had started, which is exactly the\n // guess this design gave up. Text arrives via onOutputTextDelta and\n // settles via onOutputItemDone.\n onOutputItemDone: handlers.onOutputItemDone,\n onOutputTextDelta: handlers.onOutputTextDelta,\n onUserInputRequest: handlers.onUserInputRequest,\n onProbeAnswer: handlers.onProbeAnswer,\n onDeferredInterjection: handlers.onDeferredInterjection,\n onAgentControlState: handlers.onAgentControlState,\n onArtifact: handlers.onArtifact,\n onMailDraft: handlers.onMailDraft,\n onElapsedTime: handlers.onElapsedTime,\n onContextUpdate: handlers.onContextUpdate,\n onQuotaExceeded: (quota) => chatHost?.onQuotaExceeded?.(quota),\n onWorkspace: (workspaceId) => {\n streamState.workspaceId = workspaceId\n confirmTurnWorkspace()\n },\n })\n // The stream is over: commit the text still waiting for a frame now, while the message is\n // the streamed one. Left buffered, it lands after the thread is re-read and is appended\n // to the answer the server stored.\n flushStreamingTokens(queryClient)\n\n // A steering response has no assistant stream of its own. The backend\n // accepted the queued user message into the active tool loop. Keep it\n // visibly queued until the parent stream emits its interjection step at\n // the actual tool boundary; that event settles the cache entry.\n if (queuedContinuation && !streamState.hasStreamStarted) {\n if (streamState.queuedFailed) failQueuedContinuation(queryClient, session, streamState)\n return\n }\n\n // The server refused the turn before storing anything (a parent that is gone, a model\n // that is down): say the send failed and offer Retry with the question, instead of letting\n // it vanish with nothing in the thread. Re-read the thread in case the server did store it.\n if (\n streamState.serverError &&\n !streamState.userMessageId &&\n !streamState.assistantId &&\n !queuedContinuation\n ) {\n if (ownsActiveGeneration()) {\n session.setConversationError(\n streamState.conversationId,\n streamState.serverError,\n content\n )\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n // Undo the optimistic 'in_progress' set when the send started.\n void invalidateConversationLists(queryClient)\n }\n return\n }\n\n const ownsGeneration = ownsActiveGeneration()\n if (ownsGeneration) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n }\n\n // The user's own generation just consumed AI usage \u2014 refresh the\n // \"\u00A3 used today\" indicator now instead of polling for it.\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.userUsageToday() })\n\n // Steering that reached the agent too late to steer this turn was\n // deferred by the backend rather than allowed to derail the answer.\n // Now that the turn is done, submit it as a new turn \u2014 threaded off the\n // assistant message that just finished, exactly as if the user had sent\n // it a moment later. Sent as one turn so a burst reads as a single\n // follow-up. Fire-and-forget via the ref so we don't block this turn's\n // completion bookkeeping (and to sidestep the self-reference).\n if (streamState.deferredInterjections.length > 0) {\n const followUp = streamState.deferredInterjections.join('\\n\\n')\n const threadParent = streamState.assistantId\n if (threadParent) {\n session.clearQueuedMessages(threadParent)\n }\n // In the conversation and workspace of the turn it steered, captured now: the view (or\n // the surface's workspace) may have moved on while the turn ran.\n void sendMessageRef.current?.(\n followUp,\n threadParent,\n streamState.workspaceId && streamState.conversationId !== 'new'\n ? {\n target: {\n workspaceId: streamState.workspaceId,\n conversationId: streamState.conversationId,\n },\n }\n : undefined\n )\n }\n\n // The conversations list cache is patched to 'in_progress' on stream\n // start (see the stream handlers). Patch it back to 'completed' here\n // so the Status column / sidebar reflect reality without a refetch.\n if (ownsGeneration) {\n const lastStatus = streamState.serverError ? 'failed' : 'completed'\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: lastStatus,\n })\n }\n\n // A new conversation changes the workspace's conversation_count \u2014 refresh\n // the workspaces list so onboarding's \"Ask ARBI\" step ticks reactively.\n if (isNewConversation && ownsGeneration) invalidateUserWorkspaces()\n\n if (ownsGeneration) {\n clearLoadingState(queryClient, streamState.conversationId)\n }\n } catch (error) {\n flushStreamingTokens(queryClient)\n const isAbort = error instanceof Error && error.name === 'AbortError'\n // The server stored the turn and only the connection dropped: the run is not over.\n const isDroppedConnection = !streamState.serverError && !isAbort && !streamState.isStopped()\n if (queuedContinuation && !streamState.hasStreamStarted) {\n // The server holds this follow-up in its queue already, and runs it in turn.\n if (isDroppedConnection && streamState.queuedUserMessageId) {\n if (streamState.queuedClientId) {\n session.removeQueuedMessage(streamState.queuedClientId)\n }\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n return\n }\n failQueuedContinuation(queryClient, session, streamState)\n return\n }\n\n if (streamState.isStopped() || isAbort) {\n console.debug('Message sending was aborted by user')\n // The stopped stream leaves its assistant message loading with no stream behind it, and\n // a queued follow-up is not the owner so nothing else clears it. Clear it and re-read the\n // thread: a follow-up the server still runs is attached again, a stopped one shows its end.\n clearLoadingState(queryClient, streamState.conversationId)\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n if (ownsActiveGeneration()) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: 'completed',\n })\n }\n return\n }\n\n console.error('Message sending failed:', error)\n if (!ownsActiveGeneration()) return\n\n // A dropped connection after the server stored the question does not end the turn: the\n // run goes on there. Failing it here offered Retry, which deleted the question under the\n // live answer (its answer then landed in the thread with no question) and, if the resend\n // failed too, left the view on the deleted turn. Re-read the thread instead: a running\n // answer is attached again, a failed one shows Retry, a finished one shows its answer.\n // Generation is held until the thread is re-read (or a few seconds pass, offline), so no\n // \"Response Incomplete\" alert offers to delete the question meanwhile.\n if (isDroppedConnection && streamState.userMessageId) {\n let timer: ReturnType<typeof setTimeout> | undefined\n await Promise.race([\n queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n }),\n new Promise((resolve) => {\n timer = setTimeout(resolve, RECONCILE_TIMEOUT_MS)\n }),\n ])\n clearTimeout(timer)\n clearLoadingState(queryClient, streamState.conversationId)\n if (ownsActiveGeneration()) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n }\n void invalidateConversationLists(queryClient)\n return\n }\n\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: 'failed',\n })\n\n // Open the upgrade modal if either (a) the error string carries\n // LiteLLM's ExceededBudget payload directly, or (b) the project's\n // cached AI usage is used up. Either path beats showing only\n // the conversation's generic error.\n const quota =\n quotaFromStreamError(error) ??\n cachedQuotaUsedUp(queryClient, session.getState().workspaceId)\n if (quota) chatHost?.onQuotaExceeded?.(quota)\n\n session.setConversationError(\n streamState.conversationId,\n error instanceof Error ? error.message : String(error),\n content\n )\n }\n },\n [\n selectedWorkspaceId,\n parentMessageId,\n queryClient,\n session,\n createHandlers,\n chatHost,\n arbi,\n invalidateUserWorkspaces,\n routeMessage,\n postComment,\n ]\n )\n\n // Keep the ref pointing at the latest sendMessage so the deferred-interjection\n // resubmit inside sendMessage always calls the current closure.\n sendMessageRef.current = sendMessage\n\n const handleCreateBranch = useCallback(\n async (parentMessageExtId: string | null, newContent: string) => {\n if (!newContent.trim() || !selectedWorkspaceId) return\n await sendMessage(newContent, parentMessageExtId, { branch: true })\n },\n [selectedWorkspaceId, sendMessage]\n )\n\n const handleSendMessage = useCallback(\n async (options?: SendMessageOptions) => {\n const currentMessage = selectDraft(session.getState()).trim()\n // The draft a shared thread starts with (`@<assistant> `) is not a question yet.\n if (!selectedWorkspaceId || !hasMessageBody(currentMessage, assistantLabels(assistantName)))\n return\n\n // A send consumes the suggested follow-up, whether or not it was used \u2014\n // the next turn's metadata brings a fresh one.\n session.setSuggestedQuery(null)\n\n // Chat runs against the server-side AI \u2014 there's nothing to queue offline.\n // Don't fire a mutation that would just pause and hang; tell the user.\n if (refuseChatWhenOffline()) return\n\n // While a turn is active, only true out-of-band controls use /interject.\n // Ordinary text still goes through the typed query endpoint, whose\n // arbi.message_queued event persists and renders it before the response gate\n // opens. The backend then either steers it into the next tool boundary or\n // starts a normal follow-up turn after the current final answer completes.\n if (isGenerating) {\n const convKey = session.getState().conversationId || 'new'\n const genState = session.getState().generating[convKey]\n const streamingAssistantId = genState?.streamingAssistantId\n\n // In a thread, a message that does not @mention the assistant is a comment between\n // people: post it straight away instead of queueing it into the running turn.\n const route = routeMessage(currentMessage)\n if (route.isComment && streamingAssistantId) {\n session.setDraft(draftAfterSend(queryClient, session, route.isComment, assistantName))\n await postComment(currentMessage, streamingAssistantId, route.mentions)\n return\n }\n\n if (streamingAssistantId) {\n const command = currentMessage.toLowerCase()\n const isPause = command === AGENT_CONTROL_COMMANDS.pause\n const isResume = command === AGENT_CONTROL_COMMANDS.resume\n const isReport =\n command === AGENT_CONTROL_COMMANDS.report ||\n command.startsWith(`${AGENT_CONTROL_COMMANDS.report} `)\n\n session.setDraft(draftAfterSend(queryClient, session, route.isComment, assistantName))\n\n if (isPause) {\n session.setAgentControlState(streamingAssistantId, 'pausing')\n } else if (isResume) {\n session.setAgentControlState(streamingAssistantId, 'resuming')\n }\n\n if (isReport) {\n await requestAgentStatus(arbi, session, streamingAssistantId, currentMessage)\n } else if (isPause || isResume) {\n await arbi.assistant.interject(streamingAssistantId, currentMessage)\n } else {\n const queuedClientId = `queued-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`\n session.addQueuedMessage(streamingAssistantId, {\n clientId: queuedClientId,\n content: currentMessage,\n serverId: null,\n acknowledged: false,\n createdAt: Date.now(),\n })\n await sendMessage(currentMessage, streamingAssistantId, {\n ...options,\n queuedContinuation: true,\n queueOwnerAssistantId: streamingAssistantId,\n queuedClientId,\n })\n }\n return\n }\n // Keep the draft intact during the brief pre-stream window.\n return\n }\n\n const parentId = session.getState().cursor\n\n session.setDraft(\n draftAfterSend(queryClient, session, routeMessage(currentMessage).isComment, assistantName)\n )\n\n await sendMessage(currentMessage, parentId, options)\n },\n [\n selectedWorkspaceId,\n isGenerating,\n session,\n sendMessage,\n arbi,\n routeMessage,\n postComment,\n queryClient,\n assistantName,\n ]\n )\n\n const handleAbortGeneration = useCallback(async () => {\n // A second press (a double-click) must not stop the run again: it would cancel twice, and\n // once the local abort has landed it would clear the stopped-stream marker, so the stream's\n // error would read as a failed answer.\n const stream = session.getState().generating[conversationKey]\n if (stopInFlightRef.current || stream?.isGenerating === false) return\n // A tap right after a Stop must not stop the follow-up the queue started in the meantime.\n if (Date.now() - lastStopAtRef.current < STOP_REPEAT_WINDOW_MS) return\n lastStopAtRef.current = Date.now()\n stopInFlightRef.current = true\n try {\n // Stop the run on the server first; closing the stream alone leaves it running and\n // its answer would arrive later.\n const controller = stream?.abortController ?? null\n stoppedStreamRef.current = controller\n let streamKey = conversationKey\n let responseId = stream?.streamingAssistantId ?? null\n // Pressed before the stream reported its id: the run already exists on the server, so wait\n // for the id instead of only closing the stream. Further presses meanwhile do nothing.\n if (!responseId && controller) {\n const reported = await waitForResponseId(session, controller)\n if (reported) {\n streamKey = reported.conversationKey\n responseId = reported.responseId\n }\n }\n // In a sub-agent's branch this is the run that delegated it.\n const threads =\n queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(streamKey))?.threads ?? []\n const runId = responseId ? getRunToCancel(threads, responseId) : null\n if (runId) {\n try {\n await arbi.assistant.cancel(runId)\n } catch {\n // Still stop here (the run may already have ended); say the server may keep going.\n notify.warning(\n \"Stopped here, but the server didn't confirm: the answer may still appear later.\"\n )\n }\n }\n // The cancel is awaited, and the server starts the next queued follow-up as soon as it lands:\n // that follow-up may already own this conversation's generation state and attach. Only close\n // the stream this Stop belongs to, or the next answer goes silent (\"Working\", no stop square).\n const current = session.getState().generating[streamKey]\n const isStoppedStream = controller\n ? current?.abortController === controller\n : !current?.streamingAssistantId || current.streamingAssistantId === responseId\n if (isStoppedStream) session.abortConversationGeneration(streamKey)\n // A reattached run has no local controller: close its stream too, or it keeps painting. The\n // attach follows this conversation's streaming message (in a sub-agent branch, the branch's\n // reply), not the delegating run that was cancelled, so match it by that id.\n if (responseId) disconnectAttachedRun(streamKey, responseId)\n } finally {\n stopInFlightRef.current = false\n }\n }, [session, arbi, conversationKey, queryClient])\n\n const handleRetryOrphanedMessage = useCallback(\n async (messageContent: string, parentId: string | null, messageExtId: string) => {\n // One retry at a time: the alert's Retry and the composer's retry (or a double click) must\n // not delete and resend twice. Released however the retry ends.\n if (retryInFlightRef.current) return\n // Offline the delete would be paused and the resend refused, leaving neither done.\n if (refuseChatWhenOffline()) return\n retryInFlightRef.current = true\n try {\n // A failed parent (a follow-up the restart sweep failed behind a failed answer) is\n // refused by the server, so the resend goes to the nearest message above it instead.\n const replyTo = currentConversationId\n ? resolveReplyTarget(queryClient, currentConversationId, parentId)\n : parentId\n if (!replyTo && currentConversationId) {\n try {\n await arbi.conversations.delete(currentConversationId)\n removeConversationFromLists(queryClient, currentConversationId)\n session.startNewConversation()\n } catch (error) {\n console.error('Failed to delete conversation with orphaned first message:', error)\n }\n } else if (replyTo) {\n try {\n await arbi.conversations.deleteMessage(messageExtId)\n // The message and its replies are gone from whichever thread held them.\n void queryClient.invalidateQueries(allConversationThreads)\n } catch (error) {\n console.error('Failed to delete orphaned message:', error)\n }\n }\n\n await sendMessage(messageContent, replyTo)\n } finally {\n retryInFlightRef.current = false\n }\n },\n [currentConversationId, arbi, session, sendMessage, queryClient]\n )\n\n const handleRetrySend = useCallback(async () => {\n if (isGenerating || !lastFailedMessage || retryInFlightRef.current) return\n if (refuseChatWhenOffline()) return\n retryInFlightRef.current = true\n try {\n session.clearConversationError(conversationKey)\n // sendMessage replies to the nearest message the server accepts: the view may still point at\n // a turn a Retry deleted, or at a failed answer.\n const parentId = session.getState().cursor\n await sendMessage(lastFailedMessage, parentId)\n } finally {\n retryInFlightRef.current = false\n }\n }, [isGenerating, lastFailedMessage, session, conversationKey, sendMessage])\n\n const clearErrorState = useCallback(() => {\n session.clearConversationError(conversationKey)\n }, [session, conversationKey])\n\n // Clear error state when starting a new conversation\n useEffect(() => {\n if (currentConversationId === null) {\n session.clearConversationError('new')\n }\n }, [currentConversationId, session])\n\n return {\n handleCreateBranch,\n handleSendMessage,\n handleAbortGeneration,\n handleRetrySend,\n handleRetryOrphanedMessage,\n clearErrorState,\n }\n}\n"],
|
|
5
|
-
"mappings": "AAOA,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD,SAAS,sBAAwC;AACjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,cAAc;AACvB,SAAS,qBAAqB;AAC9B,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,mBAAmB;AAC5B,SAAS,aAAa,2BAA2B;AAEjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,wBAAwB;AACjC,SAAS,gBAAgB,mBAAmB,uBAAuB;AACnE,SAAS,2BAA2B;AACpC,SAAS,kBAAkB,iBAAiB;AAC5C,SAAS,oBAAoB,uBAAuB;AACpD,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAA2C;AACpD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,MAAM,uBAAuB;AAwC7B,SAAS,eACP,aACA,SACA,YACA,eACQ;AACR,QAAM,SAAS,qBAAqB,aAAa,QAAQ,SAAS,EAAE,cAAc;AAClF,SAAO,UAAU,CAAC,aAAa,IAAI,aAAa,MAAM;AACxD;AAMA,SAAS,uBACP,aACA,SACA,aAMM;AACN,MAAI,YAAY,qBAAqB;AACnC;AAAA,MACE;AAAA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A,MAC7B;AAAA,IACF;AAAA,IACA,CAAC,uBAAuB,MAAM,SAAS,aAAa,WAAW;AAAA,EACjE;AAEA,QAAM,kBAAkB,YAAY,YAAY;AAC9C,QAAI,gBAAgB,CAAC,qBAAqB,iBAAiB,QAAS;AACpE,QAAI,sBAAsB,EAAG;AAC7B,qBAAiB,UAAU;AAC3B,QAAI;AACF,cAAQ,uBAAuB,eAAe;AAG9C,YAAM,WAAW,QAAQ,SAAS,EAAE;AACpC,YAAM,YAAY,mBAAmB,QAAQ;AAAA,IAC/C,UAAE;AACA,uBAAiB,UAAU;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,cAAc,mBAAmB,SAAS,iBAAiB,WAAW,CAAC;AAE3E,QAAM,kBAAkB,YAAY,MAAM;AACxC,YAAQ,uBAAuB,eAAe;AAAA,EAChD,GAAG,CAAC,SAAS,eAAe,CAAC;AAG7B,YAAU,MAAM;AACd,QAAI,0BAA0B,MAAM;AAClC,cAAQ,uBAAuB,KAAK;AAAA,IACtC;AAAA,EACF,GAAG,CAAC,uBAAuB,OAAO,CAAC;AAEnC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["/**\n * The chat engine's actions on a conversation: send (a turn, or a comment to the people in a\n * thread), branch, retry, stop, and the run-control commands typed while a turn runs. A turn goes\n * through `arbi.assistant.ask`, its frames through the stream handlers, and its state lives in the\n * session (`ArbiSessionState`) and the conversation cache.\n */\n\nimport { flushDocumentForTurn } from './turn-flush'\nimport { pendingChatModelSave } from '../config/config-hooks'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { useQueryClient, type QueryClient } from '@tanstack/react-query'\nimport {\n ArbiApiError,\n STOP_REPEAT_WINDOW_MS,\n getRunToCancel,\n quotaFromStreamError,\n type ConversationResponse as Conversation,\n type ThreadsResponse,\n} from '@arbidocs/sdk/browser'\nimport type { components } from '@arbidocs/client'\nimport { notify } from '../shell'\nimport { arbiQueryKeys } from '../hooks'\nimport { useArbi } from '../useArbi'\nimport { requestAgentStatus } from './request-agent-status'\nimport { useArbiHost } from '../host/config'\nimport { selectDraft, useArbiSessionStore } from '../session'\nimport type { ArbiSessionStore } from '../session/store'\nimport {\n invalidateConversationLists,\n isConversationShared,\n patchConversation,\n patchConversationList,\n removeConversationFromLists,\n} from '../conversation-list'\nimport {\n allConversationThreads,\n clearLoadingState,\n flushStreamingTokens,\n getThreadsQueryKey,\n isConversationEmpty,\n updateUserMessageStateInCache,\n} from './conversation-cache'\nimport {\n assistantLabels,\n cachedAssistantMode,\n cachedMentionCandidates,\n isCommentToPeople,\n} from './conversation-mentions'\nimport { useAssistantName } from '../host/assistant-copy'\nimport { hasMessageBody, toMessageMentions, extractMentions } from './mentions'\nimport { takeDocumentForTurn } from './open-document'\nimport { agentChatOwnerOf, creatorOf } from './agent-chat-owner'\nimport { bindThreadDocument, boundDocumentOf } from './thread-binding'\nimport { resolveReplyTarget } from './reply-target'\nimport {\n confirmConversationWorkspace,\n conversationWorkspaceOf,\n watchConversationWorkspaces,\n} from './conversation-workspace'\nimport { useStreamHandlers, type StreamState } from './stream-handlers'\nimport {\n AGENT_CONTROL_COMMANDS,\n cachedQuotaUsedUp,\n disconnectAttachedRun,\n refuseChatWhenOffline,\n waitForResponseId,\n} from './turn-control'\n\ntype MessageInput = components['schemas']['MessageInput']\ntype MessageMention = components['schemas']['MessageMention']\n\n/** How long a dropped turn holds its generating state while the thread is re-read. */\nconst RECONCILE_TIMEOUT_MS = 5000\n\nexport interface SendMessageOptions {\n /** An explicit edit/fork, rather than appending a human message to the shared thread. */\n branch?: boolean\n queuedContinuation?: boolean\n queueOwnerAssistantId?: string\n queuedClientId?: string\n /**\n * Bypasses the normal single-pinned-document tools computation (the chat's documents and its\n * pin, see `buildTurnRequest`) for this one send.\n * The app's general \"pin a document\" feature is deliberately one-at-a-time\n * (`selectFullContextDocument`) \u2014 a pinned TEXT doc's full content goes\n * straight into the AGENT's chat prompt, so more than one at a time risks\n * blowing that context window. Generate image is a different resource\n * entirely: reference images never touch the agent's chat context \u2014 they go\n * to the separate ImageGen model in its own request \u2014 so multiple\n * references (e.g. \"combine these two logos\") don't compound against that\n * budget, even though they still cost real tokens against ImageGen's own\n * call. This lets that caller build its own tools object with every\n * selected reference doc instead of touching the single global pin.\n */\n toolsOverride?: MessageInput['tools']\n /**\n * Send in this conversation and workspace rather than the open ones: a follow-up captured when\n * its turn started (a deferred interjection), sent after the view may have moved on.\n */\n target?: TurnTarget\n}\n\n/** The conversation and workspace a turn belongs to, captured when it starts. */\nexport interface TurnTarget {\n workspaceId: string\n conversationId: string\n}\n\n/**\n * The draft a send leaves behind. A shared chat addresses ARBI again, except after a comment to\n * people: then the box is left empty, which a shared chat reads as a comment to the thread.\n */\nfunction draftAfterSend(\n queryClient: QueryClient,\n session: ArbiSessionStore,\n wasComment: boolean,\n assistantName: string\n): string {\n const shared = isConversationShared(queryClient, session.getState().conversationId)\n return shared && !wasComment ? `@${assistantName} ` : ''\n}\n\n/**\n * A queued follow-up the backend refused before its turn started: mark its bubble failed and\n * take it out of the queue, so it does not sit there as if it were still waiting.\n */\nfunction failQueuedContinuation(\n queryClient: QueryClient,\n session: ArbiSessionStore,\n streamState: {\n conversationId: string\n queuedUserMessageId: string | null\n queueOwnerAssistantId: string | null\n queuedClientId: string | null\n }\n): void {\n if (streamState.queuedUserMessageId) {\n updateUserMessageStateInCache(\n queryClient,\n streamState.conversationId,\n streamState.queuedUserMessageId,\n 'failed',\n false\n )\n }\n if (streamState.queuedClientId) {\n session.removeQueuedMessage(streamState.queuedClientId)\n }\n notify.error('Queued message failed to send')\n}\n\n/** The signed-in user's id, or null before the session is known. */\nfunction signedInUserId(arbi: { user: { identity: () => { externalId: string } | null } }) {\n try {\n return arbi.user.identity()?.externalId ?? null\n } catch {\n return null\n }\n}\n\n/** What the actions act on: the open workspace and conversation, as the session holds them. */\nexport interface ConversationActionsInput {\n selectedWorkspaceId: string | null\n /** The cursor when the view rendered (the stream handlers place a branch against it). */\n parentMessageId: string | null\n /** The open conversation's key (`new` for a new chat). */\n conversationKey: string\n isGenerating: boolean\n lastFailedMessage: string | null\n}\n\n/** The actions on the open conversation. */\nexport function useConversationActions({\n selectedWorkspaceId,\n parentMessageId,\n conversationKey,\n isGenerating,\n lastFailedMessage,\n}: ConversationActionsInput) {\n const queryClient = useQueryClient()\n const session = useArbiSessionStore()\n const currentConversationId = conversationKey === 'new' ? null : conversationKey\n const invalidateUserWorkspaces = useCallback(\n () => void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() }),\n [queryClient]\n )\n\n const arbi = useArbi()\n // Each conversation stays in the workspace it was opened in, though the surface switches.\n useState(() => watchConversationWorkspaces(queryClient, session))\n const createHandlers = useStreamHandlers()\n const chatHost = useArbiHost().chat\n const assistantName = useAssistantName()\n const mentionCandidates = useCallback(\n () =>\n cachedMentionCandidates(\n queryClient,\n session.getState().workspaceId,\n signedInUserId(arbi),\n assistantName\n ),\n [queryClient, session, arbi, assistantName]\n )\n // The local stream a Stop is closing. Stop cancels the run on the server before it aborts the\n // stream, so the connection can drop first with a network error that is not an abort.\n const stoppedStreamRef = useRef<AbortController | null>(null)\n // True while a Stop's server cancel is in flight, so a second press does not cancel again.\n const stopInFlightRef = useRef(false)\n // When the last Stop was pressed. A press within STOP_REPEAT_WINDOW_MS of it is a double tap.\n const lastStopAtRef = useRef(0)\n // True while a Retry deletes and resends, so a second press does not do it again.\n const retryInFlightRef = useRef(false)\n // Lets sendMessage resubmit a deferred interjection as a new turn without a\n // self-reference (it is a useCallback that would otherwise close over a stale\n // or not-yet-defined copy of itself). Kept current just below its definition.\n const sendMessageRef = useRef<\n | ((content: string, parentId?: string | null, options?: SendMessageOptions) => Promise<void>)\n | null\n >(null)\n\n /**\n * Shared posts, and posts in a `mentioned` thread, run ARBI only when addressed; posts in an\n * ordinary solo chat address it implicitly.\n */\n const routeMessage = useCallback(\n (content: string, conversationId?: string | null) => {\n const state = session.getState()\n const convId = conversationId === undefined ? state.conversationId : conversationId\n const { newConversationAssistantMode } = state\n const candidates = mentionCandidates()\n const mentioned = extractMentions(content, candidates)\n const assistantMode = cachedAssistantMode(queryClient, convId, newConversationAssistantMode)\n const isComment = isCommentToPeople(queryClient, convId, content, candidates)\n const mentions = toMessageMentions(mentioned) as MessageMention[]\n // A message not taken as a comment addresses ARBI. In an existing `mentioned` thread that is\n // only one that @mentions it; what is left is the first message of a thread not created\n // yet, whose turn creates it in `mentioned` mode.\n if (\n !isComment &&\n assistantMode === 'mentioned' &&\n !mentions.some((m) => m.type === 'assistant')\n ) {\n mentions.push({ type: 'assistant' })\n }\n return {\n mentions,\n assistantMode,\n isComment,\n }\n },\n [queryClient, session, mentionCandidates]\n )\n\n /** Post a comment (no assistant run) and land the thread on it. */\n const postComment = useCallback(\n async (\n content: string,\n parentId: string | null,\n mentions: MessageMention[],\n branch = false\n ) => {\n const convId = session.getState().conversationId\n try {\n const saved = await arbi.conversations.postMessage({\n content,\n mentions,\n // Only an explicit edit creates a branch. Ordinary comments append to the\n // server's latest message, so simultaneous sends stay visible together. Else\n // (nothing yet) start a thread. The mode only applies to a conversation it creates.\n ...(branch && parentId\n ? { previous_message_ext_id: parentId }\n : convId\n ? { conversation_ext_id: convId }\n : {}),\n assistant_mode: 'mentioned',\n })\n const conversationId = saved.conversation_ext_id\n const nowIso = new Date().toISOString()\n if (!convId) {\n // A comment starts the thread without a turn to carry its binding: bind it right after.\n const bindTo = session.getState().newChatDocumentId\n session.moveConversation('new', conversationId)\n if (bindTo) session.setNewChatDocumentId(null)\n patchConversationList(queryClient, session.getState().workspaceId, (old) => [\n {\n external_id: conversationId,\n title: content.slice(0, 40),\n created_by_ext_id: saved.created_by_ext_id,\n updated_by_ext_id: null,\n created_at: nowIso,\n updated_at: nowIso,\n // A mention of someone who cannot see it yet shares it server-side: refetched below.\n is_shared: false,\n message_count: 1,\n last_message_status: 'completed',\n assistant_mode: 'mentioned',\n } as Conversation,\n ...old,\n ])\n if (bindTo)\n bindThreadDocument(arbi, queryClient, conversationId, bindTo).catch(() =>\n notify.error('Could not attach the document to this thread')\n )\n invalidateUserWorkspaces()\n } else {\n patchConversation(queryClient, conversationId, (c) => ({\n ...c,\n message_count: c.message_count + 1,\n updated_at: nowIso,\n }))\n }\n // Mentioning someone shares the conversation on the server, which this cache cannot know.\n if (mentions.some((m) => m.type === 'user')) {\n await invalidateConversationLists(queryClient)\n }\n await queryClient.invalidateQueries({ queryKey: getThreadsQueryKey(conversationId) })\n session.setCursor(saved.external_id)\n } catch (error) {\n notify.error(\n (error instanceof ArbiApiError && error.detail) || 'Failed to post the message'\n )\n // Give the text back rather than lose it.\n if (!selectDraft(session.getState())) session.setDraft(content)\n }\n },\n [arbi, session, queryClient, invalidateUserWorkspaces]\n )\n\n const sendMessage = useCallback(\n async (content: string, requestedParentId?: string | null, options?: SendMessageOptions) => {\n // Never reply to a failed or deleted message: the server refuses it, so every Retry and every\n // new message would fail again. A queued follow-up names the running turn on purpose. With\n // nothing above to reply to, the parent stays: only a fresh conversation could take it.\n const target = options?.target\n const parentId =\n options?.queuedContinuation || !requestedParentId\n ? requestedParentId\n : (resolveReplyTarget(\n queryClient,\n (target ? target.conversationId : session.getState().conversationId) || 'new',\n requestedParentId\n ) ?? requestedParentId)\n const route = routeMessage(content, target?.conversationId)\n if (route.isComment && !options?.queuedContinuation && !target) {\n await postComment(content, parentId ?? null, route.mentions, options?.branch)\n return\n }\n // A model picked just now is still being saved: the turn runs on it, not on the config before.\n const modelSave = pendingChatModelSave(session)\n if (modelSave) await modelSave.catch(() => undefined)\n const state = session.getState()\n const convId = target ? target.conversationId : state.conversationId\n const convKey = convId || 'new'\n // The turn's workspace, captured now: the conversation's own (a docked or scoped chat keeps\n // its conversation across a switch), else the surface's for a new conversation. Named on the\n // request, so neither a switch nor the session's open workspace can move it.\n const turnWorkspaceId =\n target?.workspaceId ?? conversationWorkspaceOf(queryClient, convId) ?? selectedWorkspaceId\n const agentChat = state.newAgentChat\n // An existing conversation's agent: as recorded, else its creator when that is one of the\n // person's own agents (an agent chat runs under the agent's session; the record does not\n // survive a sign-out, or another device).\n let agentExtId = convId\n ? state.agentChatOwners[convId]\n : agentChat?.workspaceId === turnWorkspaceId\n ? agentChat.agentId\n : undefined\n // Only a conversation an agent created is looked up (an ordinary send never waits on it).\n if (convId && !agentExtId && creatorOf(queryClient, convId)?.startsWith('agt-')) {\n agentExtId = await agentChatOwnerOf(queryClient, () => arbi.agents.list(), convId)\n if (agentExtId) session.setAgentChatOwner(convId, agentExtId)\n }\n const queuedContinuation = options?.queuedContinuation === true\n // First message of a brand-new conversation bumps the workspace's\n // conversation_count \u2014 used to tick the \"Ask ARBI\" onboarding step.\n const isNewConversation = !convId\n\n const documentIds = (state.conversationDocuments[convKey] || []).map((doc) => doc.docId)\n // The chat's facts ride every message of it (snapshot semantics, like its documents).\n const factIds = [...(state.conversationFacts[convKey] || [])]\n\n const newConfigId = state.chatModel\n\n // Frontend is the single source of truth for which config a request\n // uses (Option B): send the same config the model selector resolves &\n // displays (see useConversationSettings) \u2014 explicit per-conversation\n // choice (`newConfigId`) wins, otherwise the user's persisted\n // `last_config`, so a selected config (e.g. one with ARTIFACTS_ENABLED)\n // actually drives the chat instead of being silently dropped to an\n // empty config. `newConfigId` alone is insufficient \u2014 it is transient\n // and cleared on every new conversation. Read `last_config` from the\n // shared settings cache by partial key match: openapi-react-query\n // suffixes the query key with request options and the settings hook is\n // token-gated, so the hook value can momentarily be undefined here even\n // though the data is cached app-wide.\n const cachedSettings = queryClient\n .getQueriesData<{ last_config?: string }>({ queryKey: arbiQueryKeys.userSettings() })\n .map(([, data]) => data)\n .find((data) => data?.last_config)\n const lastConfigId = cachedSettings?.last_config\n const resolvedConfigId = newConfigId || (agentExtId ? undefined : lastConfigId)\n\n // PA mode delegates the turn to the personal agent (`buildTurnRequest` prefixes `/pa ` so\n // the backend routes it straight to the delegation stream).\n const isPaMode = !agentExtId && state.paMode\n\n // Drafting mode: the thread's own document is named (a reference, never its content): the one\n // the thread is bound to (started from it, or attached in it), else one made in this thread\n // and open. A document merely open beside a chat is not: a new chat starts unbound. While an\n // earlier version of it is on screen the viewer returns to the live document. For a Word\n // document the server binds the live document: the assistant reads what it needs on demand\n // and edits it as tracked changes. For an html/react artifact it gets the source and a\n // targeted edit tool. PA-mode turns are delegated to a separate agent and never touch\n // artifacts.\n const threadDocumentId = boundDocumentOf(queryClient, { ...state, conversationId: convId })\n const activeArtifactExtId = isPaMode\n ? null\n : takeDocumentForTurn({\n boundDocumentId: threadDocumentId,\n conversationId: convId,\n workspaceId: turnWorkspaceId,\n })\n\n // An editor holding unsaved changes to that document saves them first: ARBI works on what\n // the person sees.\n const flushing = flushDocumentForTurn(activeArtifactExtId)\n if (flushing) await flushing\n\n // A workflow launch can leave structured tools for its one send; consume them here.\n const pendingTools = state.pendingTools\n if (pendingTools) session.setPendingTools(null)\n const toolsOverride = options?.toolsOverride ?? pendingTools ?? undefined\n\n const request = {\n question: content,\n workspaceId: turnWorkspaceId!,\n docIds: documentIds,\n pinnedDocumentId: state.pinnedDocumentId,\n factIds,\n tools: toolsOverride,\n personalAgent: isPaMode,\n activeArtifactExtId,\n // A new chat about a document is bound by its first turn, on the server (every device).\n ...(!convId && threadDocumentId ? { bindDocumentId: threadDocumentId } : {}),\n previousResponseId: parentId,\n // The first turn of an existing conversation with no message yet (a task's thread) runs in\n // it: without its id the server starts a new conversation for the turn.\n ...(convId && !parentId && !options?.branch && isConversationEmpty(queryClient, convId)\n ? { conversationId: convId }\n : {}),\n agentId: agentExtId,\n model: resolvedConfigId,\n mentions: route.mentions,\n // A brand-new conversation starts in the mode picked in the composer.\n ...(!convId && route.assistantMode === 'mentioned'\n ? { assistantMode: 'mentioned' as const }\n : {}),\n }\n\n const abortController = new AbortController()\n if (!queuedContinuation) {\n session.setConversationGenerating(convKey, true, abortController)\n }\n\n // Optimistically mark this conversation in-progress the instant we start a\n // turn. Without this, Conversation's \"reconcile stale isGenerating\" effect\n // runs on the setConversationGenerating(true) above, sees the conversation\n // list's last_message_status still 'completed' from the PREVIOUS turn (the\n // stream_start patch below only lands ~50ms later), and immediately clears\n // isGenerating \u2014 which race-hid the live status bar on every follow-up\n // turn (first turns were exempt: the new conversation isn't in the list\n // yet). Patching here closes that window. No-op for a brand-new\n // conversation (convKey === 'new' isn't in the list).\n if (!queuedContinuation) {\n patchConversation(queryClient, convKey, { last_message_status: 'in_progress' })\n }\n\n // Mutable stream state \u2014 shared by all SSE handlers via closure\n const streamState: StreamState = {\n conversationId: convKey,\n workspaceId: turnWorkspaceId,\n assistantId: null,\n // 0 = nothing narrated yet, so nothing is owed a reading window.\n lastNarrationSettledAt: 0,\n // True once the model has pivoted to a tool call and not yet resumed\n // prose. Prose arriving while this is set opens a NEW narration, so the\n // one before it closes: paragraph break, and everything above becomes\n // superseded. Item boundaries alone cannot say this \u2014 the backend splits\n // a single sentence across several items.\n pivotedSinceProse: false,\n // Steering that landed too late to steer this turn; resubmitted as a new\n // turn once this one completes (see after the ask below).\n deferredInterjections: [],\n queuedContinuation,\n queuedUserMessageId: null,\n hasStreamStarted: false,\n queuedFailed: false,\n abortController,\n isStopped: () => stoppedStreamRef.current === abortController,\n queueOwnerAssistantId: options?.queueOwnerAssistantId ?? null,\n queuedClientId: options?.queuedClientId ?? null,\n // Set when a create_fact / label_facts tool runs this turn, so the Facts\n // table + label vocabulary refresh on completion (see handleComplete).\n factsTouched: false,\n threadDocumentId,\n // Set by the handlers: the server stored the question / reported its own failure.\n userMessageId: null,\n serverError: null,\n }\n\n // A follow-up sent for another conversation than the one on screen places itself under its own\n // parent, not under the screen's cursor.\n const handlers = createHandlers({\n streamState,\n parentMessageId: target ? (parentId ?? null) : parentMessageId,\n parentId,\n })\n // The server's word on the turn's workspace binds the conversation to it.\n const confirmTurnWorkspace = () => {\n if (streamState.workspaceId)\n confirmConversationWorkspace(\n queryClient,\n streamState.conversationId,\n streamState.workspaceId\n )\n }\n const onUserMessageInWorkspace = handlers.onUserMessage\n handlers.onUserMessage = (message) => {\n onUserMessageInWorkspace(message)\n confirmTurnWorkspace()\n }\n if (agentExtId) {\n const onUserMessage = handlers.onUserMessage\n handlers.onUserMessage = (message) => {\n if (message.conversation_ext_id) {\n session.setAgentChatOwner(message.conversation_ext_id, agentExtId)\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.agentChats(agentExtId) })\n }\n onUserMessage(message)\n }\n }\n\n const ownsActiveGeneration = () => {\n const activeGeneration = session.getState().generating[streamState.conversationId]\n return (\n activeGeneration?.abortController === abortController ||\n (!!streamState.assistantId &&\n activeGeneration?.streamingAssistantId === streamState.assistantId)\n )\n }\n\n try {\n performance.mark('arbi:send-message:start')\n await arbi.assistant.ask(request, {\n signal: abortController.signal,\n onMessageQueued: handlers.onMessageQueued,\n onUserMessage: handlers.onUserMessage,\n onStreamStart: handlers.onStreamStart,\n onToken: handlers.onToken,\n onMetadata: handlers.onMetadata,\n onError: handlers.onError,\n onComplete: handlers.onComplete,\n // `response.output_item.added` is deliberately NOT consumed: an item\n // opening told us only that SOME block had started, which is exactly the\n // guess this design gave up. Text arrives via onOutputTextDelta and\n // settles via onOutputItemDone.\n onOutputItemDone: handlers.onOutputItemDone,\n onOutputTextDelta: handlers.onOutputTextDelta,\n onUserInputRequest: handlers.onUserInputRequest,\n onProbeAnswer: handlers.onProbeAnswer,\n onDeferredInterjection: handlers.onDeferredInterjection,\n onAgentControlState: handlers.onAgentControlState,\n onArtifact: handlers.onArtifact,\n onMailDraft: handlers.onMailDraft,\n onElapsedTime: handlers.onElapsedTime,\n onContextUpdate: handlers.onContextUpdate,\n onQuotaExceeded: (quota) => chatHost?.onQuotaExceeded?.(quota),\n onWorkspace: (workspaceId) => {\n streamState.workspaceId = workspaceId\n confirmTurnWorkspace()\n },\n })\n // The stream is over: commit the text still waiting for a frame now, while the message is\n // the streamed one. Left buffered, it lands after the thread is re-read and is appended\n // to the answer the server stored.\n flushStreamingTokens(queryClient)\n\n // A steering response has no assistant stream of its own. The backend\n // accepted the queued user message into the active tool loop. Keep it\n // visibly queued until the parent stream emits its interjection step at\n // the actual tool boundary; that event settles the cache entry.\n if (queuedContinuation && !streamState.hasStreamStarted) {\n if (streamState.queuedFailed) failQueuedContinuation(queryClient, session, streamState)\n return\n }\n\n // The server refused the turn before storing anything (a parent that is gone, a model\n // that is down, a failed setup): say the send failed and offer Retry with the question, and\n // give the question back to the composer, instead of letting it vanish with nothing in the\n // thread. The queued acknowledgement names a response the server never stored, so only a\n // stored question or a started stream means the turn exists. Re-read the thread in case the\n // server did store it.\n if (\n streamState.serverError &&\n !streamState.userMessageId &&\n !streamState.hasStreamStarted &&\n !queuedContinuation\n ) {\n if (ownsActiveGeneration()) {\n session.setConversationError(\n streamState.conversationId,\n streamState.serverError,\n content\n )\n const chat = session.getState()\n const open = chat.conversationId ?? 'new'\n if (open === streamState.conversationId && !chat.drafts[open]) session.setDraft(content)\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n // Undo the optimistic 'in_progress' set when the send started.\n void invalidateConversationLists(queryClient)\n }\n return\n }\n\n const ownsGeneration = ownsActiveGeneration()\n if (ownsGeneration) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n }\n\n // The user's own generation just consumed AI usage \u2014 refresh the\n // \"\u00A3 used today\" indicator now instead of polling for it.\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.userUsageToday() })\n\n // Steering that reached the agent too late to steer this turn was\n // deferred by the backend rather than allowed to derail the answer.\n // Now that the turn is done, submit it as a new turn \u2014 threaded off the\n // assistant message that just finished, exactly as if the user had sent\n // it a moment later. Sent as one turn so a burst reads as a single\n // follow-up. Fire-and-forget via the ref so we don't block this turn's\n // completion bookkeeping (and to sidestep the self-reference).\n if (streamState.deferredInterjections.length > 0) {\n const followUp = streamState.deferredInterjections.join('\\n\\n')\n const threadParent = streamState.assistantId\n if (threadParent) {\n session.clearQueuedMessages(threadParent)\n }\n // In the conversation and workspace of the turn it steered, captured now: the view (or\n // the surface's workspace) may have moved on while the turn ran.\n void sendMessageRef.current?.(\n followUp,\n threadParent,\n streamState.workspaceId && streamState.conversationId !== 'new'\n ? {\n target: {\n workspaceId: streamState.workspaceId,\n conversationId: streamState.conversationId,\n },\n }\n : undefined\n )\n }\n\n // The conversations list cache is patched to 'in_progress' on stream\n // start (see the stream handlers). Patch it back to 'completed' here\n // so the Status column / sidebar reflect reality without a refetch.\n if (ownsGeneration) {\n const lastStatus = streamState.serverError ? 'failed' : 'completed'\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: lastStatus,\n })\n }\n\n // A new conversation changes the workspace's conversation_count \u2014 refresh\n // the workspaces list so onboarding's \"Ask ARBI\" step ticks reactively.\n if (isNewConversation && ownsGeneration) invalidateUserWorkspaces()\n\n if (ownsGeneration) {\n clearLoadingState(queryClient, streamState.conversationId)\n }\n } catch (error) {\n flushStreamingTokens(queryClient)\n const isAbort = error instanceof Error && error.name === 'AbortError'\n // The server stored the turn and only the connection dropped: the run is not over.\n const isDroppedConnection = !streamState.serverError && !isAbort && !streamState.isStopped()\n if (queuedContinuation && !streamState.hasStreamStarted) {\n // The server holds this follow-up in its queue already, and runs it in turn.\n if (isDroppedConnection && streamState.queuedUserMessageId) {\n if (streamState.queuedClientId) {\n session.removeQueuedMessage(streamState.queuedClientId)\n }\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n return\n }\n failQueuedContinuation(queryClient, session, streamState)\n return\n }\n\n if (streamState.isStopped() || isAbort) {\n console.debug('Message sending was aborted by user')\n // The stopped stream leaves its assistant message loading with no stream behind it, and\n // a queued follow-up is not the owner so nothing else clears it. Clear it and re-read the\n // thread: a follow-up the server still runs is attached again, a stopped one shows its end.\n clearLoadingState(queryClient, streamState.conversationId)\n void queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n })\n if (ownsActiveGeneration()) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: 'completed',\n })\n }\n return\n }\n\n console.error('Message sending failed:', error)\n if (!ownsActiveGeneration()) return\n\n // A dropped connection after the server stored the question does not end the turn: the\n // run goes on there. Failing it here offered Retry, which deleted the question under the\n // live answer (its answer then landed in the thread with no question) and, if the resend\n // failed too, left the view on the deleted turn. Re-read the thread instead: a running\n // answer is attached again, a failed one shows Retry, a finished one shows its answer.\n // Generation is held until the thread is re-read (or a few seconds pass, offline), so no\n // \"Response Incomplete\" alert offers to delete the question meanwhile.\n if (isDroppedConnection && streamState.userMessageId) {\n let timer: ReturnType<typeof setTimeout> | undefined\n await Promise.race([\n queryClient.invalidateQueries({\n queryKey: getThreadsQueryKey(streamState.conversationId),\n }),\n new Promise((resolve) => {\n timer = setTimeout(resolve, RECONCILE_TIMEOUT_MS)\n }),\n ])\n clearTimeout(timer)\n clearLoadingState(queryClient, streamState.conversationId)\n if (ownsActiveGeneration()) {\n session.setConversationGenerating(streamState.conversationId, false, null)\n }\n void invalidateConversationLists(queryClient)\n return\n }\n\n patchConversation(queryClient, streamState.conversationId, {\n last_message_status: 'failed',\n })\n\n // Open the upgrade modal if either (a) the error string carries\n // LiteLLM's ExceededBudget payload directly, or (b) the project's\n // cached AI usage is used up. Either path beats showing only\n // the conversation's generic error.\n const quota =\n quotaFromStreamError(error) ??\n cachedQuotaUsedUp(queryClient, session.getState().workspaceId)\n if (quota) chatHost?.onQuotaExceeded?.(quota)\n\n session.setConversationError(\n streamState.conversationId,\n error instanceof Error ? error.message : String(error),\n content\n )\n }\n },\n [\n selectedWorkspaceId,\n parentMessageId,\n queryClient,\n session,\n createHandlers,\n chatHost,\n arbi,\n invalidateUserWorkspaces,\n routeMessage,\n postComment,\n ]\n )\n\n // Keep the ref pointing at the latest sendMessage so the deferred-interjection\n // resubmit inside sendMessage always calls the current closure.\n sendMessageRef.current = sendMessage\n\n const handleCreateBranch = useCallback(\n async (parentMessageExtId: string | null, newContent: string) => {\n if (!newContent.trim() || !selectedWorkspaceId) return\n await sendMessage(newContent, parentMessageExtId, { branch: true })\n },\n [selectedWorkspaceId, sendMessage]\n )\n\n const handleSendMessage = useCallback(\n async (options?: SendMessageOptions) => {\n const currentMessage = selectDraft(session.getState()).trim()\n // The draft a shared thread starts with (`@<assistant> `) is not a question yet.\n if (!selectedWorkspaceId || !hasMessageBody(currentMessage, assistantLabels(assistantName)))\n return\n\n // A send consumes the suggested follow-up, whether or not it was used \u2014\n // the next turn's metadata brings a fresh one.\n session.setSuggestedQuery(null)\n\n // Chat runs against the server-side AI \u2014 there's nothing to queue offline.\n // Don't fire a mutation that would just pause and hang; tell the user.\n if (refuseChatWhenOffline()) return\n\n // While a turn is active, only true out-of-band controls use /interject.\n // Ordinary text still goes through the typed query endpoint, whose\n // arbi.message_queued event persists and renders it before the response gate\n // opens. The backend then either steers it into the next tool boundary or\n // starts a normal follow-up turn after the current final answer completes.\n if (isGenerating) {\n const convKey = session.getState().conversationId || 'new'\n const genState = session.getState().generating[convKey]\n const streamingAssistantId = genState?.streamingAssistantId\n\n // In a thread, a message that does not @mention the assistant is a comment between\n // people: post it straight away instead of queueing it into the running turn.\n const route = routeMessage(currentMessage)\n if (route.isComment && streamingAssistantId) {\n session.setDraft(draftAfterSend(queryClient, session, route.isComment, assistantName))\n await postComment(currentMessage, streamingAssistantId, route.mentions)\n return\n }\n\n if (streamingAssistantId) {\n const command = currentMessage.toLowerCase()\n const isPause = command === AGENT_CONTROL_COMMANDS.pause\n const isResume = command === AGENT_CONTROL_COMMANDS.resume\n const isReport =\n command === AGENT_CONTROL_COMMANDS.report ||\n command.startsWith(`${AGENT_CONTROL_COMMANDS.report} `)\n\n session.setDraft(draftAfterSend(queryClient, session, route.isComment, assistantName))\n\n if (isPause) {\n session.setAgentControlState(streamingAssistantId, 'pausing')\n } else if (isResume) {\n session.setAgentControlState(streamingAssistantId, 'resuming')\n }\n\n if (isReport) {\n await requestAgentStatus(arbi, session, streamingAssistantId, currentMessage)\n } else if (isPause || isResume) {\n await arbi.assistant.interject(streamingAssistantId, currentMessage)\n } else {\n const queuedClientId = `queued-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`\n session.addQueuedMessage(streamingAssistantId, {\n clientId: queuedClientId,\n content: currentMessage,\n serverId: null,\n acknowledged: false,\n createdAt: Date.now(),\n })\n await sendMessage(currentMessage, streamingAssistantId, {\n ...options,\n queuedContinuation: true,\n queueOwnerAssistantId: streamingAssistantId,\n queuedClientId,\n })\n }\n return\n }\n // Keep the draft intact during the brief pre-stream window.\n return\n }\n\n const parentId = session.getState().cursor\n\n session.setDraft(\n draftAfterSend(queryClient, session, routeMessage(currentMessage).isComment, assistantName)\n )\n\n await sendMessage(currentMessage, parentId, options)\n },\n [\n selectedWorkspaceId,\n isGenerating,\n session,\n sendMessage,\n arbi,\n routeMessage,\n postComment,\n queryClient,\n assistantName,\n ]\n )\n\n const handleAbortGeneration = useCallback(async () => {\n // A second press (a double-click) must not stop the run again: it would cancel twice, and\n // once the local abort has landed it would clear the stopped-stream marker, so the stream's\n // error would read as a failed answer.\n const stream = session.getState().generating[conversationKey]\n if (stopInFlightRef.current || stream?.isGenerating === false) return\n // A tap right after a Stop must not stop the follow-up the queue started in the meantime.\n if (Date.now() - lastStopAtRef.current < STOP_REPEAT_WINDOW_MS) return\n lastStopAtRef.current = Date.now()\n stopInFlightRef.current = true\n try {\n // Stop the run on the server first; closing the stream alone leaves it running and\n // its answer would arrive later.\n const controller = stream?.abortController ?? null\n stoppedStreamRef.current = controller\n let streamKey = conversationKey\n let responseId = stream?.streamingAssistantId ?? null\n // Pressed before the stream reported its id: the run already exists on the server, so wait\n // for the id instead of only closing the stream. Further presses meanwhile do nothing.\n if (!responseId && controller) {\n const reported = await waitForResponseId(session, controller)\n if (reported) {\n streamKey = reported.conversationKey\n responseId = reported.responseId\n }\n }\n // In a sub-agent's branch this is the run that delegated it.\n const threads =\n queryClient.getQueryData<ThreadsResponse>(getThreadsQueryKey(streamKey))?.threads ?? []\n const runId = responseId ? getRunToCancel(threads, responseId) : null\n if (runId) {\n try {\n await arbi.assistant.cancel(runId)\n } catch {\n // Still stop here (the run may already have ended); say the server may keep going.\n notify.warning(\n \"Stopped here, but the server didn't confirm: the answer may still appear later.\"\n )\n }\n }\n // The cancel is awaited, and the server starts the next queued follow-up as soon as it lands:\n // that follow-up may already own this conversation's generation state and attach. Only close\n // the stream this Stop belongs to, or the next answer goes silent (\"Working\", no stop square).\n const current = session.getState().generating[streamKey]\n const isStoppedStream = controller\n ? current?.abortController === controller\n : !current?.streamingAssistantId || current.streamingAssistantId === responseId\n if (isStoppedStream) session.abortConversationGeneration(streamKey)\n // A reattached run has no local controller: close its stream too, or it keeps painting. The\n // attach follows this conversation's streaming message (in a sub-agent branch, the branch's\n // reply), not the delegating run that was cancelled, so match it by that id.\n if (responseId) disconnectAttachedRun(streamKey, responseId)\n } finally {\n stopInFlightRef.current = false\n }\n }, [session, arbi, conversationKey, queryClient])\n\n const handleRetryOrphanedMessage = useCallback(\n async (messageContent: string, parentId: string | null, messageExtId: string) => {\n // One retry at a time: the alert's Retry and the composer's retry (or a double click) must\n // not delete and resend twice. Released however the retry ends.\n if (retryInFlightRef.current) return\n // Offline the delete would be paused and the resend refused, leaving neither done.\n if (refuseChatWhenOffline()) return\n retryInFlightRef.current = true\n try {\n // A failed parent (a follow-up the restart sweep failed behind a failed answer) is\n // refused by the server, so the resend goes to the nearest message above it instead.\n const replyTo = currentConversationId\n ? resolveReplyTarget(queryClient, currentConversationId, parentId)\n : parentId\n if (!replyTo && currentConversationId) {\n try {\n await arbi.conversations.delete(currentConversationId)\n removeConversationFromLists(queryClient, currentConversationId)\n session.startNewConversation()\n } catch (error) {\n console.error('Failed to delete conversation with orphaned first message:', error)\n }\n } else if (replyTo) {\n try {\n await arbi.conversations.deleteMessage(messageExtId)\n // The message and its replies are gone from whichever thread held them.\n void queryClient.invalidateQueries(allConversationThreads)\n } catch (error) {\n console.error('Failed to delete orphaned message:', error)\n }\n }\n\n await sendMessage(messageContent, replyTo)\n } finally {\n retryInFlightRef.current = false\n }\n },\n [currentConversationId, arbi, session, sendMessage, queryClient]\n )\n\n const handleRetrySend = useCallback(async () => {\n if (isGenerating || !lastFailedMessage || retryInFlightRef.current) return\n if (refuseChatWhenOffline()) return\n retryInFlightRef.current = true\n try {\n session.clearConversationError(conversationKey)\n // sendMessage replies to the nearest message the server accepts: the view may still point at\n // a turn a Retry deleted, or at a failed answer.\n const parentId = session.getState().cursor\n await sendMessage(lastFailedMessage, parentId)\n } finally {\n retryInFlightRef.current = false\n }\n }, [isGenerating, lastFailedMessage, session, conversationKey, sendMessage])\n\n const clearErrorState = useCallback(() => {\n session.clearConversationError(conversationKey)\n }, [session, conversationKey])\n\n // Clear error state when starting a new conversation\n useEffect(() => {\n if (currentConversationId === null) {\n session.clearConversationError('new')\n }\n }, [currentConversationId, session])\n\n return {\n handleCreateBranch,\n handleSendMessage,\n handleAbortGeneration,\n handleRetrySend,\n handleRetryOrphanedMessage,\n clearErrorState,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAOA,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD,SAAS,sBAAwC;AACjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,cAAc;AACvB,SAAS,qBAAqB;AAC9B,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,mBAAmB;AAC5B,SAAS,aAAa,2BAA2B;AAEjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,wBAAwB;AACjC,SAAS,gBAAgB,mBAAmB,uBAAuB;AACnE,SAAS,2BAA2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B,KAAK;AAAA,IACtC;AAAA,EACF,GAAG,CAAC,uBAAuB,OAAO,CAAC;AAEnC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,12 +4,14 @@ function useMessageTimer({
|
|
|
4
4
|
conversationId,
|
|
5
5
|
messageId,
|
|
6
6
|
isUser,
|
|
7
|
-
isGenerating
|
|
7
|
+
isGenerating,
|
|
8
|
+
startTime: observedStartTime
|
|
8
9
|
}) {
|
|
9
10
|
const session = useArbiSessionStore();
|
|
10
11
|
const convId = conversationId || "new";
|
|
11
12
|
const timerKey = `${convId}:${messageId}`;
|
|
12
|
-
const
|
|
13
|
+
const streamStartTime = useArbiSessionState((s) => s.generating[convId]?.startTime ?? null);
|
|
14
|
+
const generationStartTime = observedStartTime ?? streamStartTime;
|
|
13
15
|
const storedElapsed = useArbiSessionState((s) => s.messageTimers[timerKey]?.elapsedTime);
|
|
14
16
|
const [elapsedTime, setElapsedTime] = useState(0);
|
|
15
17
|
const lastElapsedRef = useRef(0);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/chat/useMessageTimer.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The time an answer has taken: counted on the client while its turn runs (separately from the\n * server's step times), and saved when it stops showing, so a finished answer keeps its time and a\n * re-attached run keeps counting from its real start.\n */\n\nimport { useEffect, useRef, useState } from 'react'\nimport { useArbiSessionState, useArbiSessionStore } from '../session'\n\nexport interface UseMessageTimerOptions {\n conversationId: string | undefined\n messageId: string | undefined\n isUser: boolean\n isGenerating: boolean\n}\n\nexport interface MessageTimerResult {\n /** Seconds. */\n elapsedTime: number\n}\n\nexport function useMessageTimer({\n conversationId,\n messageId,\n isUser,\n isGenerating,\n}: UseMessageTimerOptions): MessageTimerResult {\n const session = useArbiSessionStore()\n const convId = conversationId || 'new'\n const timerKey = `${convId}:${messageId}`\n\n const
|
|
5
|
-
"mappings": "AAMA,SAAS,WAAW,QAAQ,gBAAgB;AAC5C,SAAS,qBAAqB,2BAA2B;
|
|
4
|
+
"sourcesContent": ["/**\n * The time an answer has taken: counted on the client while its turn runs (separately from the\n * server's step times), and saved when it stops showing, so a finished answer keeps its time and a\n * re-attached run keeps counting from its real start.\n */\n\nimport { useEffect, useRef, useState } from 'react'\nimport { useArbiSessionState, useArbiSessionStore } from '../session'\n\nexport interface UseMessageTimerOptions {\n conversationId: string | undefined\n messageId: string | undefined\n isUser: boolean\n isGenerating: boolean\n /** Authoritative start for runs observed outside the workspace stream (e.g. personal chat). */\n startTime?: number\n}\n\nexport interface MessageTimerResult {\n /** Seconds. */\n elapsedTime: number\n}\n\nexport function useMessageTimer({\n conversationId,\n messageId,\n isUser,\n isGenerating,\n startTime: observedStartTime,\n}: UseMessageTimerOptions): MessageTimerResult {\n const session = useArbiSessionStore()\n const convId = conversationId || 'new'\n const timerKey = `${convId}:${messageId}`\n\n const streamStartTime = useArbiSessionState((s) => s.generating[convId]?.startTime ?? null)\n const generationStartTime = observedStartTime ?? streamStartTime\n const storedElapsed = useArbiSessionState((s) => s.messageTimers[timerKey]?.elapsedTime)\n\n const [elapsedTime, setElapsedTime] = useState(0)\n // The latest elapsed time, for the cleanup to save without depending on it.\n const lastElapsedRef = useRef(0)\n\n // A finished answer shows its saved time.\n useEffect(() => {\n if (!isUser && !isGenerating && storedElapsed) setElapsedTime(storedElapsed)\n }, [isUser, isGenerating, storedElapsed])\n\n // Count while the turn runs. The cleanup saves the final time through the store's current state,\n // so the saved timer is not a dependency (saving would re-run the effect, which saves again...).\n useEffect(() => {\n if (isUser || !isGenerating || !generationStartTime) return\n const startTime = generationStartTime\n const key = timerKey\n const interval = setInterval(() => {\n const elapsed = (Date.now() - startTime) / 1000\n lastElapsedRef.current = elapsed\n setElapsedTime(elapsed)\n }, 100)\n return () => {\n clearInterval(interval)\n const finalElapsed = lastElapsedRef.current || (Date.now() - startTime) / 1000\n session.setMessageTimer(key, { startTime, elapsedTime: finalElapsed })\n }\n }, [isUser, isGenerating, generationStartTime, timerKey, session])\n\n return { elapsedTime }\n}\n"],
|
|
5
|
+
"mappings": "AAMA,SAAS,WAAW,QAAQ,gBAAgB;AAC5C,SAAS,qBAAqB,2BAA2B;AAgBlD,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AACb,GAA+C;AAC7C,QAAM,UAAU,oBAAoB;AACpC,QAAM,SAAS,kBAAkB;AACjC,QAAM,WAAW,GAAG,MAAM,IAAI,SAAS;AAEvC,QAAM,kBAAkB,oBAAoB,CAAC,MAAM,EAAE,WAAW,MAAM,GAAG,aAAa,IAAI;AAC1F,QAAM,sBAAsB,qBAAqB;AACjD,QAAM,gBAAgB,oBAAoB,CAAC,MAAM,EAAE,cAAc,QAAQ,GAAG,WAAW;AAEvF,QAAM,CAAC,aAAa,cAAc,IAAI,SAAS,CAAC;AAEhD,QAAM,iBAAiB,OAAO,CAAC;AAG/B,YAAU,MAAM;AACd,QAAI,CAAC,UAAU,CAAC,gBAAgB,cAAe,gBAAe,aAAa;AAAA,EAC7E,GAAG,CAAC,QAAQ,cAAc,aAAa,CAAC;AAIxC,YAAU,MAAM;AACd,QAAI,UAAU,CAAC,gBAAgB,CAAC,oBAAqB;AACrD,UAAM,YAAY;AAClB,UAAM,MAAM;AACZ,UAAM,WAAW,YAAY,MAAM;AACjC,YAAM,WAAW,KAAK,IAAI,IAAI,aAAa;AAC3C,qBAAe,UAAU;AACzB,qBAAe,OAAO;AAAA,IACxB,GAAG,GAAG;AACN,WAAO,MAAM;AACX,oBAAc,QAAQ;AACtB,YAAM,eAAe,eAAe,YAAY,KAAK,IAAI,IAAI,aAAa;AAC1E,cAAQ,gBAAgB,KAAK,EAAE,WAAW,aAAa,aAAa,CAAC;AAAA,IACvE;AAAA,EACF,GAAG,CAAC,QAAQ,cAAc,qBAAqB,UAAU,OAAO,CAAC;AAEjE,SAAO,EAAE,YAAY;AACvB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -464,7 +464,8 @@ var EntityPill = React.forwardRef(function EntityPill2({
|
|
|
464
464
|
{
|
|
465
465
|
className: chunkS6A6FSG7_cjs.cn(
|
|
466
466
|
textSizeClass,
|
|
467
|
-
"font-medium tracking-[0.01em] truncate leading-tight min-w-0
|
|
467
|
+
"font-medium tracking-[0.01em] truncate leading-tight min-w-0 decoration-dotted decoration-current/35 underline-offset-4",
|
|
468
|
+
!disabled && (onClick || href) && "group-hover/pill:underline group-focus-visible/pill:underline",
|
|
468
469
|
labelMaxWidth,
|
|
469
470
|
labelClassName
|
|
470
471
|
),
|
|
@@ -2914,46 +2915,34 @@ function ProjectEntity({
|
|
|
2914
2915
|
}
|
|
2915
2916
|
);
|
|
2916
2917
|
}
|
|
2917
|
-
var ArbiBotHeadIcon = ({ size = 24, className = "" }) =>
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
"svg",
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
}
|
|
2946
|
-
),
|
|
2947
|
-
/* @__PURE__ */ jsxRuntime.jsxs("g", { transform: "translate(0,250) scale(0.1,-0.1)", fill: "currentColor", stroke: "none", children: [
|
|
2948
|
-
/* @__PURE__ */ jsxRuntime.jsx("path", { d: "M785 1777 c-60 -60 -59 -134 1 -186 92 -82 236 9 204 128 -25 93 -138 125 -205 58z m161 -29 c7 -22 -19 -52 -40 -45 -21 7 -30 35 -17 51 19 23 48 20 57 -6z" }),
|
|
2949
|
-
/* @__PURE__ */ jsxRuntime.jsx("path", { d: "M1591 1803 c-128 -67 -85 -243 60 -243 83 0 141 99 105 178 -32 69 -103 97 -165 65z m127 -59 c4 -25 -19 -47 -41 -38 -22 8 -30 34 -16 51 17 20 53 12 57 -13z" }),
|
|
2950
|
-
/* @__PURE__ */ jsxRuntime.jsx("path", { d: "M843 1347 c-9 -15 9 -63 41 -108 148 -202 565 -209 730 -12 37 44 60 103 47 116 -13 13 -810 17 -818 4z" })
|
|
2951
|
-
] })
|
|
2952
|
-
] })
|
|
2953
|
-
]
|
|
2954
|
-
}
|
|
2955
|
-
);
|
|
2956
|
-
};
|
|
2918
|
+
var ArbiBotHeadIcon = ({ size = 24, className = "" }) => /* @__PURE__ */ jsxRuntime.jsxs(
|
|
2919
|
+
"svg",
|
|
2920
|
+
{
|
|
2921
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
2922
|
+
width: size,
|
|
2923
|
+
height: size,
|
|
2924
|
+
viewBox: "0 0 32 32",
|
|
2925
|
+
fill: "none",
|
|
2926
|
+
stroke: "currentColor",
|
|
2927
|
+
strokeWidth: "2.5",
|
|
2928
|
+
strokeLinecap: "round",
|
|
2929
|
+
strokeLinejoin: "round",
|
|
2930
|
+
"aria-hidden": "true",
|
|
2931
|
+
focusable: "false",
|
|
2932
|
+
className,
|
|
2933
|
+
children: [
|
|
2934
|
+
/* @__PURE__ */ jsxRuntime.jsx("path", { d: "M4.5 14C4.5 7.65 9.65 4 16 4s11.5 3.65 11.5 10v4c0 6-5.15 10-11.5 10S4.5 24 4.5 18Z" }),
|
|
2935
|
+
/* @__PURE__ */ jsxRuntime.jsx("path", { d: "M4.5 13h2m19 0h2m-13 1h3" }),
|
|
2936
|
+
/* @__PURE__ */ jsxRuntime.jsx("rect", { x: "6.5", y: "10.5", width: "8", height: "7", rx: "3.5" }),
|
|
2937
|
+
/* @__PURE__ */ jsxRuntime.jsx("rect", { x: "17.5", y: "10.5", width: "8", height: "7", rx: "3.5" }),
|
|
2938
|
+
/* @__PURE__ */ jsxRuntime.jsxs("g", { fill: "currentColor", stroke: "none", children: [
|
|
2939
|
+
/* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "10.5", cy: "14", r: "1.25" }),
|
|
2940
|
+
/* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "21.5", cy: "14", r: "1.25" })
|
|
2941
|
+
] }),
|
|
2942
|
+
/* @__PURE__ */ jsxRuntime.jsx("path", { d: "M11.5 21.5c2.5 2 6.5 2 9 0" })
|
|
2943
|
+
]
|
|
2944
|
+
}
|
|
2945
|
+
);
|
|
2957
2946
|
function VerifiedBadge({ className, label = "Identity verified" }) {
|
|
2958
2947
|
return /* @__PURE__ */ jsxRuntime.jsx(
|
|
2959
2948
|
lucideReact.BadgeCheck,
|
|
@@ -3131,14 +3120,23 @@ var UserEntity = React.memo(function UserEntity2({
|
|
|
3131
3120
|
}
|
|
3132
3121
|
) });
|
|
3133
3122
|
if (variant === "pill") {
|
|
3123
|
+
const clickable = interactive && !!onClick;
|
|
3134
3124
|
const row = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
3135
3125
|
pillAvatar,
|
|
3136
|
-
displayName && /* @__PURE__ */ jsxRuntime.jsx(
|
|
3126
|
+
displayName && /* @__PURE__ */ jsxRuntime.jsx(
|
|
3127
|
+
"span",
|
|
3128
|
+
{
|
|
3129
|
+
className: chunkS6A6FSG7_cjs.cn(
|
|
3130
|
+
"min-w-0 max-w-[320px] truncate text-sm font-medium tracking-[0.01em] decoration-dotted decoration-current/35 underline-offset-4 leading-tight",
|
|
3131
|
+
clickable && "group-hover/pill:underline group-focus-visible/pill:underline"
|
|
3132
|
+
),
|
|
3133
|
+
children: displayName
|
|
3134
|
+
}
|
|
3135
|
+
),
|
|
3137
3136
|
isVerified && !isAgent2 && /* @__PURE__ */ jsxRuntime.jsx(VerifiedBadge, {}),
|
|
3138
3137
|
agentBadge
|
|
3139
3138
|
] });
|
|
3140
3139
|
const rowClass = "group/pill inline-flex min-w-0 items-center gap-2";
|
|
3141
|
-
const clickable = interactive && !!onClick;
|
|
3142
3140
|
const clickableClass = "relative cursor-pointer rounded-md px-1 py-0.5 -mx-1 transition-colors pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-3 pointer-coarse:after:content-['']";
|
|
3143
3141
|
if (resolvedTooltip) {
|
|
3144
3142
|
return /* @__PURE__ */ jsxRuntime.jsxs(Tooltip, { children: [
|
|
@@ -5443,5 +5441,5 @@ exports.toggleVariants = toggleVariants;
|
|
|
5443
5441
|
exports.useAudioRecorder = useAudioRecorder;
|
|
5444
5442
|
exports.useDictateContext = useDictateContext;
|
|
5445
5443
|
exports.usesOriginalBytesForViewer = usesOriginalBytesForViewer;
|
|
5446
|
-
//# sourceMappingURL=chunk-
|
|
5447
|
-
//# sourceMappingURL=chunk-
|
|
5444
|
+
//# sourceMappingURL=chunk-UR5F4DNJ.cjs.map
|
|
5445
|
+
//# sourceMappingURL=chunk-UR5F4DNJ.cjs.map
|