;
}) {
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) => (
-
- );
+ {snapshotBusy ? : icon}
+ {label}
+
+ ) : null;
return (
@@ -65,13 +123,31 @@ export function ChatDiscussionConfig({
{t("rounds", { count: template.config.rounds.length })}
+ {snapshotNotice ? {snapshotNotice} : null}
+ {pending ? (
+
+ {t("pendingBadge")}
+
+ ) : bindingsLocked ? (
+ {t("activeBadge")}
+ ) : null}
{missing ? (
{t("selectAllModels")}
) : null}
+
+ {actionButton(t(refreshConfirmationPending ? "confirmRefresh" : "refreshConfiguration"), , onRefresh)}
+ {refreshConfirmationPending ? (
+
+ ) : null}
+ {pending ? actionButton(t("rollbackConfiguration"), , onRollback, true) : null}
+ {pending && canAdopt ? actionButton(t("adoptConfiguration"), , onAdopt) : null}
+
- {/* The summary model is the last node of the workflow, so it keeps a row of its own. */}
+ {snapshotError ? {snapshotError}
: null}
{summaryPlaceholder ? (
@@ -83,19 +159,36 @@ export function ChatDiscussionConfig({
{renderSelect(summaryPlaceholder, "w-[min(14rem,45%)]")}
) : null}
- {/* Discussion models fill the row and wrap only when they run out of room. */}
- {discussionPlaceholders.map((placeholder) => (
-
-
- {labels.get(placeholder.key) ?? placeholder.key}
-
- {renderSelect(placeholder)}
-
- ))}
+ {discussionPlaceholders.map((placeholder) => {
+ const modelDisabled = disabledSet.has(placeholder.key);
+ const canDisable = canDisableDiscussionModel(template.config, placeholder.key, disabledModels);
+ return (
+
+
+
+ {labels.get(placeholder.key) ?? placeholder.key}
+
+ {renderSelect(placeholder, undefined, modelDisabled)}
+
+ );
+ })}
);
diff --git a/apps/web/features/chat/hooks/use-chat-data.ts b/apps/web/features/chat/hooks/use-chat-data.ts
index caa9312c8..e13f472b5 100644
--- a/apps/web/features/chat/hooks/use-chat-data.ts
+++ b/apps/web/features/chat/hooks/use-chat-data.ts
@@ -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.
@@ -35,10 +35,12 @@ export function useChatData(
activeGenerationRunsRef,
activeGenerationRunsRevision = 0,
onConversationRunFinished,
+ onDiscussionStreamEvent,
}: {
activeGenerationRunsRef?: React.RefObject>;
activeGenerationRunsRevision?: number;
onConversationRunFinished?: (runID: string) => void;
+ onDiscussionStreamEvent?: (event: StreamMessageEvent) => void;
} = {},
) {
const t = useTranslations("chat.data");
@@ -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}`;
@@ -565,6 +568,7 @@ export function useChatData(
pendingRunID,
pendingRunIsActive,
onConversationRunFinished,
+ onDiscussionStreamEvent,
reload,
tSubmit,
]);
diff --git a/apps/web/features/chat/hooks/use-chat-discussion.ts b/apps/web/features/chat/hooks/use-chat-discussion.ts
new file mode 100644
index 000000000..bdaf267fa
--- /dev/null
+++ b/apps/web/features/chat/hooks/use-chat-discussion.ts
@@ -0,0 +1,313 @@
+"use client";
+
+import * as React from "react";
+import { useTranslations } from "next-intl";
+import {
+ adoptDiscussionSnapshot,
+ getDiscussionSnapshot,
+ refreshDiscussionSnapshot,
+ rollbackDiscussionSnapshot,
+} from "@/shared/api/discussion";
+import type {
+ DiscussionConversationSnapshot,
+ DiscussionRuntimePlan,
+ DiscussionSnapshotContent,
+ DiscussionTemplateDTO,
+} from "@/shared/api/discussion-types";
+import type { StreamMessageEvent } from "@/shared/api/conversation-types";
+import { ApiError } from "@/shared/api/http-client";
+import { resolveAccessToken } from "@/shared/auth/resolve-access-token";
+import {
+ canDisableDiscussionModel,
+ discussionRuntimeBindings,
+} from "@/shared/lib/discussion";
+import { isRecord } from "@/shared/lib/type-guards";
+
+function discussionBindingsStorageKey(conversationPublicID: string | null, templatePublicID: string): string {
+ return `deeix:discussion-bindings:${conversationPublicID || "new"}:${templatePublicID}`;
+}
+
+function discussionDisabledStorageKey(conversationPublicID: string | null, templatePublicID: string): string {
+ return `deeix:discussion-disabled:${conversationPublicID || "new"}:${templatePublicID}`;
+}
+
+function readStoredBindings(key: string): Record {
+ if (typeof window === "undefined") return {};
+ try {
+ const parsed: unknown = JSON.parse(window.localStorage.getItem(key) ?? "{}");
+ if (!isRecord(parsed)) return {};
+ return Object.fromEntries(
+ Object.entries(parsed).filter((entry): entry is [string, string] => typeof entry[1] === "string" && Boolean(entry[1].trim())),
+ );
+ } catch {
+ return {};
+ }
+}
+
+function readStoredDisabled(key: string): string[] {
+ if (typeof window === "undefined") return [];
+ try {
+ const parsed: unknown = JSON.parse(window.localStorage.getItem(key) ?? "[]");
+ return Array.isArray(parsed)
+ ? Array.from(new Set(parsed.filter((item): item is string => typeof item === "string" && Boolean(item.trim()))))
+ : [];
+ } catch {
+ return [];
+ }
+}
+
+function writeStored(key: string, value: unknown): void {
+ try {
+ window.localStorage.setItem(key, JSON.stringify(value));
+ } catch {
+ // The server snapshot is authoritative; local preferences are best-effort.
+ }
+}
+
+function snapshotBindings(content: DiscussionSnapshotContent | null | undefined): Record {
+ return content ? discussionRuntimeBindings(content.plan) : {};
+}
+
+function bindingsForTemplate(
+ template: DiscussionTemplateDTO,
+ sources: readonly Record[],
+): Record {
+ const next: Record = {};
+ for (const placeholder of template.config.placeholders) {
+ next[placeholder.key] = "";
+ for (const source of sources) {
+ if (source[placeholder.key]?.trim()) {
+ next[placeholder.key] = source[placeholder.key].trim();
+ break;
+ }
+ }
+ next[placeholder.key] ||= placeholder.defaultModel || "";
+ }
+ return next;
+}
+
+export function useChatDiscussion({
+ conversationPublicID,
+ selectedPlatformModelName,
+ discussionTemplates,
+ discussionSeedBindings,
+}: {
+ conversationPublicID: string | null;
+ selectedPlatformModelName: string;
+ discussionTemplates: DiscussionTemplateDTO[];
+ discussionSeedBindings?: Record | null;
+}) {
+ const t = useTranslations("chat.discussion");
+ const templatePublicID = selectedPlatformModelName.startsWith("discussion:")
+ ? selectedPlatformModelName.slice("discussion:".length).trim()
+ : "";
+ const liveTemplate = discussionTemplates.find((item) => item.publicID === templatePublicID) ?? null;
+ const [snapshot, setSnapshot] = React.useState(null);
+ const [snapshotLoading, setSnapshotLoading] = React.useState(false);
+ const [snapshotBusy, setSnapshotBusy] = React.useState(false);
+ const [refreshConfirmationPending, setRefreshConfirmationPending] = React.useState(false);
+ const [snapshotError, setSnapshotError] = React.useState("");
+ const [snapshotNotice, setSnapshotNotice] = React.useState("");
+ const [canAdoptPending, setCanAdoptPending] = React.useState(false);
+ const [discussionBindings, setDiscussionBindings] = React.useState>({});
+ const [disabledModels, setDisabledModels] = React.useState([]);
+ const snapshotContent = snapshot?.pending ?? snapshot?.active ?? null;
+ const selectedDiscussionTemplate = snapshotContent?.template ?? liveTemplate;
+ const bindingsRef = React.useRef>({});
+ const snapshotRef = React.useRef(null);
+ const bindingScopeRef = React.useRef("");
+ const bindingRevisionRef = React.useRef("");
+ const bindingsTouchedRef = React.useRef(false);
+ const disabledScopeRef = React.useRef("");
+
+ React.useEffect(() => { bindingsRef.current = discussionBindings; }, [discussionBindings]);
+ React.useEffect(() => { snapshotRef.current = snapshot; }, [snapshot]);
+
+ React.useEffect(() => {
+ let cancelled = false;
+ setSnapshot(null);
+ setSnapshotError("");
+ setSnapshotNotice("");
+ setCanAdoptPending(false);
+ setRefreshConfirmationPending(false);
+ if (!conversationPublicID || !templatePublicID) {
+ setSnapshotLoading(false);
+ return;
+ }
+ setSnapshotLoading(true);
+ void (async () => {
+ try {
+ const token = await resolveAccessToken();
+ if (!token) throw new Error("missing access token");
+ const result = await getDiscussionSnapshot(token, conversationPublicID, templatePublicID);
+ if (!cancelled) setSnapshot(result);
+ } catch (error) {
+ if (!cancelled) setSnapshotError(error instanceof ApiError && error.status === 409 ? t("snapshotConflict") : t("snapshotLoadFailed"));
+ } finally {
+ if (!cancelled) setSnapshotLoading(false);
+ }
+ })();
+ return () => { cancelled = true; };
+ }, [conversationPublicID, t, templatePublicID]);
+
+ React.useEffect(() => {
+ const template = selectedDiscussionTemplate;
+ const scope = `${conversationPublicID || "new"}|${templatePublicID}`;
+ const revision = snapshot ? `${snapshot.activeVersion}:${snapshot.pendingVersion}:${snapshot.updatedAt}` : "";
+ const scopeChanged = bindingScopeRef.current !== scope;
+ const revisionChanged = bindingRevisionRef.current !== revision;
+ const previousScope = bindingScopeRef.current;
+ bindingScopeRef.current = scope;
+ bindingRevisionRef.current = revision;
+ if (!template) {
+ setDiscussionBindings((current) => Object.keys(current).length === 0 ? current : {});
+ bindingsTouchedRef.current = false;
+ return;
+ }
+ if (!scopeChanged && !revisionChanged && (bindingsTouchedRef.current || !discussionSeedBindings)) return;
+
+ const stored = readStoredBindings(discussionBindingsStorageKey(conversationPublicID, templatePublicID));
+ const [previousConversationID, previousTemplateID] = previousScope.split("|");
+ const carried = scopeChanged && previousConversationID === "new" && previousTemplateID === templatePublicID && !snapshotContent
+ ? bindingsRef.current
+ : null;
+ const next = carried && Object.keys(carried).length > 0
+ ? { ...carried }
+ : bindingsForTemplate(template, [snapshotBindings(snapshotContent), discussionSeedBindings ?? {}, stored]);
+ if (scopeChanged || revisionChanged) bindingsTouchedRef.current = false;
+ writeStored(discussionBindingsStorageKey(conversationPublicID, templatePublicID), next);
+ setDiscussionBindings(next);
+ }, [conversationPublicID, discussionSeedBindings, selectedDiscussionTemplate, snapshot, snapshotContent, templatePublicID]);
+
+ React.useEffect(() => {
+ const scope = `${conversationPublicID || "new"}|${templatePublicID}`;
+ if (disabledScopeRef.current === scope) return;
+ const previousScope = disabledScopeRef.current;
+ disabledScopeRef.current = scope;
+ if (!templatePublicID) {
+ setDisabledModels([]);
+ return;
+ }
+ const [previousConversationID, previousTemplateID] = previousScope.split("|");
+ if (previousConversationID === "new" && previousTemplateID === templatePublicID && conversationPublicID) {
+ writeStored(discussionDisabledStorageKey(conversationPublicID, templatePublicID), disabledModels);
+ return;
+ }
+ setDisabledModels(readStoredDisabled(discussionDisabledStorageKey(conversationPublicID, templatePublicID)));
+ }, [conversationPublicID, disabledModels, templatePublicID]);
+
+ const setDiscussionBinding = React.useCallback((participant: string, model: string) => {
+ if (snapshotRef.current?.active && !snapshotRef.current.pending) return;
+ bindingsTouchedRef.current = true;
+ setDiscussionBindings((current) => {
+ const next = { ...current, [participant]: model };
+ writeStored(discussionBindingsStorageKey(conversationPublicID, templatePublicID), next);
+ return next;
+ });
+ }, [conversationPublicID, templatePublicID]);
+
+ const setDiscussionModelDisabled = React.useCallback((participant: string, shouldDisable: boolean) => {
+ const template = selectedDiscussionTemplate;
+ if (!template) return;
+ setDisabledModels((current) => {
+ if (shouldDisable && !canDisableDiscussionModel(template.config, participant, current)) return current;
+ const next = shouldDisable
+ ? Array.from(new Set([...current, participant]))
+ : current.filter((item) => item !== participant);
+ writeStored(discussionDisabledStorageKey(conversationPublicID, templatePublicID), next);
+ return next;
+ });
+ }, [conversationPublicID, selectedDiscussionTemplate, templatePublicID]);
+
+ const runSnapshotAction = React.useCallback(async (
+ action: "refresh" | "rollback" | "adopt",
+ ) => {
+ if (!conversationPublicID || !templatePublicID || snapshotBusy) return;
+ if (action === "refresh" && snapshotRef.current?.pending && !refreshConfirmationPending) {
+ setRefreshConfirmationPending(true);
+ setSnapshotNotice(t("refreshAgainConfirm"));
+ return;
+ }
+ setRefreshConfirmationPending(false);
+ setSnapshotBusy(true);
+ setSnapshotError("");
+ setSnapshotNotice("");
+ try {
+ const token = await resolveAccessToken();
+ if (!token) throw new Error("missing access token");
+ const expectedPendingVersion = snapshotRef.current?.pendingVersion ?? 0;
+ const result = action === "refresh"
+ ? await refreshDiscussionSnapshot(token, conversationPublicID, templatePublicID, {
+ models: bindingsRef.current,
+ expectedPendingVersion,
+ })
+ : action === "rollback"
+ ? await rollbackDiscussionSnapshot(token, conversationPublicID, templatePublicID, expectedPendingVersion)
+ : await adoptDiscussionSnapshot(token, conversationPublicID, templatePublicID, expectedPendingVersion);
+ snapshotRef.current = result;
+ setSnapshot(result);
+ setCanAdoptPending(false);
+ bindingsTouchedRef.current = false;
+ setSnapshotNotice(t(action === "refresh" ? "refreshReady" : action === "rollback" ? "rollbackDone" : "adoptDone"));
+ } catch (error) {
+ setSnapshotError(error instanceof ApiError && error.status === 409 ? t("snapshotConflict") : t("snapshotActionFailed"));
+ } finally {
+ setSnapshotBusy(false);
+ }
+ }, [conversationPublicID, refreshConfirmationPending, snapshotBusy, t, templatePublicID]);
+
+ const onDiscussionStreamEvent = React.useCallback((event: StreamMessageEvent) => {
+ if (event.type !== "discussion_done" || event.state.templateId !== templatePublicID) return;
+ if (event.state.status === "completed_with_errors" && snapshotRef.current?.pending) {
+ setCanAdoptPending(true);
+ setSnapshotNotice(t("pendingNotCommitted"));
+ }
+ if (!event.snapshotCommitted) return;
+ const current = snapshotRef.current;
+ const template = event.activeSnapshot?.template ?? current?.pending?.template ?? selectedDiscussionTemplate;
+ if (!template) return;
+ const active: DiscussionSnapshotContent = event.activeSnapshot ?? {
+ template,
+ config: template.config,
+ plan: { rounds: event.state.rounds, summary: event.state.summary } satisfies DiscussionRuntimePlan,
+ };
+ const pendingVersion = event.pendingVersion ?? 0;
+ const next: DiscussionConversationSnapshot = {
+ templatePublicID,
+ active,
+ activeVersion: event.activeVersion ?? Math.max(current?.activeVersion ?? 0, 1),
+ pending: pendingVersion > 0 ? current?.pending ?? null : null,
+ pendingVersion,
+ updatedAt: new Date().toISOString(),
+ };
+ snapshotRef.current = next;
+ setSnapshot(next);
+ setCanAdoptPending(false);
+ bindingsTouchedRef.current = false;
+ setSnapshotNotice(t("pendingCommitted"));
+ }, [selectedDiscussionTemplate, t, templatePublicID]);
+
+ return {
+ selectedDiscussionTemplate,
+ discussionBindings,
+ setDiscussionBinding,
+ discussionDisabledModels: disabledModels,
+ setDiscussionModelDisabled,
+ discussionSnapshot: snapshot,
+ discussionSnapshotLoading: snapshotLoading,
+ discussionSnapshotBusy: snapshotBusy,
+ discussionSnapshotError: snapshotError,
+ discussionSnapshotNotice: snapshotNotice,
+ discussionBindingsLocked: Boolean(snapshot?.active && !snapshot.pending),
+ canAdoptDiscussionPending: canAdoptPending,
+ discussionRefreshConfirmationPending: refreshConfirmationPending,
+ refreshDiscussionConfiguration: () => runSnapshotAction("refresh"),
+ cancelDiscussionRefresh: () => {
+ setRefreshConfirmationPending(false);
+ setSnapshotNotice("");
+ },
+ rollbackDiscussionConfiguration: () => runSnapshotAction("rollback"),
+ adoptDiscussionConfiguration: () => runSnapshotAction("adopt"),
+ onDiscussionStreamEvent,
+ };
+}
diff --git a/apps/web/features/chat/hooks/use-chat-message-submit.ts b/apps/web/features/chat/hooks/use-chat-message-submit.ts
index e1bef85d1..447ca23cd 100644
--- a/apps/web/features/chat/hooks/use-chat-message-submit.ts
+++ b/apps/web/features/chat/hooks/use-chat-message-submit.ts
@@ -70,6 +70,7 @@ import type {
import { ApiError } from "@/shared/api/http-client";
import type { SkillSummaryDTO } from "@/shared/api/skills-types";
import type { DiscussionTemplateDTO } from "@/shared/api/discussion-types";
+import { discussionBindingsComplete } from "@/shared/lib/discussion";
import { resolveAccessToken } from "@/shared/auth/resolve-access-token";
import { notifyResponseCompletion } from "@/shared/lib/system-notifications";
@@ -81,6 +82,9 @@ export function useChatMessageSubmit({
modelOptions,
discussionTemplate,
discussionBindings,
+ discussionDisabledModels,
+ discussionExpectedPendingVersion,
+ onDiscussionStreamEvent,
selectedToolIDs,
selectedSkills,
selectedKnowledgeBaseIDs,
@@ -137,6 +141,9 @@ export function useChatMessageSubmit({
modelOptions: ChatModelOption[];
discussionTemplate?: DiscussionTemplateDTO | null;
discussionBindings?: Record;
+ discussionDisabledModels?: string[];
+ discussionExpectedPendingVersion?: number;
+ onDiscussionStreamEvent?: (event: StreamMessageEvent) => void;
selectedToolIDs: number[];
selectedSkills: SkillSummaryDTO[];
selectedKnowledgeBaseIDs: string[];
@@ -285,6 +292,7 @@ export function useChatMessageSubmit({
resetStreamBuffer,
setStreamTextSnapshot,
onConversationRunFinished,
+ onDiscussionStreamEvent,
});
const submitMessage = React.useCallback(
@@ -561,8 +569,17 @@ export function useChatMessageSubmit({
effectiveAttachments,
platformModelName,
discussion:
- discussionTemplate && Object.values(discussionBindings ?? {}).every((value) => value.trim())
- ? { templatePublicID: discussionTemplate.publicID, models: discussionBindings ?? {} }
+ discussionTemplate && discussionBindingsComplete(
+ discussionTemplate.config,
+ discussionBindings ?? {},
+ discussionDisabledModels ?? [],
+ )
+ ? {
+ templatePublicID: discussionTemplate.publicID,
+ models: discussionBindings ?? {},
+ disabledModels: discussionDisabledModels ?? [],
+ expectedPendingVersion: discussionExpectedPendingVersion ?? 0,
+ }
: undefined,
selectedToolIDs: plan.selectedToolIDs,
selectedSkills: plan.selectedSkills,
@@ -794,6 +811,8 @@ export function useChatMessageSubmit({
collectUIStates,
combinedMessages,
discussionBindings,
+ discussionDisabledModels,
+ discussionExpectedPendingVersion,
discussionTemplate,
flushStreamTextNow,
flushUpstreamThinkNow,
diff --git a/apps/web/features/chat/hooks/use-chat-model-options.ts b/apps/web/features/chat/hooks/use-chat-model-options.ts
index 8f77b7594..e18d67814 100644
--- a/apps/web/features/chat/hooks/use-chat-model-options.ts
+++ b/apps/web/features/chat/hooks/use-chat-model-options.ts
@@ -3,6 +3,7 @@
import { useTranslations } from "next-intl";
import * as React from "react";
import { sanitizeConversationOptions } from "@/features/chat/model/conversation-options";
+import { useChatDiscussion } from "@/features/chat/hooks/use-chat-discussion";
import {
type ChatModelOption,
MODEL_MODALITIES,
@@ -429,46 +430,6 @@ function parseModalities(value: unknown): ModelModality[] {
return MODEL_MODALITIES.filter((modality) => value.includes(modality));
}
-function discussionBindingsStorageKey(conversationPublicID: string | null, templatePublicID: string): string {
- return `deeix:discussion-bindings:${conversationPublicID || "new"}:${templatePublicID}`;
-}
-
-function readStoredDiscussionBindings(key: string): Record {
- if (typeof window === "undefined") {
- return {};
- }
- try {
- const raw = window.localStorage.getItem(key);
- if (!raw) {
- return {};
- }
- const parsed = JSON.parse(raw);
- if (!isRecord(parsed)) {
- return {};
- }
- const result: Record = {};
- for (const [name, value] of Object.entries(parsed)) {
- if (typeof value === "string" && value.trim()) {
- result[name] = value;
- }
- }
- return result;
- } catch {
- return {};
- }
-}
-
-function writeStoredDiscussionBindings(key: string, bindings: Record): void {
- if (typeof window === "undefined") {
- return;
- }
- try {
- window.localStorage.setItem(key, JSON.stringify(bindings));
- } catch {
- // Draft persistence is best-effort; the server record remains the source of truth.
- }
-}
-
export function useChatModelOptions({
conversationPublicID,
conversationModel,
@@ -489,7 +450,6 @@ export function useChatModelOptions({
const { settings: userSettings } = useUserSettings();
const [availableModels, setAvailableModels] = React.useState([]);
const [discussionTemplates, setDiscussionTemplates] = React.useState([]);
- const [discussionBindings, setDiscussionBindings] = React.useState>({});
const [modelsLoading, setModelsLoading] = React.useState(true);
const [defaultModelResolving, setDefaultModelResolving] = React.useState(false);
const [modelsErrorMsg, setModelsErrorMsg] = React.useState("");
@@ -501,7 +461,6 @@ export function useChatModelOptions({
const [mcpMaxSelectedTools, setMCPMaxSelectedTools] = React.useState(32);
const activeConversationRef = React.useRef(null);
const userSelectedModelRef = React.useRef(false);
- const discussionBindingsTouchedRef = React.useRef(false);
// Inputs of the last default-model resolution other than the catalog itself (see below).
const defaultModelResolutionKeyRef = React.useRef("");
const previousResetTokenRef = React.useRef(resetToken);
@@ -528,6 +487,13 @@ export function useChatModelOptions({
userSelectedModelRef.current = true;
setSelectedPlatformModelName(platformModelName);
}, []);
+ const discussion = useChatDiscussion({
+ conversationPublicID,
+ selectedPlatformModelName,
+ discussionTemplates,
+ discussionSeedBindings,
+ });
+ const selectedDiscussionTemplate = discussion.selectedDiscussionTemplate;
const loadModelCatalog = React.useCallback((accessToken?: string): Promise => {
if (modelCatalogRequestRef.current) {
@@ -577,14 +543,15 @@ export function useChatModelOptions({
return null;
}
if (normalizedName.startsWith("discussion:")) {
- const template = discussionTemplates.find((item) => `discussion:${item.publicID}` === normalizedName);
- return template ? toDiscussionModelOption(template, discussionT("groupName")) : null;
+ return selectedDiscussionTemplate?.publicID === normalizedName.slice("discussion:".length)
+ ? toDiscussionModelOption(selectedDiscussionTemplate, discussionT("groupName"))
+ : null;
}
const catalog = await refreshModelCatalog();
const nextModel = catalog.models.find((item) => item.platformModelName === normalizedName);
return nextModel ? toChatModelOption(nextModel, catalog.modelOptionPolicy?.nativeTools ?? []) : null;
- }, [discussionT, discussionTemplates, refreshModelCatalog]);
+ }, [discussionT, refreshModelCatalog, selectedDiscussionTemplate]);
React.useEffect(() => {
let cancelled = false;
@@ -741,110 +708,25 @@ export function useChatModelOptions({
};
}, [availableModels, conversationPublicID, newConversationDefaultModel, newConversationDefaultsPending, resetToken, userDefaultModel]);
- const selectedDiscussionTemplate = React.useMemo(() => {
- const normalized = selectedPlatformModelName.trim();
- if (!normalized.startsWith("discussion:")) {
- return null;
- }
- return discussionTemplates.find((item) => `discussion:${item.publicID}` === normalized) ?? null;
- }, [discussionTemplates, selectedPlatformModelName]);
-
- // Scope is conversation + template: only a real change reloads the bindings.
- const discussionBindingScopeRef = React.useRef("");
- const discussionBindingsRef = React.useRef>({});
- React.useEffect(() => {
- discussionBindingsRef.current = discussionBindings;
- }, [discussionBindings]);
-
- React.useEffect(() => {
- const template = selectedDiscussionTemplate;
- const scope = `${conversationPublicID || "new"}|${template?.publicID ?? ""}`;
- if (discussionBindingScopeRef.current === scope) {
- // The seed arrives with the message list, which can load after this scope was set up.
- // Until the user picks a model themselves, the last discussion's bindings win over the
- // template defaults; otherwise the composer would show models the last run never used.
- if (!template || !discussionSeedBindings || discussionBindingsTouchedRef.current) {
- return;
- }
- const next: Record = {};
- for (const placeholder of template.config.placeholders) {
- next[placeholder.key] =
- discussionSeedBindings[placeholder.key] ||
- discussionBindingsRef.current[placeholder.key] ||
- placeholder.defaultModel ||
- "";
- }
- const unchanged = template.config.placeholders.every(
- (placeholder) => discussionBindingsRef.current[placeholder.key] === next[placeholder.key],
- );
- if (unchanged) {
- return;
- }
- writeStoredDiscussionBindings(discussionBindingsStorageKey(conversationPublicID, template.publicID), next);
- setDiscussionBindings(next);
- return;
- }
- const previousScope = discussionBindingScopeRef.current;
- discussionBindingScopeRef.current = scope;
- discussionBindingsTouchedRef.current = false;
- if (!template) {
- setDiscussionBindings((previous) => (Object.keys(previous).length === 0 ? previous : {}));
- return;
- }
- const [previousConversationID, previousTemplateID] = previousScope.split("|");
- // Sending the first message turns the draft into a conversation. The models just picked
- // belong to that message, so they carry over instead of being reset by the new key.
- const carriedOver =
- previousConversationID === "new" && previousTemplateID === template.publicID
- ? discussionBindingsRef.current
- : null;
- if (carriedOver && Object.keys(carriedOver).length > 0) {
- const next = { ...carriedOver };
- writeStoredDiscussionBindings(
- discussionBindingsStorageKey(conversationPublicID, template.publicID),
- next,
- );
- setDiscussionBindings(next);
- return;
- }
- const stored = readStoredDiscussionBindings(
- discussionBindingsStorageKey(conversationPublicID, template.publicID),
- );
- const next: Record = {};
- for (const placeholder of template.config.placeholders) {
- next[placeholder.key] =
- discussionSeedBindings?.[placeholder.key] || stored[placeholder.key] || placeholder.defaultModel || "";
- }
- setDiscussionBindings(next);
- }, [conversationPublicID, discussionSeedBindings, selectedDiscussionTemplate]);
-
- const setDiscussionBinding = React.useCallback((participant: string, model: string) => {
- discussionBindingsTouchedRef.current = true;
- setDiscussionBindings((current) => {
- const next = { ...current, [participant]: model };
- if (selectedDiscussionTemplate) {
- writeStoredDiscussionBindings(
- discussionBindingsStorageKey(conversationPublicID, selectedDiscussionTemplate.publicID),
- next,
- );
- }
- return next;
- });
- }, [conversationPublicID, selectedDiscussionTemplate]);
-
const modelOptions = React.useMemo(
- () => [
- ...availableModels.map((model) => toChatModelOption(model, modelOptionPolicy?.nativeTools ?? [])),
- ...discussionTemplates.map((template) => toDiscussionModelOption(template, discussionT("groupName"))),
- ],
- [availableModels, discussionT, discussionTemplates, modelOptionPolicy?.nativeTools],
+ () => {
+ const templates = [...discussionTemplates];
+ if (selectedDiscussionTemplate && !templates.some((item) => item.publicID === selectedDiscussionTemplate.publicID)) {
+ templates.push(selectedDiscussionTemplate);
+ }
+ return [
+ ...availableModels.map((model) => toChatModelOption(model, modelOptionPolicy?.nativeTools ?? [])),
+ ...templates.map((template) => toDiscussionModelOption(template, discussionT("groupName"))),
+ ];
+ },
+ [availableModels, discussionT, discussionTemplates, modelOptionPolicy?.nativeTools, selectedDiscussionTemplate],
);
return {
modelOptions,
refreshModelCatalog,
refreshModelOption,
- modelsLoading: modelsLoading || newConversationDefaultsPending || defaultModelResolving,
+ modelsLoading: modelsLoading || newConversationDefaultsPending || defaultModelResolving || discussion.discussionSnapshotLoading,
modelsErrorMsg,
sendShortcut,
restoreDraftOnFailure,
@@ -865,8 +747,6 @@ export function useChatModelOptions({
mcpMaxSelectedTools,
selectedPlatformModelName,
setSelectedPlatformModelName: selectPlatformModelName,
- selectedDiscussionTemplate,
- discussionBindings,
- setDiscussionBinding,
+ ...discussion,
};
}
diff --git a/apps/web/features/chat/hooks/use-chat-run-stream.ts b/apps/web/features/chat/hooks/use-chat-run-stream.ts
index 47128dc1b..a5300c458 100644
--- a/apps/web/features/chat/hooks/use-chat-run-stream.ts
+++ b/apps/web/features/chat/hooks/use-chat-run-stream.ts
@@ -46,6 +46,7 @@ export function useChatRunStream({
resetStreamBuffer,
setStreamTextSnapshot,
onConversationRunFinished,
+ onDiscussionStreamEvent,
}: {
updatePendingExchange: (
exchangeKey: string,
@@ -61,6 +62,7 @@ export function useChatRunStream({
resetStreamBuffer: (exchangeKey?: string) => void;
setStreamTextSnapshot: (exchangeKey: string, content: string) => void;
onConversationRunFinished?: (runID: string) => void;
+ onDiscussionStreamEvent?: (event: StreamMessageEvent) => void;
}) {
const t = useTranslations("chat.submit");
@@ -107,7 +109,12 @@ export function useChatRunStream({
sourceMessagePublicID: string | null;
branchReason: "default" | "retry" | "edit";
assistantOnlyBranch: boolean;
- discussion?: { templatePublicID: string; models: Record };
+ discussion?: {
+ templatePublicID: string;
+ models: Record;
+ disabledModels: string[];
+ expectedPendingVersion: number;
+ };
signal: AbortSignal;
}): Promise => {
let terminalStreamError: Extract | null = null;
@@ -166,6 +173,7 @@ export function useChatRunStream({
}));
},
onDiscussionEvent: (event) => {
+ onDiscussionStreamEvent?.(event);
updatePendingExchange(exchangeKey, (current) => {
const discussion = applyDiscussionEvent(current.assistantDiscussion, event);
if (!discussion) {
@@ -289,6 +297,8 @@ export function useChatRunStream({
content,
templatePublicID: discussion.templatePublicID,
models: discussion.models,
+ disabledModels: discussion.disabledModels,
+ expectedPendingVersion: discussion.expectedPendingVersion,
clientRunID: commonStreamPayload.clientRunID,
parentMessagePublicID: commonStreamPayload.parentMessagePublicID,
sourceMessagePublicID: commonStreamPayload.sourceMessagePublicID,
@@ -364,6 +374,7 @@ export function useChatRunStream({
flushStreamTextNow,
flushUpstreamThinkNow,
onConversationRunFinished,
+ onDiscussionStreamEvent,
resetStreamBuffer,
setStreamTextSnapshot,
t,
diff --git a/apps/web/features/chat/hooks/use-chat-runtime.ts b/apps/web/features/chat/hooks/use-chat-runtime.ts
index c8264d20d..a8ee4c38d 100644
--- a/apps/web/features/chat/hooks/use-chat-runtime.ts
+++ b/apps/web/features/chat/hooks/use-chat-runtime.ts
@@ -11,6 +11,7 @@ import type {
ConversationOptions,
MessageDTO,
MessageUIStateInput,
+ StreamMessageEvent,
} from "@/shared/api/conversation-types";
import type { SkillSummaryDTO } from "@/shared/api/skills-types";
@@ -96,6 +97,9 @@ export function useChatRuntime({
modelOptions,
discussionTemplate,
discussionBindings,
+ discussionDisabledModels,
+ discussionExpectedPendingVersion,
+ onDiscussionStreamEvent,
selectedToolIDs,
selectedSkills,
selectedKnowledgeBaseIDs,
@@ -136,6 +140,9 @@ export function useChatRuntime({
modelOptions: ChatModelOption[];
discussionTemplate?: DiscussionTemplateDTO | null;
discussionBindings?: Record;
+ discussionDisabledModels?: string[];
+ discussionExpectedPendingVersion?: number;
+ onDiscussionStreamEvent?: (event: StreamMessageEvent) => void;
selectedToolIDs: number[];
selectedSkills: SkillSummaryDTO[];
selectedKnowledgeBaseIDs: string[];
@@ -219,6 +226,9 @@ export function useChatRuntime({
modelOptions,
discussionTemplate,
discussionBindings,
+ discussionDisabledModels,
+ discussionExpectedPendingVersion,
+ onDiscussionStreamEvent,
selectedToolIDs,
selectedSkills,
selectedKnowledgeBaseIDs,
diff --git a/apps/web/features/chat/hooks/use-chat-submit-stream.ts b/apps/web/features/chat/hooks/use-chat-submit-stream.ts
index 0c2c0d7e4..eccf641b6 100644
--- a/apps/web/features/chat/hooks/use-chat-submit-stream.ts
+++ b/apps/web/features/chat/hooks/use-chat-submit-stream.ts
@@ -15,6 +15,7 @@ import type {
ConversationOptions,
MessageDTO,
MessageUIStateInput,
+ StreamMessageEvent,
} from "@/shared/api/conversation-types";
import type { SkillSummaryDTO } from "@/shared/api/skills-types";
import type { DiscussionTemplateDTO } from "@/shared/api/discussion-types";
@@ -27,6 +28,9 @@ export function useChatSubmitStream({
modelOptions,
discussionTemplate,
discussionBindings,
+ discussionDisabledModels,
+ discussionExpectedPendingVersion,
+ onDiscussionStreamEvent,
selectedToolIDs,
selectedSkills,
selectedKnowledgeBaseIDs,
@@ -76,6 +80,9 @@ export function useChatSubmitStream({
modelOptions: ChatModelOption[];
discussionTemplate?: DiscussionTemplateDTO | null;
discussionBindings?: Record;
+ discussionDisabledModels?: string[];
+ discussionExpectedPendingVersion?: number;
+ onDiscussionStreamEvent?: (event: StreamMessageEvent) => void;
selectedToolIDs: number[];
selectedSkills: SkillSummaryDTO[];
selectedKnowledgeBaseIDs: string[];
@@ -130,6 +137,9 @@ export function useChatSubmitStream({
modelOptions,
discussionTemplate,
discussionBindings,
+ discussionDisabledModels,
+ discussionExpectedPendingVersion,
+ onDiscussionStreamEvent,
selectedToolIDs,
selectedSkills,
selectedKnowledgeBaseIDs,
diff --git a/apps/web/i18n/messages/en-US/chat.json b/apps/web/i18n/messages/en-US/chat.json
index c3e7691e3..c2b0ca24a 100644
--- a/apps/web/i18n/messages/en-US/chat.json
+++ b/apps/web/i18n/messages/en-US/chat.json
@@ -1220,6 +1220,25 @@
"debugHidePrompt": "Hide prompt",
"debugPromptFor": "Full prompt sent to {model}",
"debugSummaryPrompt": "Full prompt sent to the summary model",
- "debugPromptMissing": "No prompt recorded for this message (older run)"
+ "debugPromptMissing": "No prompt recorded for this message (older run)",
+ "enableModel": "Enable this discussion model",
+ "disableModel": "Temporarily disable this discussion model",
+ "lastModelRequired": "Keep at least one discussion model and one non-empty round",
+ "activeBadge": "Configuration locked",
+ "pendingBadge": "New configuration pending",
+ "refreshConfiguration": "Refresh discussion configuration",
+ "rollbackConfiguration": "Discard refresh",
+ "adoptConfiguration": "Use new configuration anyway",
+ "refreshAgainConfirm": "Refreshing again discards the current pending configuration. Click again to confirm",
+ "confirmRefresh": "Confirm refresh",
+ "cancelRefresh": "Cancel",
+ "refreshReady": "New configuration is ready and takes effect after a fully successful run",
+ "rollbackDone": "Restored the previous configuration",
+ "adoptDone": "New configuration adopted",
+ "pendingCommitted": "New configuration is now active",
+ "pendingNotCommitted": "The run was not fully successful; the new configuration is still pending",
+ "snapshotConflict": "Configuration changed in another tab. Reload this conversation and retry",
+ "snapshotLoadFailed": "Failed to load discussion configuration",
+ "snapshotActionFailed": "Discussion configuration operation failed; the active configuration is unchanged"
}
}
diff --git a/apps/web/i18n/messages/en-US/errors.json b/apps/web/i18n/messages/en-US/errors.json
index 01ebb386c..622396d96 100644
--- a/apps/web/i18n/messages/en-US/errors.json
+++ b/apps/web/i18n/messages/en-US/errors.json
@@ -164,6 +164,12 @@
"streamInterrupted": "The generation connection was interrupted. Retry this message.",
"streamNotFound": "Generation stream not found."
},
+ "discussion": {
+ "snapshotConflict": "The discussion configuration changed in another tab. Reload and retry.",
+ "pendingNotFound": "There is no pending discussion configuration to adopt.",
+ "noEnabledModels": "Keep at least one discussion model and one non-empty round.",
+ "summaryModelLocked": "The summary model cannot be disabled."
+ },
"conversationShare": {
"invalid": "Invalid conversation share.",
"invalidId": "Invalid share ID.",
diff --git a/apps/web/i18n/messages/zh-CN/chat.json b/apps/web/i18n/messages/zh-CN/chat.json
index 9de83f307..5164d5195 100644
--- a/apps/web/i18n/messages/zh-CN/chat.json
+++ b/apps/web/i18n/messages/zh-CN/chat.json
@@ -1220,6 +1220,25 @@
"debugHidePrompt": "收起 Prompt",
"debugPromptFor": "发送给 {model} 的完整 Prompt",
"debugSummaryPrompt": "总结模型收到的完整 Prompt",
- "debugPromptMissing": "该消息未记录 Prompt(旧版本生成)"
+ "debugPromptMissing": "该消息未记录 Prompt(旧版本生成)",
+ "enableModel": "启用此讨论模型",
+ "disableModel": "临时关闭此讨论模型",
+ "lastModelRequired": "至少保留一个讨论模型和一个非空轮次",
+ "activeBadge": "配置已固定",
+ "pendingBadge": "新配置待验证",
+ "refreshConfiguration": "刷新讨论配置",
+ "rollbackConfiguration": "撤回刷新",
+ "adoptConfiguration": "仍然采用新配置",
+ "refreshAgainConfirm": "再次刷新会丢弃当前待验证配置,请再次点击确认",
+ "confirmRefresh": "确认再次刷新",
+ "cancelRefresh": "取消",
+ "refreshReady": "新配置已就绪,下一次完整成功后生效",
+ "rollbackDone": "已撤回到原配置",
+ "adoptDone": "已采用新配置",
+ "pendingCommitted": "新配置已生效",
+ "pendingNotCommitted": "本次讨论未完整成功,新配置尚未生效",
+ "snapshotConflict": "配置已在其他标签页变化,请重新加载会话后重试",
+ "snapshotLoadFailed": "讨论配置加载失败",
+ "snapshotActionFailed": "讨论配置操作失败,当前生效配置未改变"
}
}
diff --git a/apps/web/i18n/messages/zh-CN/errors.json b/apps/web/i18n/messages/zh-CN/errors.json
index 2a0677640..869c7413c 100644
--- a/apps/web/i18n/messages/zh-CN/errors.json
+++ b/apps/web/i18n/messages/zh-CN/errors.json
@@ -164,6 +164,12 @@
"streamInterrupted": "生成连接已中断,请重试本条消息。",
"streamNotFound": "生成流不存在。"
},
+ "discussion": {
+ "snapshotConflict": "讨论配置已在其他标签页变化,请重新加载后重试。",
+ "pendingNotFound": "当前没有可采用的待验证讨论配置。",
+ "noEnabledModels": "至少保留一个讨论模型和一个非空轮次。",
+ "summaryModelLocked": "总结模型不能关闭。"
+ },
"conversationShare": {
"invalid": "分享对话无效。",
"invalidId": "分享 ID 无效。",
diff --git a/apps/web/shared/api/conversation-types.ts b/apps/web/shared/api/conversation-types.ts
index e3b443be2..a4ff5e60f 100644
--- a/apps/web/shared/api/conversation-types.ts
+++ b/apps/web/shared/api/conversation-types.ts
@@ -57,6 +57,7 @@ import type {
DiscussionPromptMessage,
DiscussionRuntimeRound,
DiscussionRuntimeSummary,
+ DiscussionSnapshotContent,
DiscussionState,
DiscussionTurn,
} from "@/shared/api/discussion-types";
@@ -450,6 +451,10 @@ export type StreamMessageEvent =
type: "discussion_done";
seq?: number;
state: DiscussionState;
+ snapshotCommitted?: boolean;
+ activeSnapshot?: DiscussionSnapshotContent | null;
+ activeVersion?: number;
+ pendingVersion?: number;
}
| {
type: "error";
diff --git a/apps/web/shared/api/discussion-types.ts b/apps/web/shared/api/discussion-types.ts
index 0d45b67f2..04c0863ad 100644
--- a/apps/web/shared/api/discussion-types.ts
+++ b/apps/web/shared/api/discussion-types.ts
@@ -99,6 +99,32 @@ export type DiscussionRuntimeSummary = {
prompt: string;
};
+export type DiscussionRuntimePlan = {
+ rounds: DiscussionRuntimeRound[];
+ summary: DiscussionRuntimeSummary;
+};
+
+export type DiscussionSnapshotContent = {
+ template: DiscussionTemplateDTO;
+ config: DiscussionTemplateConfig;
+ plan: DiscussionRuntimePlan;
+};
+
+export type DiscussionConversationSnapshot = {
+ templatePublicID: string;
+ active: DiscussionSnapshotContent | null;
+ activeVersion: number;
+ pending: DiscussionSnapshotContent | null;
+ pendingVersion: number;
+ pendingCreatedAt?: string;
+ updatedAt: string;
+};
+
+export type DiscussionSnapshotRequest = {
+ models?: Record;
+ expectedPendingVersion: number;
+};
+
export type DiscussionState = {
enabled: boolean;
status: string;
@@ -122,6 +148,8 @@ export type DiscussionSendRequest = {
content: string;
templatePublicID: string;
models: Record;
+ disabledModels?: string[];
+ expectedPendingVersion?: number;
clientRunID?: string;
parentMessagePublicID?: string;
sourceMessagePublicID?: string;
diff --git a/apps/web/shared/api/discussion.ts b/apps/web/shared/api/discussion.ts
index 5e3268651..1c486c59e 100644
--- a/apps/web/shared/api/discussion.ts
+++ b/apps/web/shared/api/discussion.ts
@@ -1,6 +1,8 @@
import { authedRequest } from "@/shared/api/authed-client";
import { pathParam } from "@/shared/api/http-client";
import type {
+ DiscussionConversationSnapshot,
+ DiscussionSnapshotRequest,
DiscussionTemplateDTO,
DiscussionTemplatePayload,
} from "@/shared/api/discussion-types";
@@ -67,3 +69,65 @@ export async function deleteAdminDiscussionTemplate(
true,
);
}
+
+type SnapshotResponse = { data: DiscussionConversationSnapshot };
+
+function discussionSnapshotPath(conversationPublicID: string, templatePublicID: string): string {
+ return `/api/v1/conversations/${pathParam(conversationPublicID)}/discussion-snapshots/${pathParam(templatePublicID)}`;
+}
+
+export async function getDiscussionSnapshot(
+ accessToken: string,
+ conversationPublicID: string,
+ templatePublicID: string,
+ signal?: AbortSignal,
+): Promise {
+ const data = await authedRequest(
+ discussionSnapshotPath(conversationPublicID, templatePublicID),
+ { accessToken, signal },
+ true,
+ );
+ return data.data;
+}
+
+async function mutateDiscussionSnapshot(
+ accessToken: string,
+ conversationPublicID: string,
+ templatePublicID: string,
+ action: "refresh" | "rollback" | "adopt",
+ payload: DiscussionSnapshotRequest,
+): Promise {
+ const data = await authedRequest(
+ `${discussionSnapshotPath(conversationPublicID, templatePublicID)}/${action}`,
+ { method: "POST", accessToken, body: payload },
+ true,
+ );
+ return data.data;
+}
+
+export function refreshDiscussionSnapshot(
+ accessToken: string,
+ conversationPublicID: string,
+ templatePublicID: string,
+ payload: DiscussionSnapshotRequest,
+): Promise {
+ return mutateDiscussionSnapshot(accessToken, conversationPublicID, templatePublicID, "refresh", payload);
+}
+
+export function rollbackDiscussionSnapshot(
+ accessToken: string,
+ conversationPublicID: string,
+ templatePublicID: string,
+ expectedPendingVersion: number,
+): Promise {
+ return mutateDiscussionSnapshot(accessToken, conversationPublicID, templatePublicID, "rollback", { expectedPendingVersion });
+}
+
+export function adoptDiscussionSnapshot(
+ accessToken: string,
+ conversationPublicID: string,
+ templatePublicID: string,
+ expectedPendingVersion: number,
+): Promise {
+ return mutateDiscussionSnapshot(accessToken, conversationPublicID, templatePublicID, "adopt", { expectedPendingVersion });
+}
diff --git a/apps/web/shared/lib/discussion.ts b/apps/web/shared/lib/discussion.ts
index 61214f117..d616c1de8 100644
--- a/apps/web/shared/lib/discussion.ts
+++ b/apps/web/shared/lib/discussion.ts
@@ -1,4 +1,9 @@
-import type { DiscussionPlaceholder, DiscussionRound } from "@/shared/api/discussion-types";
+import type {
+ DiscussionPlaceholder,
+ DiscussionRound,
+ DiscussionRuntimePlan,
+ DiscussionTemplateConfig,
+} from "@/shared/api/discussion-types";
const SUMMARY_PLACEHOLDER_LABEL = "总结模型";
@@ -71,3 +76,56 @@ export function discussionPlaceholderLabels(
}
return labels;
}
+
+export function discussionRuntimeBindings(plan: DiscussionRuntimePlan): Record {
+ const bindings: Record = {};
+ for (const round of plan.rounds ?? []) {
+ for (const step of round.steps ?? []) {
+ if (step.participant && step.model?.trim()) {
+ bindings[step.participant] = step.model.trim();
+ }
+ }
+ }
+ if (plan.summary?.participant && plan.summary.model?.trim()) {
+ bindings[plan.summary.participant] = plan.summary.model.trim();
+ }
+ return bindings;
+}
+
+export function hasEnabledDiscussionRound(
+ config: DiscussionTemplateConfig,
+ disabledModels: readonly string[],
+): boolean {
+ const disabled = new Set(disabledModels);
+ return config.rounds.some((round) => round.steps.some((step) => !disabled.has(step.participant)));
+}
+
+export function canDisableDiscussionModel(
+ config: DiscussionTemplateConfig,
+ participant: string,
+ disabledModels: readonly string[],
+): boolean {
+ if (participant === config.summary.participant || disabledModels.includes(participant)) {
+ return false;
+ }
+ const discussionModels = new Set(
+ config.placeholders
+ .map((item) => item.key)
+ .filter((key) => key !== config.summary.participant),
+ );
+ const enabledCount = [...discussionModels].filter((key) => !disabledModels.includes(key)).length;
+ return enabledCount > 1 && hasEnabledDiscussionRound(config, [...disabledModels, participant]);
+}
+
+export function discussionBindingsComplete(
+ config: DiscussionTemplateConfig,
+ bindings: Record,
+ disabledModels: readonly string[],
+): boolean {
+ const disabled = new Set(disabledModels);
+ return hasEnabledDiscussionRound(config, disabledModels)
+ && config.placeholders.every((placeholder) =>
+ (placeholder.key !== config.summary.participant && disabled.has(placeholder.key))
+ || Boolean(bindings[placeholder.key]?.trim()),
+ );
+}
diff --git a/backend/docs/docs.go b/backend/docs/docs.go
index 25f992194..55ddcc4dc 100644
--- a/backend/docs/docs.go
+++ b/backend/docs/docs.go
@@ -23216,6 +23216,17 @@ const docTemplate = `{
"markdown"
]
},
+ "disabledModels": {
+ "type": "array",
+ "maxItems": 12,
+ "items": {
+ "type": "string"
+ }
+ },
+ "expectedPendingVersion": {
+ "type": "integer",
+ "minimum": 0
+ },
"models": {
"type": "object",
"additionalProperties": {
diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json
index b44472e54..8985411bb 100644
--- a/backend/docs/swagger.json
+++ b/backend/docs/swagger.json
@@ -23209,6 +23209,17 @@
"markdown"
]
},
+ "disabledModels": {
+ "type": "array",
+ "maxItems": 12,
+ "items": {
+ "type": "string"
+ }
+ },
+ "expectedPendingVersion": {
+ "type": "integer",
+ "minimum": 0
+ },
"models": {
"type": "object",
"additionalProperties": {
diff --git a/backend/docs/swagger.yaml b/backend/docs/swagger.yaml
index e115f1a7a..d3ddcbd6e 100644
--- a/backend/docs/swagger.yaml
+++ b/backend/docs/swagger.yaml
@@ -3458,6 +3458,14 @@ definitions:
- text
- markdown
type: string
+ disabledModels:
+ items:
+ type: string
+ maxItems: 12
+ type: array
+ expectedPendingVersion:
+ minimum: 0
+ type: integer
models:
additionalProperties:
type: string
diff --git a/backend/internal/application/conversation/errs.go b/backend/internal/application/conversation/errs.go
index 91a4e80e5..415898067 100644
--- a/backend/internal/application/conversation/errs.go
+++ b/backend/internal/application/conversation/errs.go
@@ -14,6 +14,14 @@ import (
var (
// ErrConversationNotFound 会话不存在或无权限。
ErrConversationNotFound = apperr.New("conversation.not_found", "conversation not found")
+ // ErrDiscussionSnapshotConflict 多标签页或并发请求使用了过期的 pending 版本。
+ ErrDiscussionSnapshotConflict = apperr.NewMasked("discussion.snapshot_conflict", "discussion configuration changed; reload and retry", "discussion snapshot version conflict")
+ // ErrDiscussionPendingNotFound 当前没有可采用的待验证配置。
+ ErrDiscussionPendingNotFound = apperr.NewMasked("discussion.pending_not_found", "no pending discussion configuration", "discussion pending snapshot not found")
+ // ErrDiscussionNoEnabledModels 临时关闭后没有任何可执行轮次。
+ ErrDiscussionNoEnabledModels = apperr.NewMasked("discussion.no_enabled_models", "at least one discussion model must remain enabled", "discussion has no enabled models")
+ // ErrDiscussionSummaryModelLocked 总结节点必须保留。
+ ErrDiscussionSummaryModelLocked = apperr.NewMasked("discussion.summary_model_locked", "the summary model cannot be disabled", "discussion summary model cannot be disabled")
// ErrConversationEventNotFound 对话事件日志不存在。
ErrConversationEventNotFound = apperr.New("conversation_event.not_found", "conversation event not found")
// ErrToolCallNotFound 工具调用不存在或当前用户无权访问。
diff --git a/backend/internal/application/conversation/service_discussion.go b/backend/internal/application/conversation/service_discussion.go
index 1543b18ee..5e9bd9b6a 100644
--- a/backend/internal/application/conversation/service_discussion.go
+++ b/backend/internal/application/conversation/service_discussion.go
@@ -34,18 +34,20 @@ const (
// DiscussionSendInput 是讨论消息发送入参。
type DiscussionSendInput struct {
- UserID uint
- ConversationID uint
- RequestID string
- ContentType string
- Content string
- TemplatePublicID string
- ModelBindings map[string]string
- ParentMessagePublicID string
- SourceMessagePublicID string
- BranchReason string
- ClientRunID string
- OnEvent func(eventType string, payload map[string]any) error
+ UserID uint
+ ConversationID uint
+ RequestID string
+ ContentType string
+ Content string
+ TemplatePublicID string
+ ModelBindings map[string]string
+ DisabledModels []string
+ ExpectedPendingVersion int64
+ ParentMessagePublicID string
+ SourceMessagePublicID string
+ BranchReason string
+ ClientRunID string
+ OnEvent func(eventType string, payload map[string]any) error
}
// StreamDiscussionMessage 创建一轮讨论消息,并按模板编排模型调用。
@@ -56,13 +58,25 @@ func (s *Service) StreamDiscussionMessage(ctx context.Context, input DiscussionS
if s.routeResolver == nil || s.llmClient == nil {
return nil, ErrModelRouteNotConfigured
}
- template, cfg, plan, err := s.discussionTemplates.ResolvePlan(ctx, input.TemplatePublicID, input.ModelBindings)
+ conversation, err := s.repo.GetConversationByUser(ctx, input.ConversationID, input.UserID)
+ if err != nil {
+ return nil, ErrConversationNotFound
+ }
+ execution, err := s.resolveDiscussionExecution(ctx, input)
if err != nil {
return nil, err
}
- conversation, err := s.repo.GetConversationByUser(ctx, input.ConversationID, input.UserID)
+ template, cfg := execution.template, execution.config
+ fullPlan := execution.plan
+ plan, err := domaindiscussion.FilterDisabledModels(fullPlan, input.DisabledModels)
+ if errors.Is(err, domaindiscussion.ErrSummaryModelLocked) {
+ return nil, ErrDiscussionSummaryModelLocked
+ }
+ if errors.Is(err, domaindiscussion.ErrNoEnabledModels) {
+ return nil, ErrDiscussionNoEnabledModels
+ }
if err != nil {
- return nil, ErrConversationNotFound
+ return nil, err
}
startedAt := time.Now()
runID := normalizeRunID(input.ClientRunID)
@@ -169,7 +183,7 @@ func (s *Service) StreamDiscussionMessage(ctx context.Context, input DiscussionS
finalText := ""
summaryTurn := domaindiscussion.Turn{
- Round: len(plan.Rounds) + 1,
+ Round: domaindiscussion.SummaryRoundIndex(plan),
StepID: "summary",
Participant: plan.Summary.Participant,
Model: plan.Summary.Model,
@@ -196,8 +210,16 @@ func (s *Service) StreamDiscussionMessage(ctx context.Context, input DiscussionS
if ctx.Err() != nil {
state.Status = "stopped"
}
- if summaryTurn.Status == "error" && state.Status == "completed" {
- state.Status = "completed_with_errors"
+ if state.Status == "completed" {
+ for _, turn := range state.Turns {
+ if turn.Status == "error" {
+ state.Status = "completed_with_errors"
+ break
+ }
+ }
+ if summaryTurn.Status == "error" {
+ state.Status = "completed_with_errors"
+ }
}
stateJSON, _ := json.Marshal(discussionStatePayloadOf(state))
@@ -244,11 +266,40 @@ func (s *Service) StreamDiscussionMessage(ctx context.Context, input DiscussionS
pair.assistant.ErrorMessage = errorMessage
_ = s.repo.UpdateMessageState(ctx, pair.user.ID, "success", "", "")
+ snapshotCommitted := false
+ var activeSnapshot *domaindiscussion.Snapshot
+ var activeVersion, pendingVersion int64
+ if execution.snapshot != nil {
+ activeVersion = execution.snapshot.ActiveVersion
+ pendingVersion = execution.snapshot.PendingVersion
+ }
+ if state.Status == "completed" && execution.snapshotRepo != nil {
+ committedSnapshot, committed, commitErr := execution.snapshotRepo.CommitDiscussionSnapshot(ctx, input.ConversationID, input.TemplatePublicID, domaindiscussion.Snapshot{
+ Template: *template,
+ Config: cfg,
+ Plan: fullPlan,
+ }, execution.usePending, input.ExpectedPendingVersion)
+ if commitErr != nil {
+ return nil, mapDiscussionSnapshotError(commitErr)
+ }
+ snapshotCommitted = committed
+ if committedSnapshot != nil {
+ activeSnapshot = committedSnapshot.Active
+ activeVersion = committedSnapshot.ActiveVersion
+ pendingVersion = committedSnapshot.PendingVersion
+ }
+ }
if finalText != "" {
// The summary already streamed as discussion_summary_delta; this replaces the preview.
emit("delta", map[string]any{"delta": finalText, "replace": true})
}
- emit("discussion_done", map[string]any{"state": discussionStatePayloadOf(state)})
+ emit("discussion_done", map[string]any{
+ "state": discussionStatePayloadOf(state),
+ "snapshotCommitted": snapshotCommitted,
+ "activeVersion": activeVersion,
+ "pendingVersion": pendingVersion,
+ "activeSnapshot": discussionSnapshotContentPayloadOf(activeSnapshot),
+ })
return &SendMessageResult{
UserMessage: *pair.user,
AssistantMessage: *pair.assistant,
@@ -382,7 +433,7 @@ func (s *Service) runDiscussionSummary(
emit func(string, map[string]any),
) domaindiscussion.Turn {
turn := domaindiscussion.Turn{
- Round: len(plan.Rounds) + 1,
+ Round: domaindiscussion.SummaryRoundIndex(plan),
StepID: "summary",
Participant: plan.Summary.Participant,
Model: plan.Summary.Model,
diff --git a/backend/internal/application/conversation/service_discussion_payload.go b/backend/internal/application/conversation/service_discussion_payload.go
index 5b914c5c8..bf39dc248 100644
--- a/backend/internal/application/conversation/service_discussion_payload.go
+++ b/backend/internal/application/conversation/service_discussion_payload.go
@@ -175,3 +175,81 @@ func discussionStatePayloadOf(state domaindiscussion.State) discussionStatePaylo
UpdatedAt: state.UpdatedAt,
}
}
+
+func discussionTemplateConfigPayloadOf(config domaindiscussion.TemplateConfig) map[string]any {
+ rounds := make([]map[string]any, 0, len(config.Rounds))
+ for _, round := range config.Rounds {
+ steps := make([]map[string]any, 0, len(round.Steps))
+ for _, step := range round.Steps {
+ steps = append(steps, map[string]any{
+ "id": step.ID,
+ "participant": step.Participant,
+ "prompt": step.Prompt,
+ })
+ }
+ rounds = append(rounds, map[string]any{
+ "index": round.Index,
+ "parallel": round.IsParallel(),
+ "parallelPrompt": round.ParallelPrompt,
+ "serialPrompt": round.SerialPrompt,
+ "steps": steps,
+ })
+ }
+ return map[string]any{
+ "placeholders": discussionPlaceholdersPayloadOf(config.Placeholders),
+ "rounds": rounds,
+ "summary": map[string]any{
+ "participant": config.Summary.Participant,
+ "prompt": config.Summary.Prompt,
+ },
+ }
+}
+
+func discussionTemplatePayloadOf(template domaindiscussion.Template) map[string]any {
+ return map[string]any{
+ "id": template.ID,
+ "publicID": template.PublicID,
+ "name": template.Name,
+ "description": template.Description,
+ "icon": template.Icon,
+ "status": template.Status,
+ "maxRounds": template.MaxRounds,
+ "sortOrder": template.SortOrder,
+ "createdAt": template.CreatedAt,
+ "updatedAt": template.UpdatedAt,
+ }
+}
+
+func discussionRuntimePlanPayloadOf(plan domaindiscussion.RuntimePlan) map[string]any {
+ return map[string]any{
+ "rounds": discussionRoundsPayloadOf(plan.Rounds),
+ "summary": discussionSummaryPayloadOf(plan.Summary),
+ }
+}
+
+func discussionSnapshotContentPayloadOf(snapshot *domaindiscussion.Snapshot) any {
+ if snapshot == nil {
+ return nil
+ }
+ return map[string]any{
+ "template": discussionTemplatePayloadOf(snapshot.Template),
+ "config": discussionTemplateConfigPayloadOf(snapshot.Config),
+ "plan": discussionRuntimePlanPayloadOf(snapshot.Plan),
+ }
+}
+
+// DiscussionSnapshotPayloadOf 是快照 HTTP 响应与完成事件共用的传输映射。
+func DiscussionSnapshotPayloadOf(snapshot *domaindiscussion.ConversationSnapshot) any {
+ if snapshot == nil {
+ return nil
+ }
+ return map[string]any{
+ "templatePublicID": snapshot.TemplatePublicID,
+ "active": discussionSnapshotContentPayloadOf(snapshot.Active),
+ "activeVersion": snapshot.ActiveVersion,
+ "pending": discussionSnapshotContentPayloadOf(snapshot.Pending),
+ "pendingVersion": snapshot.PendingVersion,
+ "pendingCreatedAt": snapshot.PendingCreatedAt,
+ "updatedAt": snapshot.UpdatedAt,
+ }
+}
diff --git a/backend/internal/application/conversation/service_discussion_snapshot.go b/backend/internal/application/conversation/service_discussion_snapshot.go
new file mode 100644
index 000000000..9e87c27f2
--- /dev/null
+++ b/backend/internal/application/conversation/service_discussion_snapshot.go
@@ -0,0 +1,149 @@
+package conversation
+
+import (
+ "context"
+ "errors"
+
+ domaindiscussion "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/domain/discussion"
+ "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/repository"
+)
+
+type resolvedDiscussionExecution struct {
+ template *domaindiscussion.Template
+ config domaindiscussion.TemplateConfig
+ plan domaindiscussion.RuntimePlan
+ snapshot *domaindiscussion.ConversationSnapshot
+ snapshotRepo repository.DiscussionSnapshotRepository
+ usePending bool
+}
+
+func (s *Service) discussionSnapshotRepository() (repository.DiscussionSnapshotRepository, bool) {
+ repo, ok := s.repo.(repository.DiscussionSnapshotRepository)
+ return repo, ok && repo != nil
+}
+
+func (s *Service) GetDiscussionSnapshot(ctx context.Context, userID uint, conversationID uint, templatePublicID string) (*domaindiscussion.ConversationSnapshot, error) {
+ if _, err := s.repo.GetConversationByUser(ctx, conversationID, userID); err != nil {
+ return nil, ErrConversationNotFound
+ }
+ repo, ok := s.discussionSnapshotRepository()
+ if !ok {
+ return nil, nil
+ }
+ return repo.GetDiscussionSnapshot(ctx, conversationID, templatePublicID)
+}
+
+func (s *Service) RefreshDiscussionSnapshot(ctx context.Context, userID uint, conversationID uint, templatePublicID string, models map[string]string, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, error) {
+ if _, err := s.repo.GetConversationByUser(ctx, conversationID, userID); err != nil {
+ return nil, ErrConversationNotFound
+ }
+ repo, ok := s.discussionSnapshotRepository()
+ if !ok {
+ return nil, errors.New("discussion snapshot repository is not configured")
+ }
+ current, err := repo.GetDiscussionSnapshot(ctx, conversationID, templatePublicID)
+ if err != nil {
+ return nil, err
+ }
+ var basePlan domaindiscussion.RuntimePlan
+ if current != nil {
+ base := current.Active
+ if current.Pending != nil {
+ base = current.Pending
+ }
+ if base != nil {
+ basePlan = base.Plan
+ }
+ }
+ overrides := domaindiscussion.MergeBindings(basePlan, models)
+ template, config, plan, err := s.discussionTemplates.ResolvePlan(ctx, templatePublicID, overrides)
+ if err != nil {
+ return nil, err
+ }
+ pending := domaindiscussion.Snapshot{Template: *template, Config: config, Plan: plan}
+ return repo.RefreshDiscussionSnapshot(ctx, conversationID, templatePublicID, pending, expectedPendingVersion)
+}
+
+func (s *Service) RollbackDiscussionSnapshot(ctx context.Context, userID uint, conversationID uint, templatePublicID string, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, error) {
+ if _, err := s.repo.GetConversationByUser(ctx, conversationID, userID); err != nil {
+ return nil, ErrConversationNotFound
+ }
+ repo, ok := s.discussionSnapshotRepository()
+ if !ok {
+ return nil, errors.New("discussion snapshot repository is not configured")
+ }
+ return repo.RollbackDiscussionSnapshot(ctx, conversationID, templatePublicID, expectedPendingVersion)
+}
+
+func (s *Service) AdoptDiscussionSnapshot(ctx context.Context, userID uint, conversationID uint, templatePublicID string, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, error) {
+ if _, err := s.repo.GetConversationByUser(ctx, conversationID, userID); err != nil {
+ return nil, ErrConversationNotFound
+ }
+ repo, ok := s.discussionSnapshotRepository()
+ if !ok {
+ return nil, errors.New("discussion snapshot repository is not configured")
+ }
+ result, _, err := repo.CommitDiscussionSnapshot(ctx, conversationID, templatePublicID, domaindiscussion.Snapshot{}, true, expectedPendingVersion)
+ return result, err
+}
+
+func (s *Service) resolveDiscussionExecution(ctx context.Context, input DiscussionSendInput) (*resolvedDiscussionExecution, error) {
+ repo, supported := s.discussionSnapshotRepository()
+ if !supported {
+ template, config, plan, err := s.discussionTemplates.ResolvePlan(ctx, input.TemplatePublicID, input.ModelBindings)
+ if err != nil {
+ return nil, err
+ }
+ return &resolvedDiscussionExecution{template: template, config: config, plan: plan}, nil
+ }
+ snapshot, err := repo.GetDiscussionSnapshot(ctx, input.ConversationID, input.TemplatePublicID)
+ if err != nil {
+ return nil, err
+ }
+ if snapshot != nil && snapshot.Pending != nil {
+ if input.ExpectedPendingVersion != snapshot.PendingVersion {
+ return nil, ErrDiscussionSnapshotConflict
+ }
+ pending := *snapshot.Pending
+ plan, err := domaindiscussion.ResolveRuntimePlan(pending.Config, domaindiscussion.MergeBindings(pending.Plan, input.ModelBindings))
+ if err != nil {
+ return nil, err
+ }
+ pending.Plan = plan
+ snapshot, err = repo.UpdateDiscussionSnapshotPending(ctx, input.ConversationID, input.TemplatePublicID, pending, input.ExpectedPendingVersion)
+ if err != nil {
+ return nil, mapDiscussionSnapshotError(err)
+ }
+ template := pending.Template
+ return &resolvedDiscussionExecution{
+ template: &template, config: pending.Config, plan: plan, snapshot: snapshot,
+ snapshotRepo: repo, usePending: true,
+ }, nil
+ }
+ if input.ExpectedPendingVersion != 0 {
+ return nil, ErrDiscussionSnapshotConflict
+ }
+ if snapshot != nil && snapshot.Active != nil {
+ active := *snapshot.Active
+ template := active.Template
+ return &resolvedDiscussionExecution{
+ template: &template, config: active.Config, plan: active.Plan, snapshot: snapshot, snapshotRepo: repo,
+ }, nil
+ }
+ template, config, plan, err := s.discussionTemplates.ResolvePlan(ctx, input.TemplatePublicID, input.ModelBindings)
+ if err != nil {
+ return nil, err
+ }
+ return &resolvedDiscussionExecution{template: template, config: config, plan: plan, snapshot: snapshot, snapshotRepo: repo}, nil
+}
+
+func mapDiscussionSnapshotError(err error) error {
+ switch {
+ case errors.Is(err, domaindiscussion.ErrSnapshotConflict):
+ return ErrDiscussionSnapshotConflict
+ case errors.Is(err, domaindiscussion.ErrPendingNotFound):
+ return ErrDiscussionPendingNotFound
+ default:
+ return err
+ }
+}
diff --git a/backend/internal/application/conversation/service_discussion_snapshot_test.go b/backend/internal/application/conversation/service_discussion_snapshot_test.go
new file mode 100644
index 000000000..221bff627
--- /dev/null
+++ b/backend/internal/application/conversation/service_discussion_snapshot_test.go
@@ -0,0 +1,167 @@
+package conversation
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+
+ model "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/domain/conversation"
+ domaindiscussion "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/domain/discussion"
+ "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/repository"
+)
+
+type discussionSnapshotServiceRepoStub struct {
+ repository.ConversationRepository
+ snapshot *domaindiscussion.ConversationSnapshot
+}
+
+func (r *discussionSnapshotServiceRepoStub) GetConversationByUser(context.Context, uint, uint) (*model.Conversation, error) {
+ return &model.Conversation{ID: 1, UserID: 2}, nil
+}
+
+func (r *discussionSnapshotServiceRepoStub) GetDiscussionSnapshot(context.Context, uint, string) (*domaindiscussion.ConversationSnapshot, error) {
+ return r.snapshot, nil
+}
+
+func (r *discussionSnapshotServiceRepoStub) RefreshDiscussionSnapshot(_ context.Context, _ uint, _ string, pending domaindiscussion.Snapshot, expected int64) (*domaindiscussion.ConversationSnapshot, error) {
+ if r.snapshot == nil {
+ r.snapshot = &domaindiscussion.ConversationSnapshot{}
+ }
+ if r.snapshot.PendingVersion != expected {
+ return nil, domaindiscussion.ErrSnapshotConflict
+ }
+ r.snapshot.Pending = &pending
+ r.snapshot.PendingVersion++
+ return r.snapshot, nil
+}
+
+func (r *discussionSnapshotServiceRepoStub) UpdateDiscussionSnapshotPending(_ context.Context, _ uint, _ string, pending domaindiscussion.Snapshot, expected int64) (*domaindiscussion.ConversationSnapshot, error) {
+ if r.snapshot == nil || r.snapshot.Pending == nil || r.snapshot.PendingVersion != expected {
+ return nil, domaindiscussion.ErrSnapshotConflict
+ }
+ r.snapshot.Pending = &pending
+ return r.snapshot, nil
+}
+
+func (r *discussionSnapshotServiceRepoStub) RollbackDiscussionSnapshot(context.Context, uint, string, int64) (*domaindiscussion.ConversationSnapshot, error) {
+ return r.snapshot, nil
+}
+
+func (r *discussionSnapshotServiceRepoStub) CommitDiscussionSnapshot(context.Context, uint, string, domaindiscussion.Snapshot, bool, int64) (*domaindiscussion.ConversationSnapshot, bool, error) {
+ return r.snapshot, false, nil
+}
+
+type discussionTemplateProviderStub struct {
+ template domaindiscussion.Template
+ config domaindiscussion.TemplateConfig
+ calls int
+}
+
+func (p *discussionTemplateProviderStub) ResolvePlan(_ context.Context, _ string, overrides map[string]string) (*domaindiscussion.Template, domaindiscussion.TemplateConfig, domaindiscussion.RuntimePlan, error) {
+ p.calls++
+ plan, err := domaindiscussion.ResolveRuntimePlan(p.config, overrides)
+ return &p.template, p.config, plan, err
+}
+
+func discussionSnapshotServiceFixture(model string) domaindiscussion.Snapshot {
+ config := domaindiscussion.TemplateConfig{
+ Placeholders: []domaindiscussion.Placeholder{{Key: "p1", DefaultModel: model}},
+ Rounds: []domaindiscussion.Round{{Index: 1, Steps: []domaindiscussion.Step{{ID: "s1", Participant: "p1"}}}},
+ Summary: domaindiscussion.Summary{Participant: "p1"},
+ }
+ plan, _ := domaindiscussion.ResolveRuntimePlan(config, nil)
+ return domaindiscussion.Snapshot{
+ Template: domaindiscussion.Template{PublicID: "tpl", Name: "snapshot"},
+ Config: config,
+ Plan: plan,
+ }
+}
+
+func TestResolveDiscussionExecutionIgnoresBindingsForActiveSnapshot(t *testing.T) {
+ active := discussionSnapshotServiceFixture("model-pinned")
+ repo := &discussionSnapshotServiceRepoStub{snapshot: &domaindiscussion.ConversationSnapshot{Active: &active, ActiveVersion: 1}}
+ provider := &discussionTemplateProviderStub{}
+ service := &Service{repo: repo, discussionTemplates: provider}
+ execution, err := service.resolveDiscussionExecution(context.Background(), DiscussionSendInput{
+ ConversationID: 1, UserID: 2, TemplatePublicID: "tpl", ModelBindings: map[string]string{"p1": "model-new"},
+ })
+ if err != nil {
+ t.Fatalf("resolve active: %v", err)
+ }
+ if execution.plan.Summary.Model != "model-pinned" || execution.usePending {
+ t.Fatalf("active snapshot was not pinned: %#v", execution.plan)
+ }
+ if provider.calls != 0 {
+ t.Fatalf("live template was resolved %d times", provider.calls)
+ }
+}
+
+func TestResolveDiscussionExecutionUpdatesPendingAndChecksVersion(t *testing.T) {
+ pending := discussionSnapshotServiceFixture("model-old")
+ repo := &discussionSnapshotServiceRepoStub{snapshot: &domaindiscussion.ConversationSnapshot{Pending: &pending, PendingVersion: 4}}
+ service := &Service{repo: repo, discussionTemplates: &discussionTemplateProviderStub{}}
+ _, err := service.resolveDiscussionExecution(context.Background(), DiscussionSendInput{TemplatePublicID: "tpl", ExpectedPendingVersion: 3})
+ if !errors.Is(err, ErrDiscussionSnapshotConflict) {
+ t.Fatalf("expected version conflict, got %v", err)
+ }
+ execution, err := service.resolveDiscussionExecution(context.Background(), DiscussionSendInput{
+ TemplatePublicID: "tpl", ExpectedPendingVersion: 4, ModelBindings: map[string]string{"p1": "model-new"},
+ })
+ if err != nil {
+ t.Fatalf("resolve pending: %v", err)
+ }
+ if !execution.usePending || execution.plan.Summary.Model != "model-new" || repo.snapshot.Pending.Plan.Summary.Model != "model-new" {
+ t.Fatalf("pending binding was not applied: %#v", execution.plan)
+ }
+}
+
+func TestRefreshDiscussionSnapshotKeepsExistingAndDefaultsNewBindings(t *testing.T) {
+ active := discussionSnapshotServiceFixture("model-pinned")
+ repo := &discussionSnapshotServiceRepoStub{snapshot: &domaindiscussion.ConversationSnapshot{Active: &active, ActiveVersion: 1}}
+ provider := &discussionTemplateProviderStub{
+ template: domaindiscussion.Template{PublicID: "tpl", Name: "latest"},
+ config: domaindiscussion.TemplateConfig{
+ Placeholders: []domaindiscussion.Placeholder{{Key: "p1", DefaultModel: "model-latest"}, {Key: "p2", DefaultModel: "model-new-default"}},
+ Rounds: []domaindiscussion.Round{{Index: 1, Steps: []domaindiscussion.Step{{ID: "s1", Participant: "p1"}, {ID: "s2", Participant: "p2"}}}},
+ Summary: domaindiscussion.Summary{Participant: "p1"},
+ },
+ }
+ service := &Service{repo: repo, discussionTemplates: provider}
+ current, err := service.RefreshDiscussionSnapshot(context.Background(), 2, 1, "tpl", nil, 0)
+ if err != nil {
+ t.Fatalf("refresh: %v", err)
+ }
+ bindings := domaindiscussion.PlanBindings(current.Pending.Plan)
+ if bindings["p1"] != "model-pinned" || bindings["p2"] != "model-new-default" {
+ t.Fatalf("unexpected refreshed bindings: %#v", bindings)
+ }
+ if current.Active.Plan.Summary.Model != "model-pinned" || current.PendingVersion != 1 {
+ t.Fatalf("refresh changed active: %#v", current)
+ }
+}
+
+func TestDiscussionSnapshotPayloadUsesCamelCase(t *testing.T) {
+ active := discussionSnapshotServiceFixture("model-a")
+ active.Config.Rounds[0].ParallelPrompt = "parallel prompt"
+ encoded, err := json.Marshal(DiscussionSnapshotPayloadOf(&domaindiscussion.ConversationSnapshot{
+ TemplatePublicID: "tpl",
+ Active: &active,
+ ActiveVersion: 2,
+ }))
+ if err != nil {
+ t.Fatalf("marshal snapshot payload: %v", err)
+ }
+ text := string(encoded)
+ for _, key := range []string{`"templatePublicID"`, `"activeVersion"`, `"template"`, `"config"`, `"plan"`, `"publicID"`, `"parallelPrompt"`, `"summary"`} {
+ if !strings.Contains(text, key) {
+ t.Fatalf("missing %s in %s", key, text)
+ }
+ }
+ for _, key := range []string{`"TemplatePublicID"`, `"Template"`, `"Config"`, `"Plan"`, `"PublicID"`} {
+ if strings.Contains(text, key) {
+ t.Fatalf("domain key %s leaked into %s", key, text)
+ }
+ }
+}
diff --git a/backend/internal/domain/discussion/snapshot.go b/backend/internal/domain/discussion/snapshot.go
new file mode 100644
index 000000000..144c3f4bd
--- /dev/null
+++ b/backend/internal/domain/discussion/snapshot.go
@@ -0,0 +1,101 @@
+package discussion
+
+import (
+ "errors"
+ "strings"
+ "time"
+)
+
+var (
+ ErrSnapshotConflict = errors.New("discussion snapshot version conflict")
+ ErrPendingNotFound = errors.New("discussion pending snapshot not found")
+ ErrNoEnabledModels = errors.New("discussion has no enabled models")
+ ErrSummaryModelLocked = errors.New("discussion summary model cannot be disabled")
+)
+
+// Snapshot 包含一次成功讨论所需的完整模板与绑定,不再依赖后台模板的后续状态。
+type Snapshot struct {
+ Template Template
+ Config TemplateConfig
+ Plan RuntimePlan
+}
+
+// ConversationSnapshot 按会话和模板分别保存已生效配置与一级待验证配置。
+type ConversationSnapshot struct {
+ ConversationID uint
+ TemplatePublicID string
+ Active *Snapshot
+ ActiveVersion int64
+ Pending *Snapshot
+ PendingVersion int64
+ PendingCreatedAt *time.Time
+ UpdatedAt time.Time
+}
+
+// PlanBindings 提取完整计划中的占位符绑定;过滤临时关闭模型之前调用。
+func PlanBindings(plan RuntimePlan) map[string]string {
+ bindings := make(map[string]string)
+ for _, round := range plan.Rounds {
+ for _, step := range round.Steps {
+ if step.Participant != "" && strings.TrimSpace(step.Model) != "" {
+ bindings[step.Participant] = strings.TrimSpace(step.Model)
+ }
+ }
+ }
+ if plan.Summary.Participant != "" && strings.TrimSpace(plan.Summary.Model) != "" {
+ bindings[plan.Summary.Participant] = strings.TrimSpace(plan.Summary.Model)
+ }
+ return bindings
+}
+
+// MergeBindings 以当前快照绑定为基底,仅覆盖本次明确修改的占位符。
+func MergeBindings(plan RuntimePlan, overrides map[string]string) map[string]string {
+ bindings := PlanBindings(plan)
+ for participant, model := range overrides {
+ if strings.TrimSpace(model) != "" {
+ bindings[participant] = strings.TrimSpace(model)
+ }
+ }
+ return bindings
+}
+
+// FilterDisabledModels 只过滤本次执行,不修改持久化快照;空轮次保留原编号后整体跳过。
+func FilterDisabledModels(plan RuntimePlan, disabled []string) (RuntimePlan, error) {
+ blocked := make(map[string]struct{}, len(disabled))
+ for _, participant := range disabled {
+ participant = strings.TrimSpace(participant)
+ if participant != "" {
+ blocked[participant] = struct{}{}
+ }
+ }
+ if _, ok := blocked[plan.Summary.Participant]; ok {
+ return RuntimePlan{}, ErrSummaryModelLocked
+ }
+ filtered := RuntimePlan{Summary: plan.Summary, Rounds: make([]RuntimeRound, 0, len(plan.Rounds))}
+ for _, round := range plan.Rounds {
+ next := RuntimeRound{Index: round.Index, Parallel: round.Parallel, Steps: make([]RuntimeStep, 0, len(round.Steps))}
+ for _, step := range round.Steps {
+ if _, ok := blocked[step.Participant]; !ok {
+ next.Steps = append(next.Steps, step)
+ }
+ }
+ if len(next.Steps) > 0 {
+ filtered.Rounds = append(filtered.Rounds, next)
+ }
+ }
+ if len(filtered.Rounds) == 0 {
+ return RuntimePlan{}, ErrNoEnabledModels
+ }
+ return filtered, nil
+}
+
+// SummaryRoundIndex 在跳过空轮后仍保证总结节点排在所有原始轮次之后。
+func SummaryRoundIndex(plan RuntimePlan) int {
+ index := 1
+ for _, round := range plan.Rounds {
+ if round.Index >= index {
+ index = round.Index + 1
+ }
+ }
+ return index
+}
diff --git a/backend/internal/domain/discussion/snapshot_test.go b/backend/internal/domain/discussion/snapshot_test.go
new file mode 100644
index 000000000..f95ea3dcb
--- /dev/null
+++ b/backend/internal/domain/discussion/snapshot_test.go
@@ -0,0 +1,75 @@
+package discussion
+
+import (
+ "errors"
+ "reflect"
+ "testing"
+)
+
+func filterTestPlan() RuntimePlan {
+ return RuntimePlan{
+ Rounds: []RuntimeRound{
+ {Index: 1, Steps: []RuntimeStep{{ID: "r1s1", Participant: "p1", Model: "model-a"}, {ID: "r1s2", Participant: "p2", Model: "model-b"}}},
+ {Index: 2, Steps: []RuntimeStep{{ID: "r2s1", Participant: "p2", Model: "model-b"}}},
+ {Index: 3, Steps: []RuntimeStep{{ID: "r3s1", Participant: "p1", Model: "model-a"}}},
+ },
+ Summary: RuntimeSummary{Participant: "judge", Model: "model-judge"},
+ }
+}
+
+func TestFilterDisabledModelsSkipsEmptyRoundAndKeepsIndexes(t *testing.T) {
+ plan := filterTestPlan()
+ filtered, err := FilterDisabledModels(plan, []string{"p2"})
+ if err != nil {
+ t.Fatalf("FilterDisabledModels: %v", err)
+ }
+ if len(filtered.Rounds) != 2 || filtered.Rounds[0].Index != 1 || filtered.Rounds[1].Index != 3 {
+ t.Fatalf("unexpected rounds: %#v", filtered.Rounds)
+ }
+ if len(filtered.Rounds[0].Steps) != 1 || filtered.Rounds[0].Steps[0].Participant != "p1" {
+ t.Fatalf("disabled participant was not filtered: %#v", filtered.Rounds[0].Steps)
+ }
+ if filtered.Summary.Model != "model-judge" {
+ t.Fatalf("summary changed: %#v", filtered.Summary)
+ }
+ if len(plan.Rounds) != 3 || len(plan.Rounds[0].Steps) != 2 {
+ t.Fatal("filter mutated the full snapshot plan")
+ }
+}
+
+func TestFilterDisabledModelsRejectsEmptyExecutionAndSummary(t *testing.T) {
+ plan := filterTestPlan()
+ if _, err := FilterDisabledModels(plan, []string{"p1", "p2"}); !errors.Is(err, ErrNoEnabledModels) {
+ t.Fatalf("expected no enabled models, got %v", err)
+ }
+ if _, err := FilterDisabledModels(plan, []string{"judge"}); !errors.Is(err, ErrSummaryModelLocked) {
+ t.Fatalf("expected summary lock, got %v", err)
+ }
+}
+
+func TestPlanBindingsIncludesSummaryAndMergeOverrides(t *testing.T) {
+ plan := filterTestPlan()
+ bindings := PlanBindings(plan)
+ want := map[string]string{"p1": "model-a", "p2": "model-b", "judge": "model-judge"}
+ if !reflect.DeepEqual(bindings, want) {
+ t.Fatalf("bindings = %#v, want %#v", bindings, want)
+ }
+ merged := MergeBindings(plan, map[string]string{"p2": " model-new ", "p1": ""})
+ if merged["p2"] != "model-new" || merged["p1"] != "model-a" || merged["judge"] != "model-judge" {
+ t.Fatalf("unexpected merged bindings: %#v", merged)
+ }
+}
+
+func TestSummaryRoundIndexUsesOriginalRoundNumbers(t *testing.T) {
+ plan := filterTestPlan()
+ if _, err := FilterDisabledModels(plan, []string{"p1", "p2"}); !errors.Is(err, ErrNoEnabledModels) {
+ t.Fatalf("unexpected filter result: %v", err)
+ }
+ filtered, err := FilterDisabledModels(plan, []string{"p2"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := SummaryRoundIndex(filtered); got != 4 {
+ t.Fatalf("summary round = %d, want 4", got)
+ }
+}
diff --git a/backend/internal/infra/persistence/models/chat.go b/backend/internal/infra/persistence/models/chat.go
index ceda7e844..35107702d 100644
--- a/backend/internal/infra/persistence/models/chat.go
+++ b/backend/internal/infra/persistence/models/chat.go
@@ -29,6 +29,23 @@ func (Conversation) TableName() string {
return "chat_conversations"
}
+// ConversationDiscussionSnapshot 保存会话在某个讨论模板下已生效和待验证的完整配置。
+type ConversationDiscussionSnapshot struct {
+ BaseModel
+ ConversationID uint `gorm:"not null;uniqueIndex:idx_chat_discussion_snapshot_scope,priority:1;comment:会话ID"`
+ TemplatePublicID string `gorm:"size:32;not null;uniqueIndex:idx_chat_discussion_snapshot_scope,priority:2;comment:讨论模板公开ID"`
+ ActiveSnapshotJSON string `gorm:"type:text;not null;default:'';comment:已生效讨论配置JSON"`
+ ActiveVersion int64 `gorm:"not null;default:0;comment:已生效配置版本"`
+ PendingSnapshotJSON string `gorm:"type:text;not null;default:'';comment:待验证讨论配置JSON"`
+ PendingVersion int64 `gorm:"not null;default:0;comment:待验证配置版本"`
+ PendingCreatedAt *time.Time `gorm:"comment:待验证配置创建时间"`
+}
+
+// TableName 指定表名。
+func (ConversationDiscussionSnapshot) TableName() string {
+ return "chat_conversation_discussion_snapshots"
+}
+
// ConversationProject 存储用户会话项目分组。
type ConversationProject struct {
BaseModel
diff --git a/backend/internal/infra/persistence/postgres/conversation/repository_discussion_snapshot.go b/backend/internal/infra/persistence/postgres/conversation/repository_discussion_snapshot.go
new file mode 100644
index 000000000..196b9c3e1
--- /dev/null
+++ b/backend/internal/infra/persistence/postgres/conversation/repository_discussion_snapshot.go
@@ -0,0 +1,270 @@
+package conversation
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "time"
+
+ domaindiscussion "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/domain/discussion"
+ "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/infra/persistence/models"
+ "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/repository"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+func encodeDiscussionSnapshot(snapshot *domaindiscussion.Snapshot) (string, error) {
+ if snapshot == nil {
+ return "", nil
+ }
+ raw, err := json.Marshal(snapshot)
+ return string(raw), err
+}
+
+func decodeDiscussionSnapshot(raw string) (*domaindiscussion.Snapshot, error) {
+ if strings.TrimSpace(raw) == "" {
+ return nil, nil
+ }
+ var snapshot domaindiscussion.Snapshot
+ if err := json.Unmarshal([]byte(raw), &snapshot); err != nil {
+ return nil, err
+ }
+ return &snapshot, nil
+}
+
+func toDiscussionSnapshotDomain(entity models.ConversationDiscussionSnapshot) (*domaindiscussion.ConversationSnapshot, error) {
+ active, err := decodeDiscussionSnapshot(entity.ActiveSnapshotJSON)
+ if err != nil {
+ return nil, err
+ }
+ pending, err := decodeDiscussionSnapshot(entity.PendingSnapshotJSON)
+ if err != nil {
+ return nil, err
+ }
+ return &domaindiscussion.ConversationSnapshot{
+ ConversationID: entity.ConversationID,
+ TemplatePublicID: entity.TemplatePublicID,
+ Active: active,
+ ActiveVersion: entity.ActiveVersion,
+ Pending: pending,
+ PendingVersion: entity.PendingVersion,
+ PendingCreatedAt: entity.PendingCreatedAt,
+ UpdatedAt: entity.UpdatedAt,
+ }, nil
+}
+
+func findDiscussionSnapshot(tx *gorm.DB, conversationID uint, templatePublicID string, lock bool) (*models.ConversationDiscussionSnapshot, error) {
+ var entity models.ConversationDiscussionSnapshot
+ query := tx.Where("conversation_id = ? AND template_public_id = ?", conversationID, templatePublicID)
+ if lock {
+ query = query.Clauses(clause.Locking{Strength: "UPDATE"})
+ }
+ if err := query.First(&entity).Error; err != nil {
+ return nil, err
+ }
+ return &entity, nil
+}
+
+func nextDiscussionSnapshotVersion(entity models.ConversationDiscussionSnapshot) int64 {
+ if entity.PendingVersion > entity.ActiveVersion {
+ return entity.PendingVersion + 1
+ }
+ return entity.ActiveVersion + 1
+}
+
+func validatePendingVersion(entity models.ConversationDiscussionSnapshot, expected int64) error {
+ if entity.PendingSnapshotJSON == "" {
+ if expected == 0 {
+ return nil
+ }
+ return domaindiscussion.ErrSnapshotConflict
+ }
+ if expected != entity.PendingVersion {
+ return domaindiscussion.ErrSnapshotConflict
+ }
+ return nil
+}
+
+func translateDiscussionSnapshotCreateError(err error) error {
+ translated := translateError(err)
+ if errors.Is(translated, repository.ErrDuplicate) {
+ return domaindiscussion.ErrSnapshotConflict
+ }
+ return translated
+}
+
+func (r *Repo) GetDiscussionSnapshot(ctx context.Context, conversationID uint, templatePublicID string) (*domaindiscussion.ConversationSnapshot, error) {
+ entity, err := findDiscussionSnapshot(r.db.WithContext(ctx), conversationID, templatePublicID, false)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, translateError(err)
+ }
+ return toDiscussionSnapshotDomain(*entity)
+}
+
+func (r *Repo) RefreshDiscussionSnapshot(ctx context.Context, conversationID uint, templatePublicID string, pending domaindiscussion.Snapshot, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, error) {
+ var result *domaindiscussion.ConversationSnapshot
+ err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ entity, err := findDiscussionSnapshot(tx, conversationID, templatePublicID, true)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ if expectedPendingVersion != 0 {
+ return domaindiscussion.ErrSnapshotConflict
+ }
+ now := time.Now()
+ raw, encodeErr := encodeDiscussionSnapshot(&pending)
+ if encodeErr != nil {
+ return encodeErr
+ }
+ entity = &models.ConversationDiscussionSnapshot{
+ ConversationID: conversationID,
+ TemplatePublicID: templatePublicID,
+ PendingSnapshotJSON: raw,
+ PendingVersion: 1,
+ PendingCreatedAt: &now,
+ }
+ if err = tx.Create(entity).Error; err != nil {
+ return translateDiscussionSnapshotCreateError(err)
+ }
+ } else if err != nil {
+ return translateError(err)
+ } else {
+ if err = validatePendingVersion(*entity, expectedPendingVersion); err != nil {
+ return err
+ }
+ raw, encodeErr := encodeDiscussionSnapshot(&pending)
+ if encodeErr != nil {
+ return encodeErr
+ }
+ now := time.Now()
+ entity.PendingSnapshotJSON = raw
+ entity.PendingVersion = nextDiscussionSnapshotVersion(*entity)
+ entity.PendingCreatedAt = &now
+ if err = tx.Save(entity).Error; err != nil {
+ return translateError(err)
+ }
+ }
+ result, err = toDiscussionSnapshotDomain(*entity)
+ return err
+ })
+ return result, err
+}
+
+func (r *Repo) UpdateDiscussionSnapshotPending(ctx context.Context, conversationID uint, templatePublicID string, pending domaindiscussion.Snapshot, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, error) {
+ var result *domaindiscussion.ConversationSnapshot
+ err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ entity, err := findDiscussionSnapshot(tx, conversationID, templatePublicID, true)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return domaindiscussion.ErrPendingNotFound
+ }
+ if err != nil {
+ return translateError(err)
+ }
+ if err = validatePendingVersion(*entity, expectedPendingVersion); err != nil {
+ return err
+ }
+ if entity.PendingSnapshotJSON == "" {
+ return domaindiscussion.ErrPendingNotFound
+ }
+ raw, err := encodeDiscussionSnapshot(&pending)
+ if err != nil {
+ return err
+ }
+ entity.PendingSnapshotJSON = raw
+ if err = tx.Model(entity).Update("pending_snapshot_json", raw).Error; err != nil {
+ return translateError(err)
+ }
+ result, err = toDiscussionSnapshotDomain(*entity)
+ return err
+ })
+ return result, err
+}
+
+func (r *Repo) RollbackDiscussionSnapshot(ctx context.Context, conversationID uint, templatePublicID string, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, error) {
+ var result *domaindiscussion.ConversationSnapshot
+ err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ entity, err := findDiscussionSnapshot(tx, conversationID, templatePublicID, true)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ if expectedPendingVersion == 0 {
+ return nil
+ }
+ return domaindiscussion.ErrSnapshotConflict
+ }
+ if err != nil {
+ return translateError(err)
+ }
+ if err = validatePendingVersion(*entity, expectedPendingVersion); err != nil {
+ return err
+ }
+ entity.PendingSnapshotJSON = ""
+ entity.PendingVersion = 0
+ entity.PendingCreatedAt = nil
+ if err = tx.Save(entity).Error; err != nil {
+ return translateError(err)
+ }
+ result, err = toDiscussionSnapshotDomain(*entity)
+ return err
+ })
+ return result, err
+}
+
+func (r *Repo) CommitDiscussionSnapshot(ctx context.Context, conversationID uint, templatePublicID string, snapshot domaindiscussion.Snapshot, usePending bool, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, bool, error) {
+ var result *domaindiscussion.ConversationSnapshot
+ committed := false
+ err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ entity, err := findDiscussionSnapshot(tx, conversationID, templatePublicID, true)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ if usePending {
+ return domaindiscussion.ErrPendingNotFound
+ }
+ raw, encodeErr := encodeDiscussionSnapshot(&snapshot)
+ if encodeErr != nil {
+ return encodeErr
+ }
+ entity = &models.ConversationDiscussionSnapshot{
+ ConversationID: conversationID,
+ TemplatePublicID: templatePublicID,
+ ActiveSnapshotJSON: raw,
+ ActiveVersion: 1,
+ }
+ if err = tx.Create(entity).Error; err != nil {
+ return translateDiscussionSnapshotCreateError(err)
+ }
+ committed = true
+ } else if err != nil {
+ return translateError(err)
+ } else if usePending {
+ if entity.PendingSnapshotJSON == "" {
+ return domaindiscussion.ErrPendingNotFound
+ }
+ if err = validatePendingVersion(*entity, expectedPendingVersion); err != nil {
+ return err
+ }
+ entity.ActiveSnapshotJSON = entity.PendingSnapshotJSON
+ entity.ActiveVersion = nextDiscussionSnapshotVersion(*entity)
+ entity.PendingSnapshotJSON = ""
+ entity.PendingVersion = 0
+ entity.PendingCreatedAt = nil
+ if err = tx.Save(entity).Error; err != nil {
+ return translateError(err)
+ }
+ committed = true
+ } else if entity.ActiveSnapshotJSON == "" {
+ raw, encodeErr := encodeDiscussionSnapshot(&snapshot)
+ if encodeErr != nil {
+ return encodeErr
+ }
+ entity.ActiveSnapshotJSON = raw
+ entity.ActiveVersion = nextDiscussionSnapshotVersion(*entity)
+ if err = tx.Save(entity).Error; err != nil {
+ return translateError(err)
+ }
+ committed = true
+ }
+ result, err = toDiscussionSnapshotDomain(*entity)
+ return err
+ })
+ return result, committed, err
+}
diff --git a/backend/internal/infra/persistence/postgres/conversation/repository_discussion_snapshot_test.go b/backend/internal/infra/persistence/postgres/conversation/repository_discussion_snapshot_test.go
new file mode 100644
index 000000000..6fbca74c3
--- /dev/null
+++ b/backend/internal/infra/persistence/postgres/conversation/repository_discussion_snapshot_test.go
@@ -0,0 +1,95 @@
+package conversation
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ domaindiscussion "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/domain/discussion"
+ "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/infra/persistence/models"
+)
+
+func snapshotForRepositoryTest(model string) domaindiscussion.Snapshot {
+ return domaindiscussion.Snapshot{
+ Template: domaindiscussion.Template{PublicID: "tpl", Name: "Discussion"},
+ Config: domaindiscussion.TemplateConfig{
+ Placeholders: []domaindiscussion.Placeholder{{Key: "p1", DefaultModel: model}},
+ Rounds: []domaindiscussion.Round{{Index: 1, Steps: []domaindiscussion.Step{{ID: "s1", Participant: "p1"}}}},
+ Summary: domaindiscussion.Summary{Participant: "p1"},
+ },
+ Plan: domaindiscussion.RuntimePlan{
+ Rounds: []domaindiscussion.RuntimeRound{{Index: 1, Steps: []domaindiscussion.RuntimeStep{{ID: "s1", Participant: "p1", Model: model}}}},
+ Summary: domaindiscussion.RuntimeSummary{Participant: "p1", Model: model},
+ },
+ }
+}
+
+func TestDiscussionSnapshotRefreshCommitRollbackAndVersionConflict(t *testing.T) {
+ db := openConversationRepositoryTestDB(t)
+ if err := db.AutoMigrate(&models.ConversationDiscussionSnapshot{}); err != nil {
+ t.Fatalf("migrate snapshots: %v", err)
+ }
+ repo := NewRepo(db)
+ ctx := context.Background()
+
+ current, err := repo.RefreshDiscussionSnapshot(ctx, 10, "tpl", snapshotForRepositoryTest("model-v1"), 0)
+ if err != nil {
+ t.Fatalf("refresh: %v", err)
+ }
+ if current.Active != nil || current.Pending == nil || current.PendingVersion != 1 {
+ t.Fatalf("unexpected initial pending: %#v", current)
+ }
+ current, committed, err := repo.CommitDiscussionSnapshot(ctx, 10, "tpl", domaindiscussion.Snapshot{}, true, 1)
+ if err != nil || !committed {
+ t.Fatalf("commit pending: committed=%v err=%v", committed, err)
+ }
+ if current.Active == nil || current.Active.Plan.Summary.Model != "model-v1" || current.Pending != nil || current.ActiveVersion != 2 {
+ t.Fatalf("unexpected committed snapshot: %#v", current)
+ }
+
+ current, err = repo.RefreshDiscussionSnapshot(ctx, 10, "tpl", snapshotForRepositoryTest("model-v2"), 0)
+ if err != nil {
+ t.Fatalf("second refresh: %v", err)
+ }
+ if current.Active.Plan.Summary.Model != "model-v1" || current.Pending.Plan.Summary.Model != "model-v2" || current.PendingVersion != 3 {
+ t.Fatalf("refresh changed active or wrong version: %#v", current)
+ }
+ if _, err = repo.RefreshDiscussionSnapshot(ctx, 10, "tpl", snapshotForRepositoryTest("model-stale"), 1); !errors.Is(err, domaindiscussion.ErrSnapshotConflict) {
+ t.Fatalf("expected stale refresh conflict, got %v", err)
+ }
+ pending := *current.Pending
+ pending.Plan.Summary.Model = "model-edited"
+ if _, err = repo.UpdateDiscussionSnapshotPending(ctx, 10, "tpl", pending, 3); err != nil {
+ t.Fatalf("update pending: %v", err)
+ }
+ if _, err = repo.RollbackDiscussionSnapshot(ctx, 10, "tpl", 2); !errors.Is(err, domaindiscussion.ErrSnapshotConflict) {
+ t.Fatalf("expected stale rollback conflict, got %v", err)
+ }
+ current, err = repo.RollbackDiscussionSnapshot(ctx, 10, "tpl", 3)
+ if err != nil {
+ t.Fatalf("rollback: %v", err)
+ }
+ if current.Active == nil || current.Active.Plan.Summary.Model != "model-v1" || current.Pending != nil || current.PendingVersion != 0 {
+ t.Fatalf("rollback did not preserve active: %#v", current)
+ }
+}
+
+func TestDiscussionSnapshotInitialCommitOnlySucceedsOnce(t *testing.T) {
+ db := openConversationRepositoryTestDB(t)
+ if err := db.AutoMigrate(&models.ConversationDiscussionSnapshot{}); err != nil {
+ t.Fatalf("migrate snapshots: %v", err)
+ }
+ repo := NewRepo(db)
+ ctx := context.Background()
+ current, committed, err := repo.CommitDiscussionSnapshot(ctx, 20, "tpl", snapshotForRepositoryTest("model-first"), false, 0)
+ if err != nil || !committed || current.ActiveVersion != 1 {
+ t.Fatalf("initial commit: %#v committed=%v err=%v", current, committed, err)
+ }
+ current, committed, err = repo.CommitDiscussionSnapshot(ctx, 20, "tpl", snapshotForRepositoryTest("model-second"), false, 0)
+ if err != nil || committed {
+ t.Fatalf("second initial commit should be a no-op: committed=%v err=%v", committed, err)
+ }
+ if current.Active.Plan.Summary.Model != "model-first" {
+ t.Fatalf("active binding was overwritten: %#v", current.Active.Plan)
+ }
+}
diff --git a/backend/internal/infra/persistence/schema/schema.go b/backend/internal/infra/persistence/schema/schema.go
index d1594a503..ee75a4ca0 100644
--- a/backend/internal/infra/persistence/schema/schema.go
+++ b/backend/internal/infra/persistence/schema/schema.go
@@ -36,6 +36,7 @@ func Models() []any {
&models.ConversationProject{},
&models.ConversationShare{},
&models.DiscussionTemplate{},
+ &models.ConversationDiscussionSnapshot{},
&models.Message{},
&models.ConversationMessageFeedback{},
&models.ConversationMessageUIState{},
diff --git a/backend/internal/repository/discussion_snapshot.go b/backend/internal/repository/discussion_snapshot.go
new file mode 100644
index 000000000..f822f6e2e
--- /dev/null
+++ b/backend/internal/repository/discussion_snapshot.go
@@ -0,0 +1,16 @@
+package repository
+
+import (
+ "context"
+
+ domaindiscussion "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/domain/discussion"
+)
+
+// DiscussionSnapshotRepository 原子维护会话级讨论配置的 active/pending 两阶段状态。
+type DiscussionSnapshotRepository interface {
+ GetDiscussionSnapshot(ctx context.Context, conversationID uint, templatePublicID string) (*domaindiscussion.ConversationSnapshot, error)
+ RefreshDiscussionSnapshot(ctx context.Context, conversationID uint, templatePublicID string, pending domaindiscussion.Snapshot, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, error)
+ UpdateDiscussionSnapshotPending(ctx context.Context, conversationID uint, templatePublicID string, pending domaindiscussion.Snapshot, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, error)
+ RollbackDiscussionSnapshot(ctx context.Context, conversationID uint, templatePublicID string, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, error)
+ CommitDiscussionSnapshot(ctx context.Context, conversationID uint, templatePublicID string, snapshot domaindiscussion.Snapshot, usePending bool, expectedPendingVersion int64) (*domaindiscussion.ConversationSnapshot, bool, error)
+}
diff --git a/backend/internal/transport/http/conversation/handler.go b/backend/internal/transport/http/conversation/handler.go
index e6fec6a32..aec96a293 100644
--- a/backend/internal/transport/http/conversation/handler.go
+++ b/backend/internal/transport/http/conversation/handler.go
@@ -99,6 +99,10 @@ type sendMessageErrorStatus struct {
var sendMessageErrorStatuses = []sendMessageErrorStatus{
{err: appconversation.ErrConversationNotFound, status: http.StatusNotFound},
+ {err: appconversation.ErrDiscussionSnapshotConflict, status: http.StatusConflict},
+ {err: appconversation.ErrDiscussionPendingNotFound, status: http.StatusNotFound},
+ {err: appconversation.ErrDiscussionNoEnabledModels, status: http.StatusBadRequest},
+ {err: appconversation.ErrDiscussionSummaryModelLocked, status: http.StatusBadRequest},
{err: appconversation.ErrInvalidFileReference, status: http.StatusBadRequest},
{err: appconversation.ErrFileNotFound, status: http.StatusNotFound},
{err: appconversation.ErrFileTooLarge, status: http.StatusRequestEntityTooLarge},
diff --git a/backend/internal/transport/http/conversation/handler_discussion.go b/backend/internal/transport/http/conversation/handler_discussion.go
index 8894473e6..ced96071f 100644
--- a/backend/internal/transport/http/conversation/handler_discussion.go
+++ b/backend/internal/transport/http/conversation/handler_discussion.go
@@ -16,14 +16,16 @@ import (
// DiscussionSendRequest 是讨论消息发送请求。
type DiscussionSendRequest struct {
- ContentType string `json:"contentType" binding:"required,oneof=text markdown"`
- Content string `json:"content" binding:"required"`
- TemplatePublicID string `json:"templatePublicID" binding:"required,max=32"`
- Models map[string]string `json:"models,omitempty"`
- ClientRunID string `json:"clientRunID,omitempty" binding:"omitempty,max=64"`
- ParentMessagePublicID string `json:"parentMessagePublicID,omitempty" binding:"omitempty,max=32"`
- SourceMessagePublicID string `json:"sourceMessagePublicID,omitempty" binding:"omitempty,max=32"`
- BranchReason string `json:"branchReason,omitempty" binding:"omitempty,oneof=default retry edit"`
+ ContentType string `json:"contentType" binding:"required,oneof=text markdown"`
+ Content string `json:"content" binding:"required"`
+ TemplatePublicID string `json:"templatePublicID" binding:"required,max=32"`
+ Models map[string]string `json:"models,omitempty"`
+ DisabledModels []string `json:"disabledModels,omitempty" binding:"omitempty,max=12,dive,max=64"`
+ ExpectedPendingVersion int64 `json:"expectedPendingVersion,omitempty" binding:"min=0"`
+ ClientRunID string `json:"clientRunID,omitempty" binding:"omitempty,max=64"`
+ ParentMessagePublicID string `json:"parentMessagePublicID,omitempty" binding:"omitempty,max=32"`
+ SourceMessagePublicID string `json:"sourceMessagePublicID,omitempty" binding:"omitempty,max=32"`
+ BranchReason string `json:"branchReason,omitempty" binding:"omitempty,oneof=default retry edit"`
}
// StreamDiscussionMessage godoc
@@ -90,17 +92,19 @@ func (h *Handler) StreamDiscussionMessage(c *gin.Context) {
return nil
}
input := appconversation.DiscussionSendInput{
- UserID: userID,
- ConversationID: conversation.ID,
- RequestID: middleware.MustRequestID(c),
- ContentType: req.ContentType,
- Content: req.Content,
- TemplatePublicID: req.TemplatePublicID,
- ModelBindings: req.Models,
- ParentMessagePublicID: req.ParentMessagePublicID,
- SourceMessagePublicID: req.SourceMessagePublicID,
- BranchReason: req.BranchReason,
- ClientRunID: runID,
+ UserID: userID,
+ ConversationID: conversation.ID,
+ RequestID: middleware.MustRequestID(c),
+ ContentType: req.ContentType,
+ Content: req.Content,
+ TemplatePublicID: req.TemplatePublicID,
+ ModelBindings: req.Models,
+ DisabledModels: req.DisabledModels,
+ ExpectedPendingVersion: req.ExpectedPendingVersion,
+ ParentMessagePublicID: req.ParentMessagePublicID,
+ SourceMessagePublicID: req.SourceMessagePublicID,
+ BranchReason: req.BranchReason,
+ ClientRunID: runID,
OnEvent: func(eventType string, payload map[string]any) error {
return writeEvent(normalizeStreamEventPayload(eventType, payload))
},
diff --git a/backend/internal/transport/http/conversation/handler_discussion_snapshot.go b/backend/internal/transport/http/conversation/handler_discussion_snapshot.go
new file mode 100644
index 000000000..6b3889e54
--- /dev/null
+++ b/backend/internal/transport/http/conversation/handler_discussion_snapshot.go
@@ -0,0 +1,113 @@
+package conversation
+
+import (
+ "errors"
+ "net/http"
+ "strings"
+
+ appconversation "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/application/conversation"
+ domaindiscussion "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/domain/discussion"
+ "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/shared/response"
+ "github.com/DEEIX-AI/DEEIX-Chat/backend/internal/transport/http/middleware"
+ "github.com/gin-gonic/gin"
+)
+
+type DiscussionSnapshotRequest struct {
+ Models map[string]string `json:"models,omitempty"`
+ ExpectedPendingVersion int64 `json:"expectedPendingVersion" binding:"min=0"`
+}
+
+func (h *Handler) discussionSnapshotConversation(c *gin.Context) (uint, uint, string, bool) {
+ userID := middleware.MustUserID(c)
+ conversation, err := h.service.GetConversationByPublicID(c.Request.Context(), userID, strings.TrimSpace(c.Param("id")))
+ if err != nil {
+ response.ErrorFrom(c, http.StatusNotFound, appconversation.ErrConversationNotFound)
+ return 0, 0, "", false
+ }
+ return userID, conversation.ID, strings.TrimSpace(c.Param("templateID")), true
+}
+
+func writeDiscussionSnapshotError(c *gin.Context, err error) {
+ switch {
+ case errors.Is(err, appconversation.ErrDiscussionSnapshotConflict), errors.Is(err, domaindiscussion.ErrSnapshotConflict):
+ response.ErrorFrom(c, http.StatusConflict, appconversation.ErrDiscussionSnapshotConflict)
+ case errors.Is(err, appconversation.ErrDiscussionPendingNotFound), errors.Is(err, domaindiscussion.ErrPendingNotFound):
+ response.ErrorFrom(c, http.StatusNotFound, appconversation.ErrDiscussionPendingNotFound)
+ case errors.Is(err, domaindiscussion.ErrTemplateNotFound):
+ response.ErrorFrom(c, http.StatusNotFound, err)
+ case errors.Is(err, domaindiscussion.ErrTemplateInvalid):
+ response.ErrorFrom(c, http.StatusBadRequest, err)
+ default:
+ response.InternalError(c, err)
+ }
+}
+
+func (h *Handler) GetDiscussionSnapshot(c *gin.Context) {
+ userID, conversationID, templateID, ok := h.discussionSnapshotConversation(c)
+ if !ok {
+ return
+ }
+ snapshot, err := h.service.GetDiscussionSnapshot(c.Request.Context(), userID, conversationID, templateID)
+ if err != nil {
+ writeDiscussionSnapshotError(c, err)
+ return
+ }
+ if snapshot == nil {
+ snapshot = &domaindiscussion.ConversationSnapshot{ConversationID: conversationID, TemplatePublicID: templateID}
+ }
+ response.Success(c, appconversation.DiscussionSnapshotPayloadOf(snapshot))
+}
+
+func (h *Handler) RefreshDiscussionSnapshot(c *gin.Context) {
+ userID, conversationID, templateID, ok := h.discussionSnapshotConversation(c)
+ if !ok {
+ return
+ }
+ var req DiscussionSnapshotRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ response.InvalidRequestBody(c, err)
+ return
+ }
+ snapshot, err := h.service.RefreshDiscussionSnapshot(c.Request.Context(), userID, conversationID, templateID, req.Models, req.ExpectedPendingVersion)
+ if err != nil {
+ writeDiscussionSnapshotError(c, err)
+ return
+ }
+ response.Success(c, appconversation.DiscussionSnapshotPayloadOf(snapshot))
+}
+
+func (h *Handler) RollbackDiscussionSnapshot(c *gin.Context) {
+ userID, conversationID, templateID, ok := h.discussionSnapshotConversation(c)
+ if !ok {
+ return
+ }
+ var req DiscussionSnapshotRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ response.InvalidRequestBody(c, err)
+ return
+ }
+ snapshot, err := h.service.RollbackDiscussionSnapshot(c.Request.Context(), userID, conversationID, templateID, req.ExpectedPendingVersion)
+ if err != nil {
+ writeDiscussionSnapshotError(c, err)
+ return
+ }
+ response.Success(c, appconversation.DiscussionSnapshotPayloadOf(snapshot))
+}
+
+func (h *Handler) AdoptDiscussionSnapshot(c *gin.Context) {
+ userID, conversationID, templateID, ok := h.discussionSnapshotConversation(c)
+ if !ok {
+ return
+ }
+ var req DiscussionSnapshotRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ response.InvalidRequestBody(c, err)
+ return
+ }
+ snapshot, err := h.service.AdoptDiscussionSnapshot(c.Request.Context(), userID, conversationID, templateID, req.ExpectedPendingVersion)
+ if err != nil {
+ writeDiscussionSnapshotError(c, err)
+ return
+ }
+ response.Success(c, appconversation.DiscussionSnapshotPayloadOf(snapshot))
+}
diff --git a/backend/internal/transport/http/conversation/router.go b/backend/internal/transport/http/conversation/router.go
index 60213ded5..4dadf4d28 100644
--- a/backend/internal/transport/http/conversation/router.go
+++ b/backend/internal/transport/http/conversation/router.go
@@ -41,6 +41,10 @@ func (m *Module) RegisterRoutes(authRequired *gin.RouterGroup, gate middleware.F
authRequired.POST("/conversations/:id/messages", m.Handler.SendMessage)
authRequired.POST("/conversations/:id/messages/stream", m.Handler.StreamMessage)
authRequired.POST("/conversations/:id/messages/discussion/stream", m.Handler.StreamDiscussionMessage)
+ authRequired.GET("/conversations/:id/discussion-snapshots/:templateID", m.Handler.GetDiscussionSnapshot)
+ authRequired.POST("/conversations/:id/discussion-snapshots/:templateID/refresh", m.Handler.RefreshDiscussionSnapshot)
+ authRequired.POST("/conversations/:id/discussion-snapshots/:templateID/rollback", m.Handler.RollbackDiscussionSnapshot)
+ authRequired.POST("/conversations/:id/discussion-snapshots/:templateID/adopt", m.Handler.AdoptDiscussionSnapshot)
authRequired.POST("/temporary-chat/messages/stream", m.Handler.StreamTemporaryChatMessage)
authRequired.POST("/conversations/:id/messages/:message_id/fork", m.Handler.ForkConversationFromMessage)
authRequired.DELETE("/conversations/:id/messages/:message_id", m.Handler.DeleteMessage)
diff --git a/docs/DISCUSSIONS.md b/docs/DISCUSSIONS.md
index eb6303d0d..e35098009 100644
--- a/docs/DISCUSSIONS.md
+++ b/docs/DISCUSSIONS.md
@@ -7,11 +7,12 @@
| 模板领域模型 | `backend/internal/domain/discussion/` |
| 模板 CRUD | `backend/internal/transport/http/discussion/`、`backend/internal/application/discussion/` |
| 讨论编排 | `backend/internal/application/conversation/service_discussion.go` |
-| 流事件传输 | `backend/internal/transport/http/conversation/handler_discussion.go` |
+| 会话级快照 | `backend/internal/application/conversation/service_discussion_snapshot.go`、`backend/internal/infra/persistence/postgres/conversation/repository_discussion_snapshot.go` |
+| 快照与流事件传输 | `backend/internal/transport/http/conversation/handler_discussion.go`、`handler_discussion_snapshot.go` |
| 前端事件折叠 | `apps/web/features/chat/model/discussion-stream.ts` |
| 前端面板 | `apps/web/features/chat/components/message/message-discussion.tsx` |
| 后台编辑器 | `apps/web/features/admin/components/sections/discussions/` |
-| 对话时绑定条 | `apps/web/features/chat/components/sections/chat-discussion-config.tsx` |
+| 对话时绑定条 | `apps/web/features/chat/components/sections/chat-discussion-config.tsx`、`apps/web/features/chat/hooks/use-chat-discussion.ts` |
## 1. 概念
@@ -53,14 +54,15 @@
`Service.StreamDiscussionMessage` 的顺序:
-1. `ResolvePlan` 解析模板与绑定,产出运行时的 `Rounds`(含每步绑定的模型、执行方式)与 `Summary`。
-2. 复用普通消息的建对逻辑,写入 user / assistant 两条消息,会话模型记为 `discussion:`。
-3. 沿当前分支取本次提问之前的对话历史(`ListMessageAncestors`),以**真实 user/assistant 消息**的形式放进 prompt,与普通对话的多轮结构一致。之前的讨论只以「你的提问 + 最终总结」出现一次,各模型的逐轮发言(`discussion_json`)不进入历史。
-4. 逐轮执行:并行轮次共享同一份此前轮次 transcript,整轮完成后进入下一轮;串行轮次按模型顺序逐个执行,每次成功后立即把发言加入下一个模型的 transcript。
-5. 每轮的 messages = `system(该轮 prompt + 执行方式说明)` + 历史消息 + 当前 user(本次问题 + 当前模型可见的讨论记录)。该轮 prompt 取当前执行方式对应的 `parallelPrompt` / `serialPrompt`;当前执行方式未单独配置时回落到 `steps[*].prompt`。仍然为空则使用内置默认值:并行首轮「独立、具体回答」,并行后续轮「阅读已有讨论并补充纠正」,串行首轮「先独立回答,再回应本轮前序发言的分歧」,串行后续轮「阅读此前轮次及本轮前序发言并回应分歧」。串行上下文标题明确包含「本轮在你之前」,并行明确不包含同轮其他模型。
-6. 讨论结束后调用总结模型(同样带历史);总结失败时用讨论记录拼出回退正文,而不是把整条消息判为失败。
-7. 历史按 `ContextMaxTurns` 限制条数,并在 `generateDiscussion` 里用 `fitGenerateInputToModelBudget` 按**当前模型**的上下文预算裁掉最老的轮次(保留 system 与本次问题),与普通对话同一套规则。
-8. 结束时把完整状态写入 `chat_messages.discussion_json`,并把汇总用量写入 assistant 消息。
+1. 优先读取会话级快照:有 pending 使用 pending,否则使用 active;只有首次使用才通过 `ResolvePlan` 解析实时模板。active 忽略请求中的新绑定,pending 允许修改绑定并校验版本。
+2. `FilterDisabledModels` 按占位符过滤本次执行,空轮次整体跳过但保留原编号;快照仍保存过滤前的完整计划。
+3. 复用普通消息的建对逻辑,写入 user / assistant 两条消息,会话模型记为 `discussion:`。
+4. 沿当前分支取本次提问之前的对话历史(`ListMessageAncestors`),以**真实 user/assistant 消息**的形式放进 prompt,与普通对话的多轮结构一致。之前的讨论只以「你的提问 + 最终总结」出现一次,各模型的逐轮发言(`discussion_json`)不进入历史。
+5. 逐轮执行:并行轮次共享同一份此前轮次 transcript,整轮完成后进入下一轮;串行轮次按模型顺序逐个执行,每次成功后立即把发言加入下一个模型的 transcript。
+6. 每轮的 messages = `system(该轮 prompt + 执行方式说明)` + 历史消息 + 当前 user(本次问题 + 当前模型可见的讨论记录)。该轮 prompt 取当前执行方式对应的 `parallelPrompt` / `serialPrompt`;当前执行方式未单独配置时回落到 `steps[*].prompt`。仍然为空则使用内置默认值:并行首轮「独立、具体回答」,并行后续轮「阅读已有讨论并补充纠正」,串行首轮「先独立回答,再回应本轮前序发言的分歧」,串行后续轮「阅读此前轮次及本轮前序发言并回应分歧」。串行上下文标题明确包含「本轮在你之前」,并行明确不包含同轮其他模型。
+7. 讨论结束后调用总结模型(同样带历史);总结失败时用讨论记录拼出回退正文,而不是把整条消息判为失败。
+8. 历史按 `ContextMaxTurns` 限制条数,并在 `generateDiscussion` 里用 `fitGenerateInputToModelBudget` 按**当前模型**的上下文预算裁掉最老的轮次(保留 system 与本次问题),与普通对话同一套规则。
+9. 结束时把完整状态写入 `chat_messages.discussion_json`,并把汇总用量写入 assistant 消息。只有所有轮次和总结均为 `completed` 才自动提交 pending 或写入首次 active;`completed_with_errors` / `stopped` / 提前错误均不提交。
每次调用实际发送的提示词会被记录下来(`turn.prompt` / `state.summaryPrompt`),供前端调试模式展示;记录的是 `buildTextTaskGenerateInput` 归一化之后真正发往上游的消息。
@@ -89,10 +91,10 @@
| `discussion_round_done` | `round`, `turns` | 用该轮结果整体替换该轮发言 |
| `discussion_summary_start` | `participant`, `model`, `prompt`, `promptMessages` | 总结调用前切换为「总结中」并写入实际 Prompt 与结构化消息 |
| `discussion_summary_delta` | `delta` | 追加到 assistant 正文,同时保持总结状态,实现总结流式 |
-| `discussion_done` | `state`(含 `summaryPrompt`、`summaryPromptMessages`) | 换成服务端最终状态 |
+| `discussion_done` | `state`、`snapshotCommitted`、`activeSnapshot`、`activeVersion`、`pendingVersion` | 换成服务端最终状态,并直接同步已提交的快照,无需额外查询 |
| `delta`(收尾) | `delta`, `replace: true` | 用最终正文覆盖流式预览,避免重复 |
-讨论事件的负载与 `discussion_json` 使用同一套 JSON 形状(小写驼峰,由 `service_discussion_payload.go` 的 `discussion*Payload` 产出),不要直接把领域结构体塞进事件:Go 字段名是大驼峰,前端会读不到字段。
+讨论状态与快照负载使用同一套小写驼峰契约,由 `service_discussion_payload.go` 的 `discussion*Payload` 产出。领域结构保持协议无关,不携带 JSON 标签,也不要直接塞进事件或 HTTP 响应。
所有事件同时写入 generation stream 缓存,因此切走会话再回来时,`resumeMessageGenerationStream` 能按 `afterSeq` 回放(见 `apps/web/features/chat/hooks/use-chat-data.ts`)。
@@ -137,10 +139,13 @@
选择 `discussion:*` 模型后,输入区上方出现绑定条:
-- 总结模型独占一行(主色边框 + 「总结」徽标)。
-- 讨论模型横向铺满,最小宽度 13rem,排不开才换行。
-- 绑定按「会话 + 模板」存入 localStorage(`deeix:discussion-bindings::`),新会话回退到模板默认模型。
-- 绑定优先级:本会话最近一次讨论实际使用的模型 > 本地保存的选择 > 模板默认模型。最近一次讨论的绑定是异步随消息列表到达的,因此即使到达晚于输入区初始化也会补上;用户手动改过模型后不再被覆盖。
+- 总结模型独占一行(主色边框 + 「总结」徽标),讨论模型带电源开关。关闭只影响本次执行,不产生该占位符的发言或用量;总结不可关闭,至少保留一个非空轮次。
+- 临时关闭偏好按「会话 + 模板」存入 localStorage(`deeix:discussion-disabled::`),与绑定草稿同生命周期,不写入 active/pending。
+- 首次完整成功后,服务端在 `chat_conversation_discussion_snapshots` 按 `(conversation_id, template_public_id)` 保存 active 完整模板和绑定。后台修改或删除模板不影响 active;平台模型被删除时也不自动替换,调用会按原绑定失败。
+- 「刷新讨论配置」通过 `POST .../discussion-snapshots/{templateID}/refresh` 生成 pending:已有占位符保留绑定,新占位符使用最新模板默认值,移除的占位符丢弃。pending 阶段下拉可编辑,active 阶段只读。
+- 下一次发送携带 `disabledModels` 与 `expectedPendingVersion`。严格完整成功才原子提交 pending;失败、停止或部分失败保留 active 和 pending。`rollback` 清空 pending,部分成功后可用 `adopt` 手动采用。
+- 页面刷新只读取 `GET .../discussion-snapshots/{templateID}`,不会自动拉取后台改动。再次刷新需要内联二次确认;版本冲突返回 409,提示重新加载。
+- 新会话仍使用本地绑定草稿(`deeix:discussion-bindings::`);已有会话优先使用快照。后台模板删除后,前端用快照合成 `discussion:` 选项,绑定条不会消失。
## 8. 已知边界
diff --git a/packages/api-contract/src/types.generated.ts b/packages/api-contract/src/types.generated.ts
index bc7b16d04..3b624739c 100644
--- a/packages/api-contract/src/types.generated.ts
+++ b/packages/api-contract/src/types.generated.ts
@@ -1527,6 +1527,10 @@ export interface DiscussionSendRequest {
clientRunID?: string;
content: string;
contentType: "text" | "markdown";
+ /** @maxItems 12 */
+ disabledModels?: string[];
+ /** @min 0 */
+ expectedPendingVersion?: number;
models?: Record;
/** @maxLength 32 */
parentMessagePublicID?: string;