All files / src/components/chat/ModelChat ModelChatView.tsx

68.68% Statements 136/198
55.27% Branches 89/161
60.97% Functions 25/41
72.06% Lines 129/179

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554                                                                                                4x             28x 28x 28x 28x 28x   28x 28x           28x       28x 28x 28x 7x 7x     28x           28x     8x 8x         28x     11x                 28x   8x     28x 4x 4x     4x   4x   10x                   10x 5x       5x 5x 5x               5x       5x 5x                   5x 5x               5x 5x   5x   5x   4x               28x 28x 28x 28x 28x                     28x 16x     28x 16x   1x 1x         28x 16x         28x       28x 1x             28x   28x 16x                 28x 8x 20x 3x                   17x 5x 1x 1x 1x   1x     17x           17x 5x                 5x 5x 4x   1x 1x         17x                     17x                       17x             17x         3x   3x     3x           3x 3x           3x     3x 3x     3x 3x 6x   3x 3x     3x 3x 3x   3x                             3x 1x 1x   2x             3x 3x                       2x             3x                         3x                                                             3x 3x 3x 3x 3x 3x     3x               17x 1x 1x 1x 1x 1x     1x             17x   17x         17x             22x                       22x                                                                                        
import ChatPanel, {
  ChatSettings,
  UploadedFileRef,
} from "@/components/chat/ChatPanel/ChatPanel";
import ChatLayout, { type ChatFrame } from "@/components/chat/ChatLayout/ChatLayout";
import {
  ChatViewFrame,
  ChatViewStatus,
} from "@/components/chat/ChatView/ChatViewFrame";
import ConversationSidebar from "@/components/chat/ConversationSidebar/ConversationSidebar";
import {
  AttachmentRef,
  ChatMessage,
  Conversation,
  modelDisplayName,
} from "@/objects/Model";
import type { RunningTurn } from "@/objects/Turn";
import { runningTurnsKey, useRunningTurns } from "@/hooks/useRunningTurns";
import { QUERY_KEYS } from "@/services/query_keys";
import { messageAttachments, uploadAndRead } from "@/util/chatAttachments";
import { newId } from "@/util/newId";
import {
  pendingConversation,
  turnMessage,
  turnStatusMessage,
} from "@/util/runningTurns";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Brain } from "lucide-react";
import React, { useEffect, useMemo, useRef, useState } from "react";
 
export interface ModelChatViewProps {
  /** The model, decoded; null when the route named none it could read. */
  modelId: string | null;
  /** On its own page (the chat route), or in the chat dock. */
  frame?: ChatFrame;
  /** A `?conversation=<id>&message=<id>` deep link: opens that turn. */
  linkedConversationId?: string | null;
  linkedMessageId?: string | null;
  /** Put the caret in the message box once the chat is drawn (the dock). */
  autoFocus?: boolean;
}
 
/**
 * Chat with one model directly, no agent: its conversations beside the
 * thread, each turn one request. The model chat page draws it, and so does
 * the chat dock, open over any page.
 */
