فهرست منبع

feat: support session-scoped interactive model overrides (#227)

DanielWalnut 2 ماه پیش
والد
کامیت
745386c198

+ 19 - 0
docs/tui-capabilities.md

@@ -46,3 +46,22 @@ Every collected diagnostic artifact, including prioritized session artifacts, is
 There is no raw-attachment upload option in this flow. Prompts, conversation text, tool arguments/results, command output, workspace excerpts, raw errors and unknown fields are excluded even if they contain no recognizable credential pattern. This intentionally reduces diagnostic detail: reproducing an exact response or inspecting an original stack is not possible from these uploads. Future raw attachments would require a separate, explicit review and consent surface describing their contents and scope.
 
 The regression tests use temporary synthetic files and intercepted HTTP only. They decrypt the final automatic-report request as a receiver would, and unzip the actual feedback PUT body after real session-report collection. They do not validate production ingestion of the new schemas, retention policies, live services, other telemetry paths or other platforms.
+
+
+## Interactive startup model
+
+Use `mcode -m <provider-id>/<model-id>` or
+`mcode "Fix the failing tests" --model <provider-id>/<model-id>` to select the
+model for the startup Session. References use the same syntax as `exec --model`,
+including `custom_provider:<id>/<model-id>`, model IDs containing `/`, and the
+optional `#variant` suffix. The provider must already be configured and the model
+must be available to Runtime; invalid references fail before the initial prompt runs.
+
+Without a resume option, this creates a new Session even when no prompt is given.
+With `--session <id>` or `--continue`, it updates the opened Session's model before
+submitting the prompt. The selection is saved with that Session, so later turns
+and resumes keep it. It does not change the global default, and `/new` returns to
+the configured default. Omitting `--model` preserves existing startup behavior.
+The untargeted `--session` picker cannot be combined with `--model`; provide an ID
+or use `--continue` instead. If opening or continuing a Session fails, the override
+and initial prompt are not applied.

+ 14 - 0
packages/tui/src/cli/contract.ts

@@ -1,4 +1,5 @@
 import { InvalidArgumentError, Option, type Command } from 'commander';
+import { parseHeadlessModelOverride } from '../headless/model-selection.js';
 import type { TuiMode } from '../tui/engine/public.js';
 import { parseTuiStartupEnvironment } from './environment.js';
 import type { TuiBuildEnvironment } from '../auth/environment.js';
@@ -7,6 +8,7 @@ const RETIRED_TOP_LEVEL_COMMAND_NAMES = new Set(['git', 'changes', 'projects']);
 
 export interface TuiInteractiveLaunchRequest {
   readonly initialPrompt?: string;
+  readonly model?: string;
   readonly sessionId?: string;
   readonly showSessionPicker?: boolean;
   readonly continueLatestSession?: boolean;
@@ -17,6 +19,7 @@ export interface TuiInteractiveLaunchRequest {
 }
 
 export interface RawTuiInteractiveOptions {
+  readonly model?: string;
   readonly session?: string | boolean;
   readonly continue?: boolean;
   readonly resume?: string;
@@ -31,6 +34,7 @@ export function applyInteractiveCliContract(
 ): Command {
   const configured = command
     .argument('[prompt]', 'task to execute in the interactive TUI')
+    .addOption(new Option('-m, --model <provider/model>', 'select the model for this Session only'))
     .addOption(new Option('--lane <lane>', 'managed backend lane for test or staging builds'))
     .addOption(
       new Option('--session [id]', 'open a Session by id, or browse Sessions when id is omitted'),
@@ -75,8 +79,18 @@ export function resolveInteractiveLaunchRequest(
     throw new Error('--session, --continue, and --resume cannot be combined');
   }
   const sessionId = explicitSessionId || compatibilitySessionId;
+  const model = commandOptions.model?.trim();
+  if (commandOptions.model !== undefined) {
+    parseHeadlessModelOverride(model ?? '');
+    if (showSessionPicker) {
+      throw new Error(
+        '--model requires a Session id with --session; use --session <id> or --continue.',
+      );
+    }
+  }
   return {
     ...(prompt ? { initialPrompt: prompt } : {}),
+    ...(model ? { model } : {}),
     ...(sessionId ? { sessionId } : {}),
     ...(showSessionPicker ? { showSessionPicker: true } : {}),
     ...(commandOptions.continue ? { continueLatestSession: true } : {}),

+ 7 - 1
packages/tui/src/cli/environment.ts

@@ -17,7 +17,13 @@ import { readTuiRegionPreference } from '../auth/region-preference.js';
 
 const MANAGED_BACKEND_LANE_PATTERN = /^[A-Za-z0-9._-]+$/u;
 const STARTUP_ENVIRONMENT_OPTION = '--env';
-const ROOT_OPTIONS_WITH_REQUIRED_VALUES = new Set(['--lane', '--resume', '--tui-mode']);
+const ROOT_OPTIONS_WITH_REQUIRED_VALUES = new Set([
+  '--lane',
+  '--resume',
+  '--tui-mode',
+  '-m',
+  '--model',
+]);
 const STARTUP_ENVIRONMENT_ALIASES: Readonly<Record<string, TuiBuildEnvironment>> = Object.freeze({
   test: 'test',
   pre: 'staging',

+ 2 - 0
packages/tui/src/cli/main.ts

@@ -103,6 +103,7 @@ export async function runTuiCli(dependencies: RunTuiCliDependencies = {}): Promi
       allowStartupEnvironmentSelection: dependencies.allowStartupEnvironmentSelection,
       launchTui: async ({
         initialPrompt,
+        model,
         sessionId,
         showSessionPicker,
         continueLatestSession,
@@ -114,6 +115,7 @@ export async function runTuiCli(dependencies: RunTuiCliDependencies = {}): Promi
         await launchTui({
           version: MINIMAX_CODE_VERSION,
           ...(initialPrompt ? { initialPrompt } : {}),
+          ...(model ? { model } : {}),
           ...(sessionId ? { sessionId } : {}),
           ...(showSessionPicker ? { showSessionPicker: true } : {}),
           ...(continueLatestSession ? { continueLatestSession: true } : {}),

+ 27 - 3
packages/tui/src/tui/launcher.ts

@@ -21,7 +21,8 @@ import {
 } from '../host/tui-keybindings.js';
 import { createTuiApp, type CreateTuiAppOptions, type TuiApp } from './app.js';
 import type { CreatedTuiRuntime, CreateTuiRuntimeDependencies } from '../runtime/lifecycle.js';
-import type { TuiWorkspaceRoot } from '../runtime/port.js';
+import { parseHeadlessModelOverride } from '../headless/model-selection.js';
+import type { TuiRuntime, TuiWorkspaceRoot } from '../runtime/port.js';
 import { createDeferredTuiRuntime } from '../runtime/deferred.js';
 import {
   captureTuiIncidentBestEffort,
@@ -66,6 +67,7 @@ const MINIMAX_CODE_EXIT_SLOGAN = 'Intelligence with everyone, bye~';
 export interface LaunchTuiOptions {
   version: string;
   initialPrompt?: string;
+  model?: string;
   sessionId?: string;
   showSessionPicker?: boolean;
   continueLatestSession?: boolean;
@@ -83,7 +85,8 @@ export interface LaunchTuiOptions {
 type LaunchApp = Pick<TuiApp, 'ready' | 'firstFrame' | 'start' | 'stop' | 'stopped' | 'submit'> & {
   readonly editor?: Pick<TuiApp['editor'], 'disableSubmit'>;
   readonly setStartupStatus?: TuiApp['setStartupStatus'];
-  readonly controller?: Pick<TuiApp['controller'], 'snapshot'>;
+  readonly controller?: Pick<TuiApp['controller'], 'snapshot'> &
+    Partial<Pick<TuiApp['controller'], 'ensureSession'>>;
   readonly openSession?: TuiApp['openSession'];
   readonly continueLatestSession?: TuiApp['continueLatestSession'];
   readonly suspend?: TuiApp['suspend'];
@@ -150,6 +153,12 @@ export async function launchTui(
   options: LaunchTuiOptions,
   dependencies: LaunchTuiDependencies = {},
 ): Promise<void> {
+  if (options.model !== undefined) parseHeadlessModelOverride(options.model.trim());
+  if (options.model !== undefined && options.showSessionPicker) {
+    throw new Error(
+      '--model requires a Session id with --session; use --session <id> or --continue.',
+    );
+  }
   if (!options.terminal && (!process.stdin.isTTY || !process.stdout.isTTY)) {
     throw new Error('Minimax Code interactive mode requires a TTY.');
   }
@@ -521,7 +530,7 @@ export async function launchTui(
         durationMs: performance.now() - runtimeStartedAt,
       });
       await app.ready;
-      initialStateReady = await prepareInitialTuiState(app, observability, options);
+      initialStateReady = await prepareInitialTuiState(app, observability, options, runtime.adapter);
       startupStatus.stop();
       startupStatus = undefined;
       if (app.editor) app.editor.disableSubmit = false;
@@ -884,6 +893,7 @@ async function prepareInitialTuiState(
   app: LaunchApp,
   observability: TuiObservability,
   options: LaunchTuiOptions,
+  runtime: TuiRuntime,
 ): Promise<boolean> {
   const sessionId = options.sessionId?.trim();
   if (sessionId) {
@@ -912,6 +922,20 @@ async function prepareInitialTuiState(
       return false;
     }
   }
+  if (options.model !== undefined) {
+    const model = parseHeadlessModelOverride(options.model.trim());
+    if (!app.controller?.ensureSession || !app.openSession) {
+      throw new Error('TUI Session model selection is unavailable.');
+    }
+    const session = await app.controller.ensureSession();
+    // The normal model picker also saves the global default. Startup overrides
+    // must use the Session-only operation, before login checks or any submission.
+    if (!(await runtime.selectSessionModel(model, session.sessionId))) {
+      throw new Error(`Could not select --model ${options.model}. Check the provider and model id.`);
+    }
+    // Rehydrate account status, model/effort and queued-input state from Runtime.
+    await app.openSession(session.sessionId);
+  }
   if (options.showSessionPicker) await app.submit('/sessions');
   return true;
 }

+ 240 - 0
packages/tui/test/unit/tui-app.test.ts

@@ -8,6 +8,10 @@ import {
   VStack,
   type Terminal,
 } from "../../src/tui/engine/public.js";
+import { createTuiProgram } from "../../src/cli/program.js";
+import { resolveTuiStartupEnvironmentOption } from "../../src/cli/environment.js";
+import { runTuiCli } from "../../src/cli/main.js";
+import { launchTui } from "../../src/tui/launcher.js";
 import { createTuiApp } from "../../src/tui/app.js";
 import type {
   TuiModel,
@@ -13176,3 +13180,239 @@ describe("createTuiApp", () => {
     }
   });
 });
+
+describe("interactive CLI model startup", () => {
+  it.each([
+    [
+      "new with prompt",
+      ["-m", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "session-1",
+      true,
+    ],
+    [
+      "new without prompt",
+      ["--model=custom_provider:relay/vendor/model#thinking"],
+      "session-1",
+      false,
+    ],
+    [
+      "explicit session",
+      ["--session", "existing", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "existing",
+      true,
+    ],
+    [
+      "continue",
+      ["--continue", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "existing",
+      true,
+    ],
+    [
+      "missing session",
+      ["--session", "missing", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "missing",
+      false,
+    ],
+    [
+      "empty continue",
+      ["--continue", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "existing",
+      false,
+    ],
+    ["invalid provider", ["--model", "missing/model", "hello"], "session-1", false],
+    ["invalid model", ["--model", "custom_provider:relay/missing", "hello"], "session-1", false],
+  ] as const)(
+    "routes %s through launch, hydration and submission",
+    async (_name, args, sessionId, hasPrompt) => {
+      const dataDir = await mkdtemp(join(tmpdir(), "mcode-model-startup-"));
+      const terminal = new FakeTerminal();
+      const runtime = createRuntime();
+      runtime.listBackgroundTasks = vi.fn(async () => []);
+      const models = new Map<string, { providerId: string; modelId: string; variant?: string }>();
+      const requested = {
+        providerId: "custom_provider:relay",
+        modelId: "vendor/model",
+        variant: "thinking",
+      };
+      const existing = { sessionId: "existing", workspaceDir: "/workspace", updatedAt: 10 };
+      vi.mocked(runtime.listSessions).mockResolvedValue([existing]);
+      vi.mocked(runtime.listSessionPage).mockResolvedValue({
+        sessions: [existing],
+        hasMore: false,
+      });
+      vi.mocked(runtime.getSession).mockImplementation(async (id) => ({
+        sessionId: id,
+        workspaceDir: "/workspace",
+        model: models.get(id),
+      }));
+      const failedResume = _name === "missing session" || _name === "empty continue";
+      if (_name === "missing session")
+        vi.mocked(runtime.getSession).mockRejectedValue(new Error("Session not found"));
+      if (_name === "empty continue") vi.mocked(runtime.listSessions).mockResolvedValue([]);
+      runtime.selectModel = vi.fn(async () => true);
+      runtime.selectSessionModel = vi.fn(async (model, id) => {
+        if (model.providerId !== requested.providerId || model.modelId !== requested.modelId) {
+          throw new Error("Unknown provider or model");
+        }
+        models.set(id, model);
+        return true;
+      });
+      vi.mocked(runtime.listModels).mockImplementation(async (id) => [
+        { ...requested, name: "Startup model", selected: Boolean(id && models.has(id)) },
+      ]);
+      // A global managed default needs login; the selected BYOK Session does not.
+      vi.mocked(runtime.getAccountStatus).mockImplementation(async (id) => ({
+        status: id && models.has(id) ? "ready" : "needs-login",
+        modelSource: id && models.has(id) ? "byok" : "token-plan",
+        managedTokenPresent: false,
+        warnings: [],
+      }));
+      const sentModels: unknown[] = [];
+      vi.mocked(runtime.sendMessage).mockImplementation(async function* (request) {
+        sentModels.push(models.get(request.id));
+        yield { type: "delta", content: "offline reply" };
+        yield { type: "done" };
+      });
+      const invalid = _name.startsWith("invalid");
+      const stderr = vi.fn((_text: string, callback?: () => void) => callback?.());
+      const processRef = {
+        title: "test",
+        argv: ["node", "cli.js", ...args],
+        env: {},
+        versions: { node: "24.2.0" },
+        stdout: {
+          destroyed: false,
+          writableEnded: false,
+          write: vi.fn((_text: string, cb?: () => void) => cb?.()),
+        },
+        stderr: { destroyed: false, writableEnded: false, write: stderr },
+        exit: vi.fn(),
+        exitCode: 0,
+      };
+      let app: ReturnType<typeof createTuiApp> | undefined;
+      const running = runTuiCli({
+        processRef,
+        configureNetworkProxy: () => undefined,
+        launchTui: (input) =>
+          launchTui(
+            { ...input, dataDir, terminal, workspaceDir: "/workspace" },
+            {
+              createObservability,
+              readTelemetryEnabled: () => false,
+              installProcessGuards: () => () => undefined,
+              loadRuntimeLifecycle: async () => ({
+                createTuiRuntime: async () => ({ adapter: runtime }) as never,
+                shutdownTuiRuntime: async () => false,
+              }),
+              loadUpdateApplication: async () =>
+                ({ inspect: async () => ({ status: "up-to-date" }) }) as never,
+              createApp: (options) => {
+                app = createTuiApp({ ...options, productFeatures: { queue: false } });
+                return app;
+              },
+              writeExitMessage: () => undefined,
+            },
+          ),
+      });
+      try {
+        if (invalid) {
+          await running;
+          expect(processRef.exitCode).toBe(1);
+          expect(stderr.mock.calls.flat().join(" ")).toContain("Unknown provider or model");
+          expect(runtime.sendMessage).not.toHaveBeenCalled();
+        } else if (failedResume) {
+          await vi.waitFor(() => expect(app?.editor.disableSubmit).toBe(false));
+          expect(runtime.selectSessionModel).not.toHaveBeenCalled();
+          expect(runtime.createSession).not.toHaveBeenCalled();
+          expect(runtime.sendMessage).not.toHaveBeenCalled();
+        } else {
+          await vi.waitFor(() => {
+            expect(app?.editor.disableSubmit).toBe(false);
+            expect(app?.controller.snapshot().session?.model).toEqual(requested);
+            if (hasPrompt) expect(sentModels).toEqual([requested]);
+          });
+          expect(runtime.selectSessionModel).toHaveBeenCalledWith(requested, sessionId);
+          expect(app?.controller.snapshot().account?.modelSource).toBe("byok");
+          if (sessionId === "existing") expect(runtime.createSession).not.toHaveBeenCalled();
+          if (!hasPrompt) {
+            expect(runtime.sendMessage).not.toHaveBeenCalled();
+            await app?.submit("later prompt");
+            expect(sentModels).toEqual([requested]);
+          }
+          await vi.waitFor(() => expect(app?.controller.snapshot().status).toBe("idle"));
+          await app?.submit("/new");
+          expect(app?.controller.snapshot().session).toBeUndefined();
+          expect(runtime.selectSessionModel).toHaveBeenCalledOnce();
+        }
+        expect(runtime.selectModel).not.toHaveBeenCalled();
+      } finally {
+        await app?.stop();
+        await running;
+        await rm(dataDir, { recursive: true, force: true });
+      }
+    },
+  );
+});
+
+describe("interactive model argument contract", () => {
+  function program() {
+    const launch = vi.fn(async () => undefined);
+    const command = createTuiProgram({
+      version: "test",
+      launchTui: launch,
+      runExec: vi.fn(),
+      runLogin: vi.fn(),
+      runLogout: vi.fn(),
+      runUpdate: vi.fn(),
+    })
+      .exitOverride()
+      .configureOutput({ writeErr: () => undefined });
+    return { command, launch };
+  }
+
+  it.each(["-m", "--model"])("rejects missing values for %s", async (flag) => {
+    const { command, launch } = program();
+    await expect(command.parseAsync([flag], { from: "user" })).rejects.toThrow();
+    expect(launch).not.toHaveBeenCalled();
+  });
+
+  it.each(["", "bare-model", "provider/", "/model", "provider/model#"])(
+    "rejects malformed model %j before launch",
+    async (model) => {
+      const { command, launch } = program();
+      await expect(command.parseAsync(["--model", model], { from: "user" })).rejects.toThrow(
+        "--model must use provider/model",
+      );
+      expect(launch).not.toHaveBeenCalled();
+    },
+  );
+
+  it("rejects a model with an untargeted Session picker", async () => {
+    const { command, launch } = program();
+    await expect(
+      command.parseAsync(["--session", "--model", "provider/model"], { from: "user" }),
+    ).rejects.toThrow("requires a Session id");
+    expect(launch).not.toHaveBeenCalled();
+  });
+
+  it("retains the default launch contract without a model", async () => {
+    const { command, launch } = program();
+    await command.parseAsync(["hello"], { from: "user" });
+    expect(launch).toHaveBeenCalledWith({ initialPrompt: "hello" });
+  });
+
+  it.each(["-m", "--model"])("scans startup environment after %s values", (flag) => {
+    expect(
+      resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "staging"], true),
+    ).toBe("staging");
+    expect(() =>
+      resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "prod"], false),
+    ).toThrow("only available");
+    expect(
+      resolveTuiStartupEnvironmentOption(
+        [flag, "provider/model", "exec", "--env", "staging"],
+        true,
+      ),
+    ).toBeUndefined();
+  });
+});