All files / src/components/chat/AgentChat AgentChatView.tsx

70.08% Statements 321/458
60.5% Branches 216/357
67.1% Functions 51/76
71.7% Lines 299/417

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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360                                                                                                                                                                                                                                                                                                                                                  30x 30x 30x                         2x           17x 17x     17x                                       9x             189x 189x 189x 189x 189x 189x 189x     189x 189x 189x 189x     189x     189x       189x   44x   44x 44x                     189x       189x 189x 189x 29x 29x   189x 189x       189x 189x     189x         189x 189x     189x       189x   189x         189x           189x           189x     44x 44x           189x     54x                 189x   44x     189x   44x   189x       189x   44x     189x   189x 35x 35x 35x   35x   94x                 94x 47x       47x 47x 47x 47x                     47x       47x       47x       94x                           94x 47x 8x                           39x 39x   47x             47x   47x   47x   35x                   189x 189x 189x 189x 189x 1x 1x 1x 1x   1x 1x 1x     189x 101x       189x 102x   3x 2x         189x 89x           189x     3x                       189x   189x 101x     12x 9x   12x 6x 6x     189x 56x 133x 3x                   130x 30x 2x 2x   2x     130x           130x 31x 31x       1x 1x 1x 1x   1x   30x 30x 28x     2x 2x           130x 1x 1x 1x   1x 1x         130x                       130x             130x           17x   17x     17x                 17x   17x   17x                                             17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x   17x 17x 17x   17x   17x   17x 17x 17x   17x 17x                                         17x 17x       47x   17x 30x 30x 30x 30x   30x 10x 10x       10x 20x             20x 1x 1x             1x                       19x                                                                         19x                         19x                                                                             19x                                   19x                           19x 1x 1x 1x 18x 4x 4x 4x 4x 4x 4x 2x 2x 2x               14x 1x 1x 1x 1x 1x 1x 1x     13x 4x 4x 9x 8x     8x 8x   8x 8x 8x 8x 8x 8x   8x   8x             8x                           8x 4x     8x                                           8x 8x 8x 8x 8x 8x       8x     8x 1x                                                             1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                       1x 1x 1x 1x 1x       1x       1x     1x             17x                                       17x 17x 17x 17x                               130x 1x 1x 1x 1x     1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                 130x                           130x                 130x                                   130x                 189x         189x             171x                         171x                   39x                                                                                       1x                                                                                                                                                                                                        
import AgentChatToolbar from "@/components/chat/AgentChat/AgentChatToolbar";
import { useWorkspace } from "@/context/WorkspaceContext";
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 ClarifyForm from "@/components/chat/ClarifyForm/ClarifyForm";
import {
  ClarifyAnswers,
  ClarifyQuestion,
  ClarifyRequest,
  ClarifySource,
} from "@/objects/Hitl";
import { attachHitl, withNodeResult } from "@/util/traceUtils";
import { runningTurnsKey, useRunningTurns } from "@/hooks/useRunningTurns";
import type { RunningTurn } from "@/objects/Turn";
import type { SearchReport, WebSearchSummary } from "@/objects/WebSearch";
import {
  pendingConversation,
  turnMessage,
  turnStatusMessage,
} from "@/util/runningTurns";
import {
  type CommandSubmission,
  commandOf,
  commandRecord,
  describeCommandError,
  matchCommand,
} from "@/util/chatCommands";
import BuiltInBadge from "@/components/badge/BuiltInBadge";
import { isSystemManaged } from "@/objects/Doc";
import {
  AttachmentRef,
  ChatMessage,
  Citation,
  Conversation,
  GraphPlanStage,
  MessageSegment,
  Model,
  NodeExecution,
  QualityOutcome,
  SystemNodeResult,
  TraceEvent,
  WithheldAnswer,
  selectableModels,
} from "@/objects/Model";
import { messageAttachments, uploadAndRead } from "@/util/chatAttachments";
import { nextCitations, storedCitations } from "@/util/citations";
import { resetTarget } from "@/util/tokenReset";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Bot } from "lucide-react";
import React, { useEffect, useMemo, useRef, useState } from "react";
 
