Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 46 additions & 9 deletions apps/web/features/chat/components/app-chat-area.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import { filterAvailableMCPToolIDs } from "@/features/chat/model/chat-mcp-tool-d
import type { ChatAreaMessage, } from "@/features/chat/types/messages";
import { useSettingsChatPreferences } from "@/features/settings";
import { cn } from "@/lib/utils";
import type { ConversationDTO, ConversationOptions } from "@/shared/api/conversation-types";
import type { ConversationDTO, ConversationOptions, StreamMessageEvent } from "@/shared/api/conversation-types";
import { useAuthSession } from "@/shared/auth/auth-session-context";
import { DeleteFilesOption } from "@/entities/file";
import { hasMultipleImageAttachmentProcessors, normalizeImageAttachmentProcessorSelection } from "@/entities/mcp";
Expand Down Expand Up @@ -148,6 +148,11 @@ export function AppChatArea() {
const touchByPublicID = useSidebarConversationField("touchByPublicID");
const renameByPublicID = useSidebarConversationField("renameByPublicID");
const upsertConversation = useSidebarConversationField("upsertConversation");
const discussionStreamEventHandlerRef = React.useRef<(event: StreamMessageEvent) => void>(() => {});
const forwardDiscussionStreamEvent = React.useCallback(
(event: StreamMessageEvent) => discussionStreamEventHandlerRef.current(event),
[],
);
const {
cancelResumedGeneration,
conversationPublicID: messageDataConversationID,
Expand All @@ -165,6 +170,7 @@ export function AppChatArea() {
activeGenerationRunsRef,
activeGenerationRunsRevision,
onConversationRunFinished: finishConversationRun,
onDiscussionStreamEvent: forwardDiscussionStreamEvent,
});
const { greetingTitle } = useChatViewerProfile();
const activeConversation = React.useMemo(() => {
Expand Down Expand Up @@ -264,6 +270,20 @@ export function AppChatArea() {
selectedDiscussionTemplate,
discussionBindings,
setDiscussionBinding,
discussionDisabledModels,
setDiscussionModelDisabled,
discussionSnapshot,
discussionSnapshotBusy,
discussionSnapshotError,
discussionSnapshotNotice,
discussionBindingsLocked,
canAdoptDiscussionPending,
discussionRefreshConfirmationPending,
refreshDiscussionConfiguration,
cancelDiscussionRefresh,
rollbackDiscussionConfiguration,
adoptDiscussionConfiguration,
onDiscussionStreamEvent,
} = useChatModelOptions({
conversationPublicID: conversationID,
conversationModel: currentConversation?.model ?? null,
Expand All @@ -272,6 +292,7 @@ export function AppChatArea() {
discussionSeedBindings,
resetToken: newConversationRevision,
});
discussionStreamEventHandlerRef.current = onDiscussionStreamEvent;
const {
conversationKey,
draft,
Expand All @@ -289,6 +310,25 @@ export function AppChatArea() {
() => modelOptions.find((item) => item.platformModelName === selectedPlatformModelName) ?? null,
[modelOptions, selectedPlatformModelName],
);
const discussionConfigurationProps = {
modelOptions,
bindings: discussionBindings,
onChange: setDiscussionBinding,
disabled: modelsLoading,
disabledModels: discussionDisabledModels,
onDisabledChange: setDiscussionModelDisabled,
bindingsLocked: discussionBindingsLocked,
pending: Boolean(discussionSnapshot?.pending),
snapshotBusy: discussionSnapshotBusy,
snapshotError: discussionSnapshotError,
snapshotNotice: discussionSnapshotNotice,
canAdopt: canAdoptDiscussionPending,
refreshConfirmationPending: discussionRefreshConfirmationPending,
onRefresh: conversationID ? refreshDiscussionConfiguration : undefined,
onCancelRefresh: cancelDiscussionRefresh,
onRollback: conversationID ? rollbackDiscussionConfiguration : undefined,
onAdopt: conversationID ? adoptDiscussionConfiguration : undefined,
};
const modelOptionPolicyDisabled = modelOptionPolicy?.mode?.trim() === "disabled";
const refreshModelCatalogForComposer = React.useCallback(async () => {
await refreshModelCatalog();
Expand Down Expand Up @@ -481,6 +521,9 @@ export function AppChatArea() {
modelOptions,
discussionTemplate: selectedModel?.discussionTemplate ?? null,
discussionBindings,
discussionDisabledModels,
discussionExpectedPendingVersion: discussionSnapshot?.pendingVersion ?? 0,
onDiscussionStreamEvent,
selectedToolIDs,
selectedSkills,
selectedKnowledgeBaseIDs,
Expand Down Expand Up @@ -898,10 +941,7 @@ export function AppChatArea() {
{selectedDiscussionTemplate ? (
<ChatDiscussionConfig
template={selectedDiscussionTemplate}
modelOptions={modelOptions}
bindings={discussionBindings}
onChange={setDiscussionBinding}
disabled={modelsLoading}
{...discussionConfigurationProps}
/>
) : null}
<ChatInput {...chatInputProps} />
Expand Down Expand Up @@ -1011,10 +1051,7 @@ export function AppChatArea() {
{selectedDiscussionTemplate ? (
<ChatDiscussionConfig
template={selectedDiscussionTemplate}
modelOptions={modelOptions}
bindings={discussionBindings}
onChange={setDiscussionBinding}
disabled={modelsLoading}
{...discussionConfigurationProps}
/>
) : null}
<ChatInput {...chatInputProps} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,10 +284,7 @@ export function MessageDiscussion({ discussion }: { discussion?: DiscussionState
: status === "summarizing"
? t("statusSummarizing")
: t("statusRunning");
const participantCount = Math.max(
new Set(modelsByParticipant.keys()).size,
Math.max(labels.size - 1, 0),
);
const participantCount = new Set(modelsByParticipant.keys()).size;

const scrollToRound = (round: number) => {
roundRefs.current.get(round)?.scrollIntoView({ behavior: "smooth", block: "nearest" });
Expand Down
159 changes: 126 additions & 33 deletions apps/web/features/chat/components/sections/chat-discussion-config.tsx
Original file line number Diff line number Diff line change
@@ -1,59 +1,117 @@
"use client";

import * as React from "react";
import { Users } from "lucide-react";
import { Check, Loader2, Power, RefreshCw, Undo2, Users } from "lucide-react";
import { useTranslations } from "next-intl";

import { cn } from "@/lib/utils";
import type { ChatModelOption } from "@/features/chat/types/chat-runtime";
import type { DiscussionPlaceholder, DiscussionTemplateDTO } from "@/shared/api/discussion-types";
import { discussionPlaceholderLabels, orderDiscussionPlaceholders } from "@/shared/lib/discussion";
import {
canDisableDiscussionModel,
discussionBindingsComplete,
discussionPlaceholderLabels,
orderDiscussionPlaceholders,
} from "@/shared/lib/discussion";

export function ChatDiscussionConfig({
template,
modelOptions,
bindings,
onChange,
disabled,
disabledModels = [],
onDisabledChange,
bindingsLocked = false,
pending = false,
snapshotBusy = false,
snapshotError = "",
snapshotNotice = "",
canAdopt = false,
refreshConfirmationPending = false,
onRefresh,
onCancelRefresh,
onRollback,
onAdopt,
}: {
template: DiscussionTemplateDTO;
modelOptions: ChatModelOption[];
bindings: Record<string, string>;
onChange: (participant: string, model: string) => void;
disabled?: boolean;
disabledModels?: string[];
onDisabledChange?: (participant: string, disabled: boolean) => void;
bindingsLocked?: boolean;
pending?: boolean;
snapshotBusy?: boolean;
snapshotError?: string;
snapshotNotice?: string;
canAdopt?: boolean;
refreshConfirmationPending?: boolean;
onRefresh?: () => Promise<void>;
onCancelRefresh?: () => void;
onRollback?: () => Promise<void>;
onAdopt?: () => Promise<void>;
}) {
const t = useTranslations("chat.discussion");
const candidates = React.useMemo(
() => modelOptions.filter((item) => !item.kinds.includes("discussion")),
[modelOptions],
);
const missing = template.config.placeholders.some((item) => !bindings[item.key]);
const disabledSet = React.useMemo(() => new Set(disabledModels), [disabledModels]);
const missing = !discussionBindingsComplete(template.config, bindings, disabledModels);
const summaryKey = template.config.summary.participant;
const ordered = orderDiscussionPlaceholders(template.config.placeholders, summaryKey);
const summaryPlaceholder = ordered.find((item) => item.key === summaryKey);
const discussionPlaceholders = ordered.filter((item) => item.key !== summaryKey);
const labels = discussionPlaceholderLabels(template.config.placeholders, summaryKey);

const renderSelect = (placeholder: DiscussionPlaceholder, className?: string) => (
<select
aria-label={labels.get(placeholder.key) ?? placeholder.key}
const renderSelect = (placeholder: DiscussionPlaceholder, className?: string, modelDisabled = false) => {
const value = bindings[placeholder.key] ?? "";
const valueMissing = value && !candidates.some((item) => item.platformModelName === value);
return (
<select
aria-label={labels.get(placeholder.key) ?? placeholder.key}
className={cn(
"h-7 w-[min(11rem,50%)] shrink-0 rounded-md border border-border/70 bg-background px-1.5 text-[11px] text-foreground outline-none focus-visible:border-primary disabled:opacity-60",
!value && !modelDisabled && "border-rose-400",
modelDisabled && "text-muted-foreground line-through",
className,
)}
value={value}
disabled={disabled || modelDisabled || bindingsLocked}
onChange={(event) => onChange(placeholder.key, event.target.value)}
>
<option value="">{t("chooseModel")}</option>
{valueMissing ? <option value={value}>{value}</option> : null}
{candidates.map((item) => (
<option key={item.platformModelName} value={item.platformModelName}>
{item.platformModelName}
</option>
))}
</select>
);
};

const actionButton = (
label: string,
icon: React.ReactNode,
action?: () => Promise<void>,
danger = false,
) => action ? (
<button
type="button"
className={cn(
"h-7 w-[min(11rem,50%)] shrink-0 rounded-md border border-border/70 bg-background px-1.5 text-[11px] text-foreground outline-none focus-visible:border-primary disabled:opacity-60",
!bindings[placeholder.key] && "border-rose-400",
className,
"inline-flex h-6 items-center gap-1 rounded-md border border-border/60 px-2 text-[10px] text-muted-foreground hover:bg-background hover:text-foreground disabled:opacity-50",
danger && "text-amber-600 dark:text-amber-300",
)}
value={bindings[placeholder.key] ?? ""}
disabled={disabled}
onChange={(event) => onChange(placeholder.key, event.target.value)}
disabled={disabled || snapshotBusy}
onClick={() => void action()}
>
<option value="">{t("chooseModel")}</option>
{candidates.map((item) => (
<option key={item.platformModelName} value={item.platformModelName}>
{item.platformModelName}
</option>
))}
</select>
);
{snapshotBusy ? <Loader2 className="size-3 animate-spin" /> : icon}
{label}
</button>
) : null;

return (
<div className="mb-2 rounded-xl border border-border/60 bg-muted/25 px-3 py-2">
Expand All @@ -65,13 +123,31 @@ export function ChatDiscussionConfig({
<span className="text-[11px] text-muted-foreground">
{t("rounds", { count: template.config.rounds.length })}
</span>
{snapshotNotice ? <span className={cn("text-[10px]", pending ? "text-amber-600 dark:text-amber-300" : "text-emerald-600 dark:text-emerald-300")}>{snapshotNotice}</span> : null}
{pending ? (
<span className="rounded-full bg-amber-500/10 px-2 py-0.5 text-[10px] text-amber-700 dark:text-amber-300">
{t("pendingBadge")}
</span>
) : bindingsLocked ? (
<span className="rounded-full bg-primary/10 px-2 py-0.5 text-[10px] text-primary">{t("activeBadge")}</span>
) : null}
{missing ? (
<span className="rounded-full bg-rose-500/10 px-2 py-0.5 text-[11px] text-rose-600 dark:text-rose-300">
{t("selectAllModels")}
</span>
) : null}
<span className="ml-auto flex flex-wrap gap-1">
{actionButton(t(refreshConfirmationPending ? "confirmRefresh" : "refreshConfiguration"), <RefreshCw className="size-3" />, onRefresh)}
{refreshConfirmationPending ? (
<button type="button" className="h-6 rounded-md px-2 text-[10px] text-muted-foreground hover:text-foreground" onClick={onCancelRefresh}>
{t("cancelRefresh")}
</button>
) : null}
{pending ? actionButton(t("rollbackConfiguration"), <Undo2 className="size-3" />, onRollback, true) : null}
{pending && canAdopt ? actionButton(t("adoptConfiguration"), <Check className="size-3" />, onAdopt) : null}
</span>
</div>
{/* The summary model is the last node of the workflow, so it keeps a row of its own. */}
{snapshotError ? <p className="mt-1 text-[10px] text-rose-600 dark:text-rose-300">{snapshotError}</p> : null}
{summaryPlaceholder ? (
<div className="mt-2 flex min-w-0 items-center gap-2 rounded-md border border-primary/30 bg-primary/5 px-2 py-1">
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-[11px] text-muted-foreground">
Expand All @@ -83,19 +159,36 @@ export function ChatDiscussionConfig({
{renderSelect(summaryPlaceholder, "w-[min(14rem,45%)]")}
</div>
) : null}
{/* Discussion models fill the row and wrap only when they run out of room. */}
<div className="mt-1.5 flex flex-wrap gap-1.5">
{discussionPlaceholders.map((placeholder) => (
<div
key={placeholder.key}
className="flex min-w-[13rem] flex-1 items-center gap-2 rounded-md border border-border/50 bg-background/40 px-2 py-1"
>
<span className="min-w-0 flex-1 truncate text-[11px] text-muted-foreground">
{labels.get(placeholder.key) ?? placeholder.key}
</span>
{renderSelect(placeholder)}
</div>
))}
{discussionPlaceholders.map((placeholder) => {
const modelDisabled = disabledSet.has(placeholder.key);
const canDisable = canDisableDiscussionModel(template.config, placeholder.key, disabledModels);
return (
<div
key={placeholder.key}
className={cn(
"flex min-w-[13rem] flex-1 items-center gap-2 rounded-md border border-border/50 bg-background/40 px-2 py-1",
modelDisabled && "opacity-60",
)}
>
<button
type="button"
aria-label={modelDisabled ? t("enableModel") : t("disableModel")}
aria-pressed={!modelDisabled}
title={modelDisabled ? t("enableModel") : canDisable ? t("disableModel") : t("lastModelRequired")}
className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"
disabled={disabled || (!modelDisabled && !canDisable)}
onClick={() => onDisabledChange?.(placeholder.key, !modelDisabled)}
>
<Power className={cn("size-3.5", !modelDisabled && "text-emerald-600 dark:text-emerald-400")} />
</button>
<span className={cn("min-w-0 flex-1 truncate text-[11px] text-muted-foreground", modelDisabled && "line-through")}>
{labels.get(placeholder.key) ?? placeholder.key}
</span>
{renderSelect(placeholder, undefined, modelDisabled)}
</div>
);
})}
</div>
</div>
);
Expand Down
6 changes: 5 additions & 1 deletion apps/web/features/chat/hooks/use-chat-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { applyDiscussionEvent } from "@/features/chat/model/discussion-stream";
import { mergeProcessTraceSnapshot } from "@/features/chat/model/message-submit";
import { upsertLiveUpstreamThinkTrace } from "@/features/chat/model/upstream-think-store";
import { cancelMessageGeneration, listMessagesPage, resumeMessageGenerationStream } from "@/shared/api/conversation";
import type { MessageDTO } from "@/shared/api/conversation-types";
import type { MessageDTO, StreamMessageEvent } from "@/shared/api/conversation-types";
import { resolveAccessToken } from "@/shared/auth/resolve-access-token";

// The first page covers recent turns; older ones load as the user scrolls up.
Expand Down Expand Up @@ -35,10 +35,12 @@ export function useChatData(
activeGenerationRunsRef,
activeGenerationRunsRevision = 0,
onConversationRunFinished,
onDiscussionStreamEvent,
}: {
activeGenerationRunsRef?: React.RefObject<Set<string>>;
activeGenerationRunsRevision?: number;
onConversationRunFinished?: (runID: string) => void;
onDiscussionStreamEvent?: (event: StreamMessageEvent) => void;
} = {},
) {
const t = useTranslations("chat.data");
Expand Down Expand Up @@ -444,6 +446,7 @@ export function useChatData(
if (isResumeInactive()) {
return;
}
onDiscussionStreamEvent?.(event);
let summaryContent: string | undefined;
if (event.type === "discussion_summary_delta") {
summaryContent = `${resumedTextByRun[pendingRunID] ?? ""}${event.delta}`;
Expand Down Expand Up @@ -565,6 +568,7 @@ export function useChatData(
pendingRunID,
pendingRunIsActive,
onConversationRunFinished,
onDiscussionStreamEvent,
reload,
tSubmit,
]);
Expand Down
Loading
Loading