Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

refactor(web): type start-turn request assembly

Bingxi Zhao (Frank)8ecc5f856dce
diff --git a/web/features/chat/controllers/buildStartTurnInput.ts b/web/features/chat/controllers/buildStartTurnInput.ts
new file mode 100644
index 000000000..f64d27926
--- /dev/null
+++ b/web/features/chat/controllers/buildStartTurnInput.ts
@@ -0,0 +1,117 @@
+import type { StartTurnCommand } from "@/contracts/generated/turn-protocol";
+import { buildStartTurn } from "@/contracts/parse/turn-command";
+import { ApiError } from "@/shared/api/errors";
+
+import type { LegacySendMessageArguments, StartTurnInput } from "../model/start-turn";
+
+const RUNTIME_ONLY_CONFIG_KEYS = new Set([
+ "_course_id",
+ "_persist_user_message",
+ "_regenerate",
+ "_regenerated_from_message_id",
+ "_superseded_turn_id",
+ "auto_route",
+ "followup_question_context",
+ "selection_tutor_context",
+ "subagent_consult_budget",
+]);
+
+function invalid(message: string): never {
+ throw new ApiError({
+ code: "invalid_turn_input",
+ message,
+ retryable: false,
+ scope: "turn",
+ });
+}
+
+function capabilityConfig(input: StartTurnInput): Record<string, unknown> {
+ const config = input.capabilityConfig ?? {};
+ const allowed = input.allowedCapabilityConfigKeys
+ ? new Set(input.allowedCapabilityConfigKeys)
+ : null;
+ for (const key of Object.keys(config)) {
+ if (RUNTIME_ONLY_CONFIG_KEYS.has(key)) {
+ invalid(`Runtime field ${key} must use its typed turn property`);
+ }
+ if (allowed && !allowed.has(key)) {
+ invalid(`Unsupported ${input.capability ?? "chat"} configuration field: ${key}`);
+ }
+ }
+ return { ...config };
+}
+
+export function buildStartTurnInput(input: StartTurnInput): StartTurnCommand {
+ if (!input.content.trim()) invalid("Turn content must not be empty");
+ if (input.subagentConsultBudget != null && input.subagentConsultBudget < 0) {
+ invalid("Subagent consult budget must be non-negative");
+ }
+ if (input.readingMaterialRevision != null && input.readingMaterialRevision < 1) {
+ invalid("Reading material revision must be positive");
+ }
+ if (
+ input.timedMediaViewport &&
+ (!Number.isFinite(input.timedMediaViewport.time_seconds) ||
+ input.timedMediaViewport.time_seconds < 0)
+ ) {
+ invalid("Timed media position must be non-negative");
+ }
+
+ return buildStartTurn({
+ content: input.content,
+ capability: input.capability ?? "chat",
+ session_id: input.sessionId ?? null,
+ tools: input.tools ?? null,
+ knowledge_bases: input.knowledgeBases ?? [],
+ language: input.language ?? null,
+ config: capabilityConfig(input),
+ attachments: input.attachments ?? [],
+ notebook_references: input.notebookReferences ?? [],
+ history_references: input.historyReferences ?? [],
+ partner_group_references: input.partnerGroupReferences ?? [],
+ question_notebook_references: input.questionNotebookReferences ?? [],
+ book_references: input.bookReferences ?? [],
+ reading_references: input.readingReferences ?? [],
+ memory_references: input.memoryReferences ?? [],
+ skills: input.skills ?? [],
+ persona: input.persona ?? null,
+ llm_selection: input.llmSelection ?? null,
+ workspace_mode: input.workspaceMode ?? null,
+ mastery_path_id: input.masteryPathId ?? null,
+ mastery_path_lease_managed: input.masteryPathLeaseManaged ?? false,
+ reading_material_id: input.readingMaterialId ?? null,
+ reading_material_revision: input.readingMaterialRevision ?? null,
+ reading_workspace_id: input.readingWorkspaceId ?? null,
+ reading_viewport: input.readingViewport ?? null,
+ timed_media_id: input.timedMediaId ?? null,
+ timed_media_viewport: input.timedMediaViewport ?? null,
+ parent_message_id: input.parentMessageId ?? null,
+ course_id: input.courseId ?? null,
+ persist_user_message: input.persistUserMessage ?? true,
+ regenerate: input.regenerate ?? false,
+ regenerated_from_message_id: input.regeneratedFromMessageId ?? null,
+ superseded_turn_id: input.supersededTurnId ?? null,
+ followup_question_context: input.followupQuestionContext ?? null,
+ selection_tutor_context: input.selectionTutorContext ?? null,
+ subagent_consult_budget: input.subagentConsultBudget ?? null,
+ auto_route: input.autoRoute ?? null,
+ });
+}
+
+/** Temporary positional adapter for callers migrated in Task 14. */
+export function legacySendMessageInput(
+ legacy: LegacySendMessageArguments,
+ defaults: Omit<StartTurnInput, keyof LegacySendMessageArguments | "capabilityConfig">,
+): StartTurnInput {
+ return {
+ ...defaults,
+ content: legacy.content,
+ attachments: legacy.attachments,
+ capabilityConfig: legacy.config,
+ notebookReferences: legacy.notebookReferences,
+ historyReferences: legacy.historyReferences,
+ questionNotebookReferences: legacy.questionNotebookReferences,
+ persona: legacy.persona,
+ memoryReferences: legacy.memoryReferences,
+ };
+}
diff --git a/web/features/chat/model/start-turn.ts b/web/features/chat/model/start-turn.ts
new file mode 100644
index 000000000..572383464
--- /dev/null
+++ b/web/features/chat/model/start-turn.ts
@@ -0,0 +1,61 @@
+import type {
+ BookReference,
+ LLMSelection,
+ NotebookReference,
+ OutgoingAttachment,
+ ReadingReference,
+ ReadingViewport,
+ TimedMediaViewport,
+} from "@/contracts/generated/turn-protocol";
+
+export interface StartTurnInput {
+ content: string;
+ capability?: string | null;
+ sessionId?: string | null;
+ tools?: string[] | null;
+ knowledgeBases?: string[];
+ language?: string | null;
+ capabilityConfig?: Record<string, unknown>;
+ allowedCapabilityConfigKeys?: readonly string[];
+ attachments?: OutgoingAttachment[];
+ notebookReferences?: NotebookReference[];
+ historyReferences?: string[];
+ partnerGroupReferences?: Array<Record<string, unknown>>;
+ questionNotebookReferences?: number[];
+ bookReferences?: BookReference[];
+ readingReferences?: ReadingReference[];
+ memoryReferences?: Array<Record<string, unknown>>;
+ skills?: string[];
+ persona?: string | null;
+ llmSelection?: LLMSelection | null;
+ workspaceMode?: string | null;
+ masteryPathId?: string | null;
+ masteryPathLeaseManaged?: boolean;
+ readingMaterialId?: string | null;
+ readingMaterialRevision?: number | null;
+ readingWorkspaceId?: string | null;
+ readingViewport?: ReadingViewport | null;
+ timedMediaId?: string | null;
+ timedMediaViewport?: TimedMediaViewport | null;
+ parentMessageId?: number | null;
+ courseId?: string | null;
+ persistUserMessage?: boolean;
+ regenerate?: boolean;
+ regeneratedFromMessageId?: number | null;
+ supersededTurnId?: string | null;
+ followupQuestionContext?: Record<string, unknown> | null;
+ selectionTutorContext?: Record<string, unknown> | null;
+ subagentConsultBudget?: number | null;
+ autoRoute?: boolean | null;
+}
+
+export interface LegacySendMessageArguments {
+ content: string;
+ attachments?: OutgoingAttachment[];
+ config?: Record<string, unknown>;
+ notebookReferences?: NotebookReference[];
+ historyReferences?: string[];
+ questionNotebookReferences?: number[];
+ persona?: string;
+ memoryReferences?: Array<Record<string, unknown>>;
+}
diff --git a/web/features/chat/store/ChatActions.ts b/web/features/chat/store/ChatActions.ts
index bea6fc695..1073c7864 100644
--- a/web/features/chat/store/ChatActions.ts
+++ b/web/features/chat/store/ChatActions.ts
@@ -6,6 +6,8 @@ import {
} from "@/contracts/parse/turn-command";
import type { ChatMessage, ChatSession } from "../model/types";
+import type { StartTurnInput } from "../model/start-turn";
+import { buildStartTurnInput } from "../controllers/buildStartTurnInput";
import type { TurnRuntimeClient } from "../transport/TurnRuntimeClient";
import type { ChatStore } from "./createChatStore";
import { sessionClient, type SessionClient, type SessionWireDetail } from "../api/session-client";
@@ -97,6 +99,20 @@ export class ChatActions {
runtime.send(input.command);
}
+ startTurnInput(input: {
+ sessionKey: string;
+ turn: StartTurnInput;
+ user: ChatMessage;
+ assistant: ChatMessage;
+ }): void {
+ this.startTurn({
+ sessionKey: input.sessionKey,
+ command: buildStartTurnInput(input.turn),
+ user: input.user,
+ assistant: input.assistant,
+ });
+ }
+
cancelTurn(sessionKey: string): void {
const session = this.store.getState().sessions[sessionKey];
if (!session?.activeTurnId) return;
diff --git a/web/tests/start-turn-input.test.ts b/web/tests/start-turn-input.test.ts
new file mode 100644
index 000000000..218922b39
--- /dev/null
+++ b/web/tests/start-turn-input.test.ts
@@ -0,0 +1,101 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { buildStartTurnInput, legacySendMessageInput } from "../features/chat/controllers/buildStartTurnInput";
+import type { StartTurnInput } from "../features/chat/model/start-turn";
+import { ApiError } from "../shared/api/errors";
+
+test("plain, quiz, research, and visualize turns use one typed mapper", () => {
+ const matrix: StartTurnInput[] = [
+ { content: "hello", capability: "chat" },
+ {
+ content: "quiz me",
+ capability: "deep_question",
+ capabilityConfig: { difficulty: "medium" },
+ allowedCapabilityConfigKeys: ["difficulty"],
+ },
+ {
+ content: "research",
+ capability: "deep_research",
+ capabilityConfig: { breadth: 3 },
+ allowedCapabilityConfigKeys: ["breadth"],
+ },
+ {
+ content: "draw",
+ capability: "visualize",
+ capabilityConfig: { render_type: "mermaid" },
+ allowedCapabilityConfigKeys: ["render_type"],
+ },
+ ];
+ for (const input of matrix) {
+ const wire = buildStartTurnInput(input);
+ assert.equal(wire.type, "start_turn");
+ assert.equal(wire.protocol_version, "2.0");
+ assert.equal(wire.capability, input.capability);
+ }
+});
+
+test("course, Reading, Watching, Mastery, references, edit, and budget are explicit", () => {
+ const wire = buildStartTurnInput({
+ content: "continue",
+ sessionId: "session-1",
+ workspaceMode: "immersive_reading",
+ courseId: "course-1",
+ masteryPathId: "path-1",
+ readingWorkspaceId: "reading-1",
+ readingMaterialId: "material-1",
+ readingMaterialRevision: 2,
+ readingViewport: { locator: 4, selection: "proof" },
+ timedMediaId: "video-1",
+ timedMediaViewport: { time_seconds: 12.5 },
+ parentMessageId: 9,
+ subagentConsultBudget: 3,
+ notebookReferences: [{ notebook_id: "nb", record_ids: ["r1"] }],
+ bookReferences: [{ book_id: "book", page_ids: ["p1"] }],
+ readingReferences: [{ material_id: "material-1", revision: 2, locators: [4] }],
+ attachments: [{ type: "document", filename: "notes.pdf", url: "/a" }],
+ });
+ assert.equal(wire.course_id, "course-1");
+ assert.equal(wire.parent_message_id, 9);
+ assert.equal(wire.subagent_consult_budget, 3);
+ assert.equal(wire.reading_viewport?.locator, 4);
+ assert.equal(wire.timed_media_viewport?.time_seconds, 12.5);
+});
+
+test("waiting-input replies stay commands and runtime config cannot leak into capability config", () => {
+ assert.throws(
+ () =>
+ buildStartTurnInput({
+ content: "bad",
+ capabilityConfig: { _course_id: "hidden" },
+ }),
+ (error) => error instanceof ApiError && error.code === "invalid_turn_input",
+ );
+ assert.throws(
+ () =>
+ buildStartTurnInput({
+ content: "bad",
+ capabilityConfig: { unexpected: true },
+ allowedCapabilityConfigKeys: ["difficulty"],
+ }),
+ /Unsupported/,
+ );
+
+ const wire = buildStartTurnInput({ content: "ok", courseId: "course-1" });
+ assert.equal("_course_id" in (wire.config ?? {}), false);
+ assert.equal("subagent_consult_budget" in (wire.config ?? {}), false);
+});
+
+test("the positional compatibility adapter produces object-shaped input", () => {
+ const input = legacySendMessageInput(
+ { content: "legacy", config: { difficulty: "hard" } },
+ {
+ capability: "deep_question",
+ allowedCapabilityConfigKeys: ["difficulty"],
+ sessionId: "session-1",
+ },
+ );
+ assert.equal(input.content, "legacy");
+ assert.deepEqual(input.capabilityConfig, { difficulty: "hard" });
+ assert.equal(buildStartTurnInput(input).session_id, "session-1");
+});