const ModelChatView: React.FC<ModelChatViewProps> = ({
  modelId,
  frame = "page",
  linkedConversationId = null,
  linkedMessageId = null,
  autoFocus = false,
}) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const [conversationId, setConversationId] = useState<string | null>(null);
  const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
  const [loading, setLoading] = useState(false);
  // The id this page gave the turn it is waiting on: what its Stop names.
  const turnIdRef = useRef<string | null>(null);
  const [stopping, setStopping] = useState(false);
  // The conversation the awaited turn belongs to (null for a new chat until
  // the running turns name it), and the thread as it was when the person
  // looked at another conversation — its answer is still written and
  // stored, but drawn only in its own conversation, never appended to the
  // one on screen.
  const pendingRef = useRef<{
    conversationId: string | null;
    history: ChatMessage[] | null;
  } | null>(null);
  const [pendingShown, setPendingShown] = useState(true);
  const pendingShownRef = useRef(true);
  const showPending = (shown: boolean) => {
    pendingShownRef.current = shown;
    setPendingShown(shown);
  };
 
  const decodedModelId = modelId ?? "";
 
  const {
    data: model,
    error,
    isLoading,
  } = useQuery({
    queryKey: [QUERY_KEYS.GET.MODEL_BY_ID, decodedModelId],
    queryFn: async () => {
      Iif (!decodedModelId) return null;
      return getApiHandler().model_router.id(decodedModelId);
    },
    enabled: !!decodedModelId,
  });
 
  const { data: conversations = [] } = useQuery({
    queryKey: [QUERY_KEYS.GET.CONVERSATIONS, "model", decodedModelId],
    queryFn: async () => {
      return (
        (await getApiHandler().conversation_router.list({
          modelId: decodedModelId,
        })) ?? []
      );
    },
    enabled: !!decodedModelId,
  });
 
  const { data: documents = [] } = useQuery({
    queryKey: [QUERY_KEYS.GET.UPLOADED_FILES],
    queryFn: () => getApiHandler().file_router.listFiles(),
  });
 
  const handleSelectConversation = (conv: Conversation) => {
    setConversationId(conv.id);
    const filtered: ChatMessage[] = [];
    // Old format: system messages with "[Attached file:]" immediately precede
    // their user turn.  Queue them here until the next user message consumes them.
    const pendingAttachments: { name: string }[] = [];
 
    for (const m of conv.messages) {
      // ── Old format: standalone file system message ─────────────────────────
      Iif (m.role === "system" && m.content.startsWith("[Attached file:")) {
        // Extract every filename in this system message (one system msg per file)
        const re = /\[Attached file: (.+?)\]/g;
        let hit: RegExpExecArray | null;
        while ((hit = re.exec(m.content)) !== null) {
          pendingAttachments.push({ name: hit[1] });
        }
        continue; // never show raw file system messages in the chat
      }
 
      if (m.role === "user") {
        const { displayContent, attachments: embedded } = messageAttachments(
          m.content,
          m.meta,
        );
        const allAttachments = [...pendingAttachments, ...embedded];
        pendingAttachments.length = 0;
        filtered.push({
          // Kept so a `?message=` deep link can resolve to this bubble.
          id: m.id,
          role: "user",
          content: displayContent,
          sent_at: m.sent_at,
          ...(allAttachments.length > 0 ? { attachments: allAttachments } : {}),
        });
        continue;
      }
 
      // ── Assistant / non-file system messages ──────────────────────────────
      pendingAttachments.length = 0; // discard any orphaned pending attachments
      const msg: ChatMessage = {
        id: m.id,
        invocation_id: m.invocation_id,
        verdict: m.verdict,
        cost_usd: m.cost_usd,
        unpriced_calls: m.unpriced_calls,
        role: m.role,
        content: m.content,
        sent_at: m.sent_at,
      };
      Eif (m.role === "assistant") {
        Iif (m.meta) {
          msg.meta = {
            token_count: m.meta.token_count ?? m.token_count,
            temperature: m.meta.temperature,
            output_format: m.meta.output_format,
            output_schema: m.meta.output_schema,
            withheld: m.meta.withheld,
          };
        } else Eif (m.token_count > 0) {
          msg.meta = { token_count: m.token_count };
        }
        Iif (m.trace?.length) msg.trace = m.trace;
      }
      filtered.push(msg);
    }
    setChatHistory(filtered);
  };
 
  // ── Turns still running (svc-core app/services/turns.py) ──
  // A turn runs to its end whether or not this page is open: one may be
  // under way that this page did not start. It is drawn in place of the
  // answer until it is stored; then the conversation holds the answer.
  // Waiting on the conversation on screen — not one looked away from.
  const waitingHere = loading && pendingShown;
  const viewing = useRef({ conversationId, loading: waitingHere });
  viewing.current = { conversationId, loading: waitingHere };
  const conversationsKey = [QUERY_KEYS.GET.CONVERSATIONS, "model", decodedModelId];
  const runningTurns = useRunningTurns({ modelId: decodedModelId }, (turn) => {
    void (async () => {
      await queryClient.refetchQueries({ queryKey: conversationsKey });
      const { conversationId: open, loading: busy } = viewing.current;
      if (busy || open !== turn.conversation_id) return;
      const stored = (
        queryClient.getQueryData(conversationsKey) as Conversation[] | undefined
      )?.find((c) => c.id === turn.conversation_id);
      if (stored) handleSelectConversation(stored);
    })();
  });
  const storedIds = useMemo(
    () => new Set((conversations as Conversation[]).map((c) => c.id)),
    [conversations],
  );
  const sidebarConversations = useMemo(
    () => [
      ...runningTurns
        .filter((t) => !storedIds.has(t.conversation_id))
        .map((t) => pendingConversation(t, messageAttachments)),
      ...(conversations as Conversation[]),
    ],
    [runningTurns, conversations, storedIds],
  );
  const answering = useMemo(
    () => new Set(runningTurns.map((t) => t.conversation_id)),
    [runningTurns],
  );
  // A new chat's awaited turn is named by the id this page gave it.
  const pendingConversationId =
    pendingRef.current?.conversationId ??
    runningTurns.find((t) => t.id === turnIdRef.current)?.conversation_id ??
    null;
  const watchedTurn =
    !waitingHere && conversationId && conversationId !== pendingConversationId
      ? runningTurns.find((t) => t.conversation_id === conversationId)
      : undefined;
 
  // `?conversation=<id>&message=<id>` opens a specific turn — the same deep
  // link the agent chat takes, so Activity and Governance → Rules → Activity
  // can point at a direct model prompt the same way they point at an agent
  // turn.
  const deepLinkApplied = useRef(false);
 
  useEffect(() => {
    Eif (deepLinkApplied.current || !linkedConversationId) return;
    const target = (conversations as Conversation[]).find(
      (c) => c.id === linkedConversationId,
    );
    if (!target) return;
    deepLinkApplied.current = true;
    handleSelectConversation(target);
  }, [conversations, linkedConversationId]);
 
  if (isLoading)
    return <ChatViewStatus frame={frame} state="loading" noun="model" />;
  if (error || !model)
    return (
      <ChatViewStatus
        frame={frame}
        state="error"
        message={error ? error.toString() : "Could not find model."}
      />
    );
 
  /** Look away from the conversation awaiting an answer: the turn runs on,
   *  and the thread as shown is kept to draw again on the way back. */
  const leavePending = () => {
    if (!loading || !pendingShownRef.current || !pendingRef.current) return;
    pendingRef.current.history = chatHistory;
    pendingRef.current.conversationId = pendingConversationId;
    showPending(false);
    // So the sidebar marks it answering now, not at the next poll.
    void queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.RUNNING_TURNS] });
  };
 
  const handleNewConversation = () => {
    leavePending();
    setConversationId(null);
    setChatHistory([]);
  };
 
  const selectConversation = (conv: Conversation) => {
    Iif (loading && pendingRef.current && pendingConversationId === conv.id) {
      // Back to the conversation awaiting its answer: drawn as it was left.
      if (!pendingShownRef.current) {
        setConversationId(conv.id);
        setChatHistory(pendingRef.current.history ?? []);
        showPending(true);
      }
      return;
    }
    leavePending();
    if (storedIds.has(conv.id)) {
      handleSelectConversation(conv);
    } else {
      setConversationId(conv.id);
      setChatHistory([]);
    }
  };
 
  /** Stop a turn this page did not start. */
  const stopTurn = async (turn: RunningTurn) => {
    const key = runningTurnsKey({ modelId: decodedModelId });
    queryClient.setQueryData(key, (prev: RunningTurn[] | undefined) =>
      prev?.map((t) => (t.id === turn.id ? { ...t, stopping: true } : t)),
    );
    await getApiHandler().turn_router.stop(turn.id);
    void queryClient.invalidateQueries({ queryKey: key });
  };
 
  // Settles once the text is read (or could not be), so the chip spins
  // and Send waits until then.
  const handleUploadFile = async (
    file: File,
  ): Promise<UploadedFileRef | null> => {
    try {
      return await uploadAndRead(getApiHandler().file_router, file);
    } finally {
      void queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.UPLOADED_FILES],
      });
    }
  };
 
  const handleDeleteDocument = async (id: string) => {
    await getApiHandler().file_router.deleteFile(id);
    void queryClient.invalidateQueries({
      queryKey: [QUERY_KEYS.GET.UPLOADED_FILES],
    });
  };
 
  const handleSubmit = async (
    prompt: string,
    attachedFiles: UploadedFileRef[],
    settings: ChatSettings,
  ) => {
    const userMessage = prompt.trim();
    // Documents sent without a word are a request too (svc-core runs it).
    Iif (!userMessage && attachedFiles.length === 0) return;
 
    // As the server will keep them: by id, so each chip opens its document.
    const attachments: AttachmentRef[] = attachedFiles.map((f: UploadedFileRef) => ({
      id: f.id,
      name: f.name,
      ...(f.mime_type ? { mime_type: f.mime_type } : {}),
    }));
 
    const userSentAt = new Date().toISOString();
    setChatHistory((prev) => [
      ...(settings.systemPrompt
        ? [...prev, { role: "system" as const, content: settings.systemPrompt }]
        : prev),
      { role: "user", content: userMessage, attachments, sent_at: userSentAt },
    ]);
    setLoading(true);
    // Named by this page, so its Stop can reach the turn before the
    // response says anything (svc-core POST /app/turns/{id}/stop).
    const turnId = newId();
    turnIdRef.current = turnId;
    // A turn still awaited in a conversation looked away from goes on
    // without this page; only this one's answer is drawn from here.
    pendingRef.current = { conversationId, history: null };
    showPending(true);
    const mine = () => turnIdRef.current === turnId;
 
    try {
      const systemMessages = settings.systemPrompt
        ? [settings.systemPrompt]
        : [];
      const { format, schema } = settings.outputFormat;
      const outputFormat = format !== "markdown" ? format : undefined;
      const outputSchema = schema.trim() || undefined;
 
      const res = await getApiHandler().model_router.prompt(
        decodedModelId,
        userMessage,
        conversationId,
        systemMessages,
        attachedFiles.map((f: UploadedFileRef) => f.id), // file_ids
        settings.temperature, // temperature
        undefined, // signal: leaving or stopping never cancels the request
        outputFormat, // output_format
        outputSchema, // output_schema
        turnId, // turn_id
      );
 
      // Not this page's turn any more (another was sent), or looked away
      // from: the answer is stored, and drawn when its conversation opens.
      if (!mine() || !pendingShownRef.current) {
        void queryClient.invalidateQueries({ queryKey: conversationsKey });
        return;
      }
      setConversationId(res?.conversation_id ?? null);
 
      // Wrap structured responses in a code fence for display since the model
      // returns raw text without fences when instructed via output_format.
      // A stopped turn's text is shown as it is stored, unfenced: it is
      // what was written so far, not the format asked for — as is a
      // withheld answer's, which is the rule's message.
      let responseContent = res?.response ?? "No response.";
      Iif (
        outputFormat &&
        outputFormat !== "plain" &&
        !res?.stopped &&
        !res?.withheld
      ) {
        const trimmed = responseContent.trim();
        if (!trimmed.startsWith("```")) {
          responseContent = `\`\`\`${outputFormat}\n${trimmed}\n\`\`\``;
        }
      }
 
      const assistantMeta: ChatMessage["meta"] = {
        temperature: settings.temperature,
        ...(outputFormat ? { output_format: outputFormat } : {}),
        ...(outputSchema ? { output_schema: outputSchema } : {}),
        ...(res?.output_tokens ? { token_count: res.output_tokens } : {}),
        ...(res?.withheld ? { withheld: res.withheld } : {}),
      };
      setChatHistory((prev) => [
        ...prev,
        {
          role: "assistant",
          invocation_id: res?.invocation_id ?? null,
          cost_usd: res?.cost_usd,
          unpriced_calls: res?.unpriced_calls,
          content: responseContent,
          sent_at: new Date().toISOString(),
          meta: assistantMeta,
          ...(res?.trace?.length ? { trace: res.trace } : {}),
        },
      ]);
      void queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.CONVERSATIONS, "model", decodedModelId],
      });
    } catch (err) {
      if (!mine() || !pendingShownRef.current) {
        void queryClient.invalidateQueries({ queryKey: conversationsKey });
        return;
      }
      console.error(err);
      // A 403 with a structured detail means a policy rule blocked the
      // request — show the rule's block message, not a generic error. A
      // string detail is written to be shown: what to fix (a 502), or that
      // the conversation is still answering an earlier message (a 409).
      const detail = (err as { response?: { data?: { detail?: unknown } } })
        .response?.data?.detail;
      const block =
        detail && typeof detail === "object" && "message" in detail
          ? (detail as { rule?: string; message?: string })
          : null;
      setChatHistory((prev) => [
        ...prev,
        {
          role: "assistant",
          content: block?.message
            ? `🚫 ${block.message}${block.rule ? `\n\n*Blocked by rule "${block.rule}"*` : ""}`
            : typeof detail === "string" && detail
              ? detail
              : "Error fetching response.",
        },
      ]);
    } finally {
      Eif (mine()) {
        turnIdRef.current = null;
        pendingRef.current = null;
        showPending(true);
        setStopping(false);
        setLoading(false);
      }
      // Stored, so no longer running: a list read during it is stale.
      void queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.RUNNING_TURNS],
      });
    }
  };
 
  /** Stop the turn this page is waiting on. svc-ai's run ends, and the
   *  request returns with what the turn had written, as it is stored. */
  const handleStop = () => {
    const turnId = turnIdRef.current;
    Iif (!turnId) return;
    setStopping(true);
    void (async () => {
      const api = getApiHandler().turn_router;
      // A Stop pressed the instant the message went may arrive before the
      // turn is registered: asked once more, shortly after.
      Iif (!(await api.stop(turnId)) && turnIdRef.current === turnId) {
        await new Promise((resolve) => setTimeout(resolve, 500));
        if (turnIdRef.current === turnId) await api.stop(turnId);
      }
    })();
  };
 
  const name = modelDisplayName(model);
  const titleIcon = (
    <div className="w-8 h-8 rounded-lg bg-indigo-100 dark:bg-indigo-900/40 border border-indigo-200 dark:border-indigo-800 flex items-center justify-center shrink-0">
      <Brain className="w-4 h-4 text-indigo-500" />
    </div>
  );
 
  return (
    <ChatViewFrame frame={frame} title={name} icon={titleIcon}>
      <ChatLayout
        title={name}
        icon={titleIcon}
        frame={frame}
        sidebar={(fill, stacked) => (
          <ConversationSidebar
            conversations={sidebarConversations}
            selectedId={conversationId}
            onSelect={selectConversation}
            onNew={handleNewConversation}
            fill={fill}
            stacked={stacked}
            answering={answering}
          />
        )}
      >
        {(fill) => (
          <ChatPanel
            messages={
              watchedTurn
                ? [
                    ...chatHistory,
                    turnMessage(watchedTurn, messageAttachments),
                  ]
                : chatHistory
            }
            displayName={name}
            // Only the conversation awaiting the answer shows it coming.
            loading={waitingHere || !!watchedTurn}
            statusMessage={
              watchedTurn
                ? turnStatusMessage(watchedTurn)
                : waitingHere && stopping
                  ? "Stopping…"
                  : undefined
            }
            conversationId={conversationId}
            highlightMessageId={
              conversationId === linkedConversationId ? linkedMessageId : null
            }
            onSubmit={handleSubmit}
            onStop={watchedTurn ? () => void stopTurn(watchedTurn) : handleStop}
            onUploadFile={handleUploadFile}
            documents={documents}
            onDeleteDocument={(id) => {
              void handleDeleteDocument(id);
            }}
            supportsTemperature
            supportsThinking={model.is_chat}
            supportsSystemPrompt
            placeholder={`Message ${name}…`}
            fill={fill}
            autoFocus={autoFocus}
          />
        )}
      </ChatLayout>
    </ChatViewFrame>
  );
};
 
export default ModelChatView;