type WebSocketMessage =
  /** Sent first: the conversation the turn is stored under β€” for a new chat,
   *  minted by svc-core before any answer exists. */
  | { type: "turn"; conversation_id: string; turn_id?: string }
  | { type: "status"; message: string }
  | { type: "token"; token: string; worker_agent_slug?: string }
  | { type: "worker_token"; worker_agent_slug: string; token: string }
  /** What the node has streamed since it started, or was last reset, was
   *  not answer β€” a model's account of what it was about to do beside a
   *  tool call β€” so its preview starts again. */
  | { type: "token_reset"; worker_agent_slug?: string }
  /** `final`: the answer's own sources, which replace what was streamed as
   *  it was retrieved (svc-ai `cited_citations`). */
  | { type: "citations"; citations: Citation[]; final?: boolean }
  | {
      type: "response";
      conversation_id: string | null;
      /** The stored assistant message β€” see `_persist` in svc-core. */
      message_id?: string | null;
      /** The turn's id: what "Why did it do this?" opens. */
      invocation_id?: string | null;
      /** What the quality check concluded, as stored on the answer. */
      eval_outcome?: QualityOutcome | null;
      eval_score?: number | null;
      /** What the turn cost, read back from the usage ledger. */
      cost_usd?: number | null;
      unpriced_calls?: number;
      /** An Output rule withheld the answer: `response` is its message. */
      withheld?: WithheldAnswer;
      /** What the turn's web searches came to (`meta.web_search`). */
      web_search?: WebSearchSummary;
      response: string;
      segments: MessageSegment[];
      model_name?: string;
      provider?: string;
    }
  | {
      type: "error";
      message: string;
      rule?: string;
      conversation_id?: string;
      /** "command" when a chat command could not run; ``suggestions`` are
       *  the command lines the server thinks were meant, and ``fields`` what
       *  it said about each form value it refused. */
      code?: string;
      suggestions?: string[];
      fields?: Record<string, string> | null;
    }
  | { type: "graph_plan"; stages: GraphPlanStage[] }
  | {
      type: "node_start";
      node_id: string;
      is_system_node?: boolean;
      /** Ms from the stream's start, and the graph pass it starts on. */
      t_ms?: number;
      pass?: number;
    }
  | {
      type: "node_end";
      node_id: string;
      is_system_node?: boolean;
      output_preview?: string;
      tokens?: { input: number; output: number };
      duration_ms?: number;
      t_ms?: number;
    }
  | {
      type: "tool_call";
      node_id: string;
      tool: string;
      params?: Record<string, unknown>;
      output_preview?: string;
      status?: "success" | "error";
      /** A web search's report (`objects/WebSearch.ts`). */
      report?: SearchReport;
    }
  | {
      type: "system_node_result";
      node_id: string;
      result: SystemNodeResult;
      input?: Record<string, unknown>;
    }
  | {
      type: "hitl_interrupt";
      thread_id: string;
      /** Which kind of pause this is. Absent on older backends β†’ approval. */
      interrupt_type?: "approval_request" | "clarification_request";
      /** approval_request */
      task?: string;
      output?: string;
      /** clarification_request */
      title?: string | null;
      intro?: string | null;
      reason?: string | null;
      source?: ClarifySource;
      questions?: ClarifyQuestion[];
      node_id?: string;
    }
  /** Trace frames: where the run stopped for a person, and how it ended. */
  | (TraceEvent & { type: "hitl_pause" | "hitl_resume" })
  /** svc-core refused an answer; the pause is still open. */
  | {
      type: "hitl_invalid";
      message: string;
      fields?: Record<string, string>;
    };
 
function isWebSocketMessage(data: unknown): data is WebSocketMessage {
  Iif (typeof data !== "object" || data === null) return false;
  const obj = data as Record<string, unknown>;
  return typeof obj.type === "string";
}
 
/**
 * Render a blocked/errored turn's content the same way whether it just came
 * in live over the WS or was reloaded from persisted conversation history β€”
 * so a policy block (or any other failure) looks identical before and after
 * a page refresh instead of showing raw text once it's no longer live.
 */
function formatFailedTurnContent(
  content: string,
  rule: string | undefined,
): string {
  return rule
    ? `🚫 ${content}\n\n*Blocked by rule "${rule}"*`
    : `Error: ${content}`;
}
 
function buildAgentWsUrl(agentId: string): string {
  const appDomain = import.meta.env.VITE_APP_DOMAIN;
  const wsBase = appDomain
    .replace(/^https:\/\//, "wss://")
    .replace(/^http:\/\//, "ws://");
  return `${wsBase}/api/ws/app/agents/${agentId}/prompt/ws`;
}
 
export interface AgentChatViewProps {
  /** The agent, decoded; null when the route named none it could read. */
  agentId: 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 agent: its conversations beside the thread, a turn streamed
 * over a socket per message. The agent chat page draws it, and so does the
 * chat dock, open over any page.
 */
const AgentChatView: React.FC<AgentChatViewProps> = ({
  agentId,
  frame = "page",
  linkedConversationId = null,
  linkedMessageId = null,
  autoFocus = false,
}) => {
  const workspace = useWorkspace();
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const [conversationId, setConversationId] = useState<string | null>(null);
  const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
  const [loading, setLoading] = useState(false);
  const [statusMessage, setStatusMessage] = useState<string | undefined>(
    undefined,
  );
  const [streamingContent, setStreamingContent] = useState<string>("");
  const [pendingCitations, setPendingCitations] = useState<Citation[]>([]);
  const [executionSteps, setExecutionSteps] = useState<string[]>([]);
  const [nodeExecutions, setNodeExecutions] = useState<NodeExecution[]>([]);
  // Stage plan for the run in flight β€” lets the pipeline render every stage
  // before the first node reports in.
  const [graphPlan, setGraphPlan] = useState<GraphPlanStage[] | undefined>(
    undefined,
  );
  const wsRef = useRef<WebSocket | null>(null);
  // Leaving the page closes the socket, not the turn: svc-core finishes it
  // and stores the answer, which the conversation shows on the way back
  // (app/services/chat_socket.py). Only Stop ends a turn early.
  useEffect(
    () => () => {
      const ws = wsRef.current;
      // Let go first, so the closing socket updates nothing on the way out.
      wsRef.current = null;
      ws?.close();
    },
    [],
  );
  // The stream this page is running belongs to one conversation: the one it
  // was sent in, or β€” for a new chat β€” the one svc-core names in its first
  // frame. Looking at another conversation does not stop it (its answer is
  // still written and stored) but stops drawing it there; `history` keeps
  // the thread as it was left, question included, to draw again on the way
  // back. Before this the stream drew in whatever conversation was open, and
  // its answer was appended there.
  const streamRef = useRef<{
    conversationId: string | null;
    history: ChatMessage[] | null;
  } | null>(null);
  const [streamShown, setStreamShown] = useState(true);
  const streamShownRef = useRef(true);
  const showStream = (shown: boolean) => {
    streamShownRef.current = shown;
    setStreamShown(shown);
  };
  const streamingRef = useRef<string>("");
  const citationsCacheRef = useRef<Map<string, Citation[]>>(new Map());
 
  // The toolbar's choices for this chat's turns: a model in place of the
  // agent's (`""` keeps the agent's), and whether to skip its skill graph.
  const [modelOverrideId, setModelOverrideId] = useState<string>("");
  const [disableSkills, setDisableSkills] = useState(false);
 
  // HITL approval state β€” set when the graph pauses for human review.
  const [hitlInterrupt, setHitlInterrupt] = useState<{
    thread_id: string;
    task: string;
    output: string;
  } | null>(null);
  const [hitlShowFeedback, setHitlShowFeedback] = useState(false);
  const [hitlFeedback, setHitlFeedback] = useState("");
 
  // Clarification state β€” set when the agent pauses to ask the user something.
  const [clarify, setClarify] = useState<ClarifyRequest | null>(null);
  // True from sending an answer until svc-core accepts it (hitl_resume) or
  // refuses it (hitl_invalid) β€” the form stays up, disabled, so a refusal
  // does not cost the person what they typed.
  const [clarifySubmitting, setClarifySubmitting] = useState(false);
  // Refusals svc-core sent back for the last answer, keyed by question id.
  const [clarifyErrors, setClarifyErrors] = useState<Record<string, string>>(
    {},
  );
  // The pause last shown, so a refused answer can reopen it. The server
  // keeps the pause open; the form must come back with it.
  const lastPauseRef = useRef<
    | { kind: "clarify"; request: ClarifyRequest }
    | { kind: "approval"; thread_id: string; task: string; output: string }
    | null
  >(null);
 
  const decodedAgentId = agentId ?? "";
 
  const {
    data: agent,
    error,
    isLoading,
  } = useQuery({
    queryKey: [QUERY_KEYS.GET.AGENT_BY_ID, decodedAgentId],
    queryFn: async () => {
      Iif (!decodedAgentId) return null;
      return getApiHandler().agent_router.id(decodedAgentId);
    },
    enabled: !!decodedAgentId,
  });
 
  const { data: conversations = [], isLoading: conversationsLoading } =
    useQuery({
      queryKey: [QUERY_KEYS.GET.CONVERSATIONS, "agent", decodedAgentId],
      queryFn: async () => {
        return (
          (await getApiHandler().conversation_router.list({
            agentId: decodedAgentId,
          })) ?? []
        );
      },
      enabled: !!decodedAgentId,
    });
 
  const { data: documents = [] } = useQuery({
    queryKey: [QUERY_KEYS.GET.UPLOADED_FILES],
    queryFn: () => getApiHandler().file_router.listFiles(),
  });
 
  const { data: allModels = [] } = useQuery<Model[]>({
    queryKey: [QUERY_KEYS.GET.MODELS],
    queryFn: async () => (await getApiHandler().model_router.list()) ?? [],
  });
  const chatModels = selectableModels(allModels, modelOverrideId);
 
  // The chat commands this chat offers here, for the palette; per workspace,
  // since what a command can target is the workspace's.
  const { data: commandCatalogue } = useQuery({
    queryKey: [QUERY_KEYS.GET.AGENT_COMMANDS, decodedAgentId],
    queryFn: () => getApiHandler().agent_router.commands(decodedAgentId),
    enabled: !!decodedAgentId,
  });
  const commands = commandCatalogue?.commands;
 
  const handleSelectConversation = (conv: Conversation) => {
    setConversationId(conv.id);
    const filtered: ChatMessage[] = [];
    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:")) {
        const re = /\[Attached file: (.+?)\]/g;
        let hit: RegExpExecArray | null;
        while ((hit = re.exec(m.content)) !== null) {
          pendingAttachments.push({ name: hit[1] });
        }
        continue;
      }
 
      if (m.role === "user") {
        const { displayContent, attachments: embedded } = messageAttachments(
          m.content,
          m.meta,
        );
        const command = commandOf(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 } : {}),
          // The chat command it ran, drawn from its record (line, form
          // values, request) rather than the composed task it was sent as.
          ...(command ? { meta: { command } } : {}),
        });
        continue;
      }
 
      // ── Assistant / non-file system messages ──────────────────────────────
      pendingAttachments.length = 0;
      // A stopped answer is stored as an error but is not one: it shows as
      // what it had written.
      const isFailedTurn =
        m.role === "assistant" &&
        m.status &&
        m.status !== "completed" &&
        !m.meta?.stopped;
      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: isFailedTurn
          ? formatFailedTurnContent(m.content, m.meta?.rule)
          : m.content,
        status: m.status,
        sent_at: m.sent_at,
        segments: (m.segments as MessageSegment[]) ?? undefined,
      };
      if (m.role === "assistant") {
        if (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,
            rule: m.meta.rule,
            hitl: m.meta.hitl,
            // The quality check's verdict: the answer's badge. Dropped here
            // until October 2026, so no reloaded answer showed one.
            eval_outcome: m.meta.eval_outcome,
            eval_score: m.meta.eval_score,
            withheld: m.meta.withheld,
            web_search: m.meta.web_search,
          };
        } else Eif (m.token_count > 0) {
          msg.meta = { token_count: m.token_count };
        }
        Iif (m.trace?.length) msg.trace = m.trace;
        // The sources the answer cites, as stored with it (svc-core
        // `meta.cited_sources`; `[]` is "cites none"). A turn stored without
        // them falls back to what this session streamed for that same
        // message β€” keyed by its id: keyed by position, a blocked or failed
        // turn (which advances no position) took a later answer's sources.
        const cited =
          storedCitations(m.meta) ??
          (m.id ? citationsCacheRef.current.get(m.id) : undefined);
        if (cited?.length) msg.citations = cited;
      }
      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, so one may be
  // under way that this page did not start: before the person left, or in
  // another window. It is drawn in place of the live stream β€” its message,
  // a status, a Stop that reaches it β€” until it is stored; then the
  // conversation, read again, holds the answer.
  // Streaming the conversation on screen β€” as opposed to one looked away from.
  const streamingHere = loading && streamShown;
  const viewing = useRef({ conversationId, loading: streamingHere });
  viewing.current = { conversationId, loading: streamingHere };
  const conversationsKey = [QUERY_KEYS.GET.CONVERSATIONS, "agent", decodedAgentId];
  const runningTurns = useRunningTurns({ agentId: decodedAgentId }, (turn) => {
    void (async () => {
      await queryClient.refetchQueries({ queryKey: conversationsKey });
      const { conversationId: open, loading: busy } = viewing.current;
      Iif (busy || open !== turn.conversation_id) return;
      const stored = (
        queryClient.getQueryData(conversationsKey) as Conversation[] | undefined
      )?.find((c) => c.id === turn.conversation_id);
      Eif (stored) handleSelectConversation(stored);
    })();
  });
  const storedIds = useMemo(
    () => new Set((conversations as Conversation[]).map((c) => c.id)),
    [conversations],
  );
  // A new chat's turn has no stored conversation yet: listed all the same.
  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],
  );
  // The turn running in the conversation on screen, when this page is not
  // the one streaming it.
  const watchedTurn =
    !streamingHere &&
    conversationId &&
    conversationId !== streamRef.current?.conversationId
      ? runningTurns.find((t) => t.conversation_id === conversationId)
      : undefined;
 
  // ── Deep link ────────────────────────────────────────────────────────────
  //
  // `?conversation=<id>&message=<id>` opens a specific turn. The Activity and
  // Governance β†’ Rules β†’ Activity pages link here rather than to the agent's
  // chat at whatever it happens to be showing: a governance row that says a
  // rule redacted something is only useful if the message it redacted is one
  // click away.
  // Applied once. The conversation list arrives after the first render, and
  // re-applying would drag the reader back every time they clicked away.
  const deepLinkApplied = useRef(false);
 
  useEffect(() => {
    if (deepLinkApplied.current || !linkedConversationId) return;
    // Typed explicitly: this query has no generic, so `conversations` is
    // `any` (see the TS 5.0.2 note in docs/guides/frontend-components.md).
    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="agent" />;
  if (error || !agent)
    return (
      <ChatViewStatus
        frame={frame}
        state="error"
        message={error ? error.toString() : "Could not find agent."}
      />
    );
 
  /** Look away from the conversation being streamed: the turn runs on, and
   *  the thread as shown is kept to draw again on the way back. */
  const leaveStream = () => {
    if (!loading || !streamShownRef.current || !streamRef.current) return;
    streamRef.current.history = chatHistory;
    showStream(false);
    // So the sidebar marks it answering now, not at the next poll.
    void queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.RUNNING_TURNS] });
  };
 
  const handleNewConversation = () => {
    leaveStream();
    setConversationId(null);
    setChatHistory([]);
  };
 
  const selectConversation = (conv: Conversation) => {
    const stream = streamRef.current;
    if (loading && stream && stream.conversationId === conv.id) {
      // The conversation being streamed: drawn as it was left, the stream
      // carrying on where it has got to. Opened again while on screen, it is
      // left alone β€” reading it back would drop the question not yet stored.
      Eif (!streamShownRef.current) {
        setConversationId(conv.id);
        setChatHistory(stream.history ?? []);
        showStream(true);
      }
      return;
    }
    leaveStream();
    if (storedIds.has(conv.id)) {
      handleSelectConversation(conv);
    } else {
      // A turn's new conversation, not stored yet: nothing to show but it.
      setConversationId(conv.id);
      setChatHistory([]);
    }
  };
 
  /** Stop a turn this page did not start β€” through svc-core, which ends
   *  it as its own page's Stop would. */
  const stopTurn = async (turn: RunningTurn) => {
    const key = runningTurnsKey({ agentId: decodedAgentId });
    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,
    sent?: CommandSubmission,
  ) => {
    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) => ({
      id: f.id,
      name: f.name,
      ...(f.mime_type ? { mime_type: f.mime_type } : {}),
    }));
    // The chat command this sends: the panel's token and form, or a line
    // that reached here as text. It shows as what the server will store β€”
    // the command's record (line, form values, request) on the message's
    // meta, drawn in place of its text.
    const typed = sent ? null : matchCommand(userMessage, commands);
    const command: CommandSubmission | null =
      sent ?? (typed ? { entry: typed, inputs: {}, request: typed.request } : null);
 
    setChatHistory((prev) => [
      ...prev,
      {
        role: "user",
        content: command ? command.request || command.entry.line : userMessage,
        attachments,
        sent_at: new Date().toISOString(),
        ...(command
          ? {
              meta: {
                command: commandRecord(
                  command.entry,
                  command.inputs,
                  command.request,
                ),
              },
            }
          : {}),
      },
    ]);
    // A turn still running in a conversation looked away from: it goes on
    // without this page (svc-core stores it; the sidebar marks it answering)
    // and this one streams instead.
    const previous = wsRef.current;
    wsRef.current = null;
    previous?.close();
    streamRef.current = { conversationId, history: null };
    showStream(true);
    setLoading(true);
    setStatusMessage(undefined);
    setStreamingContent("");
    setPendingCitations([]);
    setExecutionSteps([]);
    setNodeExecutions([]);
    setGraphPlan(undefined);
    setClarify(null);
    setHitlInterrupt(null);
 
    const { format, schema } = settings.outputFormat;
    const outputFormat = format !== "markdown" ? format : undefined;
    const outputSchema = schema.trim() || undefined;
 
    const wsUrl = buildAgentWsUrl(decodedAgentId);
 
    streamingRef.current = "";
 
    await new Promise<void>((resolve) => {
      const ws = new WebSocket(wsUrl);
      wsRef.current = ws;
 
      ws.onopen = () => {
        ws.send(
          JSON.stringify({
            prompt: userMessage,
            // A command's form values, beside its line in the prompt; svc-core
            // checks them against the target's run schema.
            ...(command && Object.keys(command.inputs).length
              ? { command_inputs: command.inputs }
              : {}),
            conversation_id: conversationId,
            // The workspace this chat happens in: its rules govern the turn
            // and its ledger counts it (svc-core app/services/workspace.py).
            workspace: workspace.key,
            file_ids: attachedFiles.map((f) => f.id),
            ...(outputFormat ? { output_format: outputFormat } : {}),
            ...(outputSchema ? { output_schema: outputSchema } : {}),
            ...(modelOverrideId ? { model_override_id: modelOverrideId } : {}),
            ...(disableSkills ? { disable_skills: true } : {}),
          }),
        );
      };
 
      let accumulatedCitations: Citation[] = [];
      const accumulatedTrace: TraceEvent[] = [];
 
      // Only the page's current socket may change it: one let go of (sent
      // elsewhere, stopped, the page left) is still closing.
      const mine = () => wsRef.current === ws;
 
      ws.onmessage = (event) => {
        Iif (!mine()) return;
        try {
          const data: unknown = JSON.parse(event.data as string);
          Iif (!isWebSocketMessage(data)) return;
 
          if (data.type === "turn") {
            Eif (streamRef.current) {
              streamRef.current.conversationId = data.conversation_id;
            }
            // A new chat has its id from now: the sidebar lists it, and
            // switching back to it finds this stream.
            Eif (streamShownRef.current) setConversationId(data.conversation_id);
          } else Iif (data.type === "graph_plan") {
            accumulatedTrace.push({
              type: "graph_plan",
              node_id: "",
              stages: data.stages,
            });
            setGraphPlan(data.stages);
          } else if (data.type === "node_start") {
            const { node_id, is_system_node, t_ms, pass } = data;
            accumulatedTrace.push({
              type: "node_start",
              node_id,
              is_system_node,
              ...(typeof t_ms === "number" ? { t_ms } : {}),
              ...(typeof pass === "number" ? { pass } : {}),
            });
            setNodeExecutions((prev: NodeExecution[]) => [
              ...prev,
              {
                node_id,
                is_system_node: is_system_node ?? false,
                streamingContent: "",
                tools: [],
                done: false,
                ...(typeof t_ms === "number" ? { started_ms: t_ms } : {}),
                ...(typeof pass === "number" ? { pass } : {}),
              },
            ]);
          } else Iif (data.type === "node_end") {
            const {
              node_id,
              output_preview,
              tokens,
              duration_ms,
              is_system_node,
              t_ms,
            } = data;
            accumulatedTrace.push({
              type: "node_end",
              node_id,
              output_preview,
              tokens,
              duration_ms,
              is_system_node,
              ...(typeof t_ms === "number" ? { t_ms } : {}),
            });
            setNodeExecutions((prev) =>
              prev.map((n) =>
                n.node_id === node_id && !n.done
                  ? {
                      ...n,
                      done: true,
                      output: output_preview,
                      tokens,
                      duration_ms,
                      ...(typeof t_ms === "number" ? { ended_ms: t_ms } : {}),
                    }
                  : n,
              ),
            );
            // A node's text is shown until the next one streams; a revision
            // (the agent answering again after the quality check) starts on
            // an empty preview, and Stop keeps only what the preview shows.
            setStreamingContent("");
            streamingRef.current = "";
          } else Iif (data.type === "system_node_result") {
            const { node_id, result, input } = data;
            accumulatedTrace.push({
              type: "system_node_result",
              node_id,
              result,
              input,
            });
            // The newest execution of its node only: a second pass's plan
            // must not overwrite the first's.
            setNodeExecutions((prev) =>
              withNodeResult(prev, node_id, result, input),
            );
          } else Iif (data.type === "tool_call") {
            const { node_id, tool, output_preview, status, params, report } =
              data;
            accumulatedTrace.push({
              type: "tool_call",
              node_id,
              tool,
              params: params,
              output_preview,
              status,
              ...(report ? { report } : {}),
            });
            setNodeExecutions((prev: NodeExecution[]) => {
              let targetIdx = -1;
              for (let i = prev.length - 1; i >= 0; i--) {
                if (prev[i].node_id === node_id && !prev[i].done) {
                  targetIdx = i;
                  break;
                }
              }
              if (targetIdx === -1) return prev;
              return prev.map((n: NodeExecution, i: number) =>
                i === targetIdx
                  ? {
                      ...n,
                      tools: [
                        ...n.tools,
                        {
                          tool,
                          output_preview: output_preview ?? "",
                          status: status ?? "success",
                          params,
                          ...(report ? { report } : {}),
                        },
                      ],
                    }
                  : n,
              );
            });
          } else Iif (
            data.type === "hitl_pause" ||
            data.type === "hitl_resume"
          ) {
            // Folded onto the execution that paused, exactly as a stored
            // trace is, so the live pipeline and the history agree.
            const frame = data as TraceEvent;
            accumulatedTrace.push(frame);
            if (frame.type === "hitl_resume") {
              // Accepted: the pause is over.
              setClarify(null);
              setClarifySubmitting(false);
              setClarifyErrors({});
            }
            setNodeExecutions((prev) => {
              const next = prev.map((n) => ({ ...n }));
              return attachHitl(next, frame) === -1 ? prev : next;
            });
          } else Iif (data.type === "hitl_invalid") {
            const last = lastPauseRef.current;
            setStatusMessage(undefined);
            if (last?.kind === "clarify") {
              setClarifyErrors(data.fields ?? {});
              setClarifySubmitting(false);
              setClarify((current) => current ?? last.request);
            } else if (last?.kind === "approval") {
              setHitlInterrupt({
                thread_id: last.thread_id,
                task: last.task,
                output: last.output,
              });
            }
          } else if (data.type === "status") {
            const msg = (data as { type: "status"; message: string }).message;
            setStatusMessage(msg);
            setExecutionSteps((prev) => [...prev, msg]);
          } else if (data.type === "token") {
            setStatusMessage(undefined);
            streamingRef.current += data.token;
            setStreamingContent((prev) => prev + data.token);
            setNodeExecutions((prev) => {
              const lastIdx = prev.length - 1;
              if (lastIdx < 0) return prev;
              const last = prev[lastIdx];
              Iif (last.done) return prev;
              return [
                ...prev.slice(0, lastIdx),
                {
                  ...last,
                  streamingContent: last.streamingContent + data.token,
                },
              ];
            });
          } else if (data.type === "token_reset") {
            streamingRef.current = "";
            setStreamingContent("");
            setNodeExecutions((prev) => {
              const at = resetTarget(prev, data.worker_agent_slug);
              Iif (at < 0) return prev;
              return prev.map((n, i) =>
                i === at ? { ...n, streamingContent: "" } : n,
              );
            });
          } else if (data.type === "citations") {
            accumulatedCitations = nextCitations(accumulatedCitations, data);
            setPendingCitations(accumulatedCitations);
          } else if (data.type === "response") {
            const newId = data.conversation_id ?? null;
            // Looked away from: the answer is stored, and drawn when its
            // conversation is opened β€” never added to the one on screen.
            const shown = streamShownRef.current;
            const finalCitations = accumulatedCitations;
            const finalTrace =
              accumulatedTrace.length > 0 ? [...accumulatedTrace] : undefined;
            if (shown) setConversationId(newId);
            setStatusMessage(undefined);
            setStreamingContent("");
            setPendingCitations([]);
            setExecutionSteps([]);
 
            let responseContent = data.response;
            // A withheld answer is the rule's message, never the format asked.
            Iif (outputFormat && outputFormat !== "plain" && !data.withheld) {
              const trimmed = responseContent.trim();
              if (!trimmed.startsWith("```")) {
                responseContent = `\`\`\`${outputFormat}\n${trimmed}\n\`\`\``;
              }
            }
 
            const assistantMeta: ChatMessage["meta"] = {
              ...(outputFormat ? { output_format: outputFormat } : {}),
              ...(outputSchema ? { output_schema: outputSchema } : {}),
              ...(data.model_name ? { model_name: data.model_name } : {}),
              ...(data.provider ? { provider: data.provider } : {}),
              ...(data.eval_outcome ? { eval_outcome: data.eval_outcome } : {}),
              ...(data.eval_score != null ? { eval_score: data.eval_score } : {}),
              ...(data.withheld ? { withheld: data.withheld } : {}),
              ...(data.web_search ? { web_search: data.web_search } : {}),
            };
 
            // Cache citations so they survive conversation switches within
            // this session β€” the fallback for a stored answer that carries
            // no `cited_sources`. Keyed by the stored message's id.
            if (data.message_id && finalCitations.length > 0) {
              citationsCacheRef.current.set(data.message_id, finalCitations);
            }
 
            if (shown) setChatHistory((prev) => [
              ...prev,
              {
                // The stored message's id, so a document in the reply
                // downloads (and deep-links) without reloading the chat.
                id: data.message_id ?? undefined,
                invocation_id: data.invocation_id ?? null,
                cost_usd: data.cost_usd,
                unpriced_calls: data.unpriced_calls,
                role: "assistant",
                content: responseContent,
                sent_at: new Date().toISOString(),
                meta:
                  Object.keys(assistantMeta).length > 0
                    ? assistantMeta
                    : undefined,
                citations:
                  finalCitations.length > 0 ? finalCitations : undefined,
                segments: data.segments.length > 0 ? data.segments : undefined,
                trace: finalTrace,
              },
            ]);
            setLoading(false);
            wsRef.current = null;
            streamRef.current = null;
            showStream(true);
            ws.close();
            void queryClient.invalidateQueries({
              queryKey: [QUERY_KEYS.GET.CONVERSATIONS],
            });
            // Stored, so no longer running: a list read during it is stale.
            void queryClient.invalidateQueries({
              queryKey: [QUERY_KEYS.GET.RUNNING_TURNS],
            });
            resolve();
          } else Iif (data.type === "hitl_interrupt") {
            // Graph paused β€” surface the right UI for the kind of pause.
            // WebSocket stays open either way.
            setStatusMessage(undefined);
            setStreamingContent("");
            if (
              data.interrupt_type === "clarification_request" &&
              data.questions?.length
            ) {
              const request: ClarifyRequest = {
                thread_id: data.thread_id,
                title: data.title,
                intro: data.intro,
                reason: data.reason,
                source: data.source,
                questions: data.questions,
              };
              lastPauseRef.current = { kind: "clarify", request };
              setClarifyErrors({});
              setClarify(request);
            } else {
              const approval = {
                thread_id: data.thread_id,
                task: data.task ?? "",
                output: data.output ?? "",
              };
              lastPauseRef.current = { kind: "approval", ...approval };
              setHitlInterrupt(approval);
              setHitlShowFeedback(false);
              setHitlFeedback("");
            }
          } else Eif (data.type === "error") {
            const shown = streamShownRef.current;
            setStatusMessage(undefined);
            setStreamingContent("");
            setPendingCitations([]);
            setExecutionSteps([]);
            setHitlInterrupt(null);
            setClarify(null);
            setClarifySubmitting(false);
            // Stored as a failed turn: shown where it happened, only.
            Eif (shown) setChatHistory((prev) => [
              ...prev,
              {
                role: "assistant",
                // A rule-tagged error is a governance block, not a failure β€”
                // show the rule's message the way the rule author wrote it.
                content: formatFailedTurnContent(
                  data.code === "command"
                    ? describeCommandError(
                        data.message,
                        data.suggestions,
                        data.fields,
                      )
                    : data.message,
                  data.rule,
                ),
                status: data.rule ? "blocked" : "error",
                meta: data.rule ? { rule: data.rule } : undefined,
              },
            ]);
            setLoading(false);
            wsRef.current = null;
            streamRef.current = null;
            showStream(true);
            ws.close();
            // The backend now persists blocked/errored turns too (not just
            // successful ones) β€” refetch so History/Activity pick it up
            // instead of only showing it locally until the next reload.
            void queryClient.invalidateQueries({
              queryKey: [QUERY_KEYS.GET.CONVERSATIONS],
            });
            // Stored, so no longer running: a list read during it is stale.
            void queryClient.invalidateQueries({
              queryKey: [QUERY_KEYS.GET.RUNNING_TURNS],
            });
            resolve();
          }
        } catch {
          // ignore parse errors
        }
      };
 
      ws.onerror = () => {
        if (!mine()) return;
        const shown = streamShownRef.current;
        setStatusMessage(undefined);
        setStreamingContent("");
        setPendingCitations([]);
        setExecutionSteps([]);
        setHitlInterrupt(null);
        setClarify(null);
        setClarifySubmitting(false);
        if (shown) {
          setChatHistory((prev) => [
            ...prev,
            { role: "assistant", content: "Connection error. Please try again." },
          ]);
        }
        setLoading(false);
        resolve();
      };
 
      ws.onclose = () => {
        Eif (!mine()) {
          resolve();
          return;
        }
        wsRef.current = null;
        streamRef.current = null;
        showStream(true);
        setStatusMessage(undefined);
        setStreamingContent("");
        setHitlInterrupt(null);
        setClarify(null);
        setClarifySubmitting(false);
        setLoading(false);
        resolve();
      };
    });
  };
 
  const handleStop = () => {
    const partial = streamingRef.current.trim();
    streamingRef.current = "";
    const ws = wsRef.current;
    Eif (ws?.readyState === WebSocket.OPEN) {
      // Said, not implied: a socket that just closes is a page that was
      // left, and svc-core carries that turn on to its end.
      ws.send(JSON.stringify({ type: "stop" }));
    }
    wsRef.current = null;
    streamRef.current = null;
    ws?.close();
    setLoading(false);
    setStatusMessage(undefined);
    setStreamingContent("");
    setPendingCitations([]);
    setExecutionSteps([]);
    setNodeExecutions([]);
    setGraphPlan(undefined);
    setHitlInterrupt(null);
    setClarify(null);
    setClarifySubmitting(false);
    setChatHistory((prev) => [
      ...prev,
      {
        role: "assistant",
        content: partial || "*Generation stopped.*",
      },
    ]);
  };
 
  const handleClarifySubmit = (answers: ClarifyAnswers) => {
    const ws = wsRef.current;
    if (!ws || ws.readyState !== WebSocket.OPEN) return;
    ws.send(JSON.stringify({ type: "hitl_resume", answers }));
    setClarifyErrors({});
    setClarifySubmitting(true);
    setStatusMessage("Checking your answers…");
  };
 
  /**
   * Skipping still resumes the run β€” the agent is told the questions went
   * unanswered and proceeds on its best assumption, which beats stranding a
   * paused graph the user can no longer dismiss.
   */
  const handleClarifySkip = () => {
    const ws = wsRef.current;
    if (!ws || ws.readyState !== WebSocket.OPEN) return;
    ws.send(JSON.stringify({ type: "hitl_resume", answers: {} }));
    setClarifyErrors({});
    setClarifySubmitting(true);
    setStatusMessage("Continuing without answers…");
  };
 
  const handleHitlResume = (approved: boolean) => {
    const ws = wsRef.current;
    if (!ws || ws.readyState !== WebSocket.OPEN) return;
    ws.send(
      JSON.stringify({
        type: "hitl_resume",
        approved,
        feedback: approved ? "" : hitlFeedback,
      }),
    );
    setHitlInterrupt(null);
    setHitlShowFeedback(false);
    setHitlFeedback("");
    setStatusMessage(
      approved ? "Resuming execution…" : "Incorporating feedback…",
    );
  };
 
  const title = isSystemManaged(agent) ? (
    <span className="inline-flex items-center gap-2 flex-wrap">
      {agent.name}
      <BuiltInBadge />
    </span>
  ) : (
    agent.name
  );
  const titleIcon = (
    <div className="w-8 h-8 rounded-lg bg-emerald-100 dark:bg-emerald-900/40 border border-emerald-200 dark:border-emerald-800 flex items-center justify-center shrink-0">
      <Bot className="w-4 h-4 text-emerald-500" />
    </div>
  );
 
  return (
    <ChatViewFrame frame={frame} title={title} icon={titleIcon}>
      <ChatLayout
        title={title}
        icon={titleIcon}
        frame={frame}
        sidebar={(fill, stacked) => (
          <ConversationSidebar
            conversations={sidebarConversations}
            selectedId={conversationId}
            onSelect={selectConversation}
            onNew={handleNewConversation}
            loading={conversationsLoading}
            fill={fill}
            stacked={stacked}
            answering={answering}
          />
        )}
      >
        {(fill) => (
          <div
            className={`min-w-0 flex flex-col gap-0 rounded-2xl border border-gray-200 dark:border-gray-700 shadow-sm ${
              // Filling, the column has the frame's height (the window, or
              // the page down to its bottom), so a tall clarifying form
              // scrolls inside it rather than off the screen.
              fill ? "flex-1 min-h-0 overflow-y-auto" : "overflow-hidden"
            }`}
          >
            <AgentChatToolbar
              agentId={decodedAgentId}
              agentModel={allModels.find((m) => m.id === agent.model_id)}
              models={chatModels}
              modelOverrideId={modelOverrideId}
              onModelChange={setModelOverrideId}
              skillsDisabled={disableSkills}
              onSkillsDisabledChange={setDisableSkills}
            />
            <ChatPanel
              messages={
                watchedTurn
                  ? [
                      ...chatHistory,
                      turnMessage(watchedTurn, messageAttachments),
                    ]
                  : chatHistory
              }
              displayName={agent.name}
              // Only the conversation being streamed draws the stream.
              loading={streamingHere || !!watchedTurn}
              paused={
                (streamingHere && (!!clarify || !!hitlInterrupt)) ||
                watchedTurn?.status === "awaiting_input"
              }
              conversationId={conversationId}
              // Only while the linked conversation is the one on screen β€”
              // clicking away should not leave a ring on a message that is
              // no longer there.
              highlightMessageId={
                conversationId === linkedConversationId ? linkedMessageId : null
              }
              statusMessage={
                watchedTurn
                  ? turnStatusMessage(watchedTurn)
                  : streamingHere
                    ? statusMessage
                    : undefined
              }
              streamingContent={streamingHere ? streamingContent : ""}
              streamingCitations={streamingHere ? pendingCitations : []}
              executionSteps={streamingHere ? executionSteps : []}
              nodeExecutions={streamingHere ? nodeExecutions : []}
              graphPlan={streamingHere ? graphPlan : undefined}
              onSubmit={handleSubmit}
              onStop={
                watchedTurn ? () => void stopTurn(watchedTurn) : handleStop
              }
              onUploadFile={handleUploadFile}
              documents={documents}
              onDeleteDocument={(id) => {
                void handleDeleteDocument(id);
              }}
              placeholder={`Message ${agent.name}…`}
              fill={fill}
              commands={commands}
              autoFocus={autoFocus}
            />
 
            {streamingHere && clarify && (
              <ClarifyForm
                // Remount per pause, so one form's answers never leak into
                // the next question the agent asks.
                key={clarify.questions.map((q) => q.id).join("|")}
                request={clarify}
                onSubmit={handleClarifySubmit}
                onSkip={handleClarifySkip}
                serverErrors={clarifyErrors}
                disabled={clarifySubmitting}
              />
            )}
 
            {streamingHere && hitlInterrupt && (
              <div className="rounded-xl border border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-950/40 p-4 flex flex-col gap-3 shadow-sm">
                <div className="flex items-start gap-2">
                  <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-amber-400 dark:bg-amber-600 text-white text-xs font-bold">
                    !
                  </span>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold text-amber-800 dark:text-amber-300">
                      Human review required
                    </p>
                    <p className="text-xs text-amber-700 dark:text-amber-400 mt-0.5 truncate">
                      {hitlInterrupt.task}
                    </p>
                  </div>
                </div>
 
                <div className="rounded-lg border border-amber-200 dark:border-amber-800 bg-white dark:bg-gray-900 p-3 text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap max-h-48 overflow-y-auto">
                  {hitlInterrupt.output || "(no output preview)"}
                </div>
 
                {hitlShowFeedback && (
                  <textarea
                    className="w-full rounded-lg border border-amber-300 dark:border-amber-700 bg-white dark:bg-gray-900 p-2 text-sm text-gray-700 dark:text-gray-300 placeholder:text-gray-400 dark:placeholder:text-gray-600 focus:outline-none focus:ring-2 focus:ring-amber-400 resize-none"
                    rows={3}
                    placeholder="Describe the changes needed…"
                    value={hitlFeedback}
                    onChange={(e) => setHitlFeedback(e.target.value)}
                  />
                )}
 
                <div className="flex gap-2 justify-end">
                  {hitlShowFeedback ? (
                    <>
                      <button
                        className="px-3 py-1.5 rounded-lg text-sm font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                        onClick={() => setHitlShowFeedback(false)}
                      >
                        Cancel
                      </button>
                      <button
                        className="px-3 py-1.5 rounded-lg text-sm font-medium bg-amber-500 hover:bg-amber-600 text-white transition-colors disabled:opacity-50"
                        disabled={!hitlFeedback.trim()}
                        onClick={() => handleHitlResume(false)}
                      >
                        Send feedback
                      </button>
                    </>
                  ) : (
                    <>
                      <button
                        className="px-3 py-1.5 rounded-lg text-sm font-medium text-amber-700 dark:text-amber-300 border border-amber-300 dark:border-amber-700 hover:bg-amber-100 dark:hover:bg-amber-900/40 transition-colors"
                        onClick={() => setHitlShowFeedback(true)}
                      >
                        Request changes
                      </button>
                      <button
                        className="px-3 py-1.5 rounded-lg text-sm font-medium bg-emerald-600 hover:bg-emerald-700 text-white transition-colors"
                        onClick={() => handleHitlResume(true)}
                      >
                        Approve & continue
                      </button>
                    </>
                  )}
                </div>
              </div>
            )}
          </div>
        )}
      </ChatLayout>
    </ChatViewFrame>
  );
};
 
export default AgentChatView;