Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(task): pick a task's model from the task tools and the CLI (#21852)

Lobehub Coder9641167b92b1
diff --git a/.agents/skills/cli/references/goal.md b/.agents/skills/cli/references/goal.md
index 03468675f4b..9b64b160729 100644
--- a/.agents/skills/cli/references/goal.md
+++ b/.agents/skills/cli/references/goal.md
@@ -138,19 +138,21 @@ Submits the wrap-up report from the Goal's wrap-up run.
## Lifecycle, budget and routing
-| Command | Effect |
-| ------------------------------------- | -------------------------------------------------------------------- |
-| `lh goal create <title>` | Create a goal and seed its graph (`--topic`: a draft) |
-| `lh goal start <id>` | Start a draft (`--rollout` folds its seed tasks into a batch) |
-| `lh goal pause <id>` / `resume <id>` | Stop / restart coordination (`--confirm-exit` settles a paused turn) |
-| `lh goal restart <id>` | Reset every unfinished task to backlog |
-| `lh goal delete <id>` | Delete the goal and its graph (`--yes`) |
-| `lh goal tick <id>` | Advance exactly one coordinator step |
-| `lh goal run <id>` | Tick until a stop condition |
-| `lh goal set-budget <id>` | Rounds / cost / experiments / turns / concurrency / attempts |
-| `lh goal set-agent <id> <agent>` | Hand supervision to another agent |
-| `lh goal set-task-agent <id> <agent>` | Route tasks to a dedicated executor (`none` hands them back) |
-| `lh goal bind-topic <id>` | Supervise from the current topic run |
+| Command | Effect |
+| ------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
+| `lh goal create <title>` | Create a goal and seed its graph (`--topic`: a draft; `--task-model` + `--task-provider` pick the task model) |
+| `lh goal start <id>` | Start a draft (`--rollout` folds its seed tasks into a batch) |
+| `lh goal pause <id>` / `resume <id>` | Stop / restart coordination (`--confirm-exit` settles a paused turn) |
+| `lh goal restart <id>` | Reset every unfinished task to backlog |
+| `lh goal delete <id>` | Delete the goal and its graph (`--yes`) |
+| `lh goal tick <id>` | Advance exactly one coordinator step |
+| `lh goal run <id>` | Tick until a stop condition |
+| `lh goal set-budget <id>` | Rounds / cost / experiments / turns / concurrency / attempts |
+| `lh goal set-agent <id> <agent>` | Hand supervision to another agent |
+| `lh goal set-task-agent <id> <agent>` | Route tasks to a dedicated executor (`none` hands them back) |
+| `lh goal set-model <id>` | Planning model: `--model <id> --provider <id>`, `--model none` clears |
+| `lh goal set-task-model <id>` | Model of every task (unfinished ones switch); `--model none` clears |
+| `lh goal bind-topic <id>` | Supervise from the current topic run |
`create --topic` links a Goal to the conversation it was created from and
returns a `turnToken` for the first plan; without it the Goal is standalone and
diff --git a/apps/cli/src/commands/goal/assignment.test.ts b/apps/cli/src/commands/goal/assignment.test.ts
new file mode 100644
index 00000000000..dc8e921b626
--- /dev/null
+++ b/apps/cli/src/commands/goal/assignment.test.ts
@@ -0,0 +1,144 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ ensureCreatedGoalTaskModel,
+ parseGoalModelConfig,
+ registerGoalAssignmentCommands,
+} from './assignment';
+
+const mocks = vi.hoisted(() => ({
+ getTrpcClient: vi.fn(),
+ setModel: vi.fn(),
+ setTaskModel: vi.fn(),
+ warn: vi.fn(),
+}));
+
+vi.mock('../../api/client', () => ({ getTrpcClient: mocks.getTrpcClient }));
+vi.mock('../../utils/logger', () => ({
+ log: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: mocks.warn },
+}));
+
+const run = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerGoalAssignmentCommands(program.command('goal'));
+ await program.parseAsync(['node', 'test', 'goal', ...args]);
+};
+
+describe('parseGoalModelConfig', () => {
+ it('needs a provider with a model, and a model with a provider', () => {
+ expect(() => parseGoalModelConfig({ model: 'gpt-5' })).toThrow('--model requires --provider');
+ expect(() => parseGoalModelConfig({ provider: 'openai' })).toThrow(
+ '--provider requires --model',
+ );
+ });
+
+ it('reads none/null as clearing and nothing as unset', () => {
+ expect(parseGoalModelConfig({ model: 'none' })).toBeNull();
+ expect(parseGoalModelConfig({ model: 'null', provider: 'openai' })).toBeNull();
+ expect(parseGoalModelConfig({})).toBeUndefined();
+ expect(parseGoalModelConfig({ model: 'gpt-5', provider: 'openai' })).toEqual({
+ model: 'gpt-5',
+ provider: 'openai',
+ });
+ });
+});
+
+describe('goal model commands', () => {
+ afterEach(() => {
+ process.exitCode = undefined;
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.setModel.mockResolvedValue({ message: 'Goal model updated' });
+ mocks.setTaskModel.mockResolvedValue({ message: 'Goal task model updated' });
+ mocks.getTrpcClient.mockResolvedValue({
+ goal: {
+ setModel: { mutate: mocks.setModel },
+ setTaskModel: { mutate: mocks.setTaskModel },
+ },
+ });
+ });
+
+ it('sets the planning model', async () => {
+ await run('set-model', 'goal_1', '--model', 'gpt-5', '--provider', 'openai');
+
+ expect(mocks.setModel).toHaveBeenCalledWith({
+ id: 'goal_1',
+ modelConfig: { model: 'gpt-5', provider: 'openai' },
+ });
+ });
+
+ it('sets and clears the task model', async () => {
+ await run('set-task-model', 'goal_1', '--model', 'deepseek-flash', '--provider', 'lobehub');
+ await run('set-task-model', 'goal_1', '--model', 'none');
+
+ expect(mocks.setTaskModel).toHaveBeenNthCalledWith(1, {
+ id: 'goal_1',
+ modelConfig: { model: 'deepseek-flash', provider: 'lobehub' },
+ });
+ expect(mocks.setTaskModel).toHaveBeenNthCalledWith(2, { id: 'goal_1', modelConfig: null });
+ });
+
+ it('skips the follow-up write when the server already applied the model at creation', async () => {
+ const client = await mocks.getTrpcClient();
+
+ await ensureCreatedGoalTaskModel(
+ client,
+ { config: { taskModel: 'gpt-5' }, id: 'goal_1' },
+ { model: 'gpt-5', provider: 'openai' },
+ );
+
+ expect(mocks.setTaskModel).not.toHaveBeenCalled();
+ });
+
+ it('applies the model afterwards on a server that dropped the field', async () => {
+ const client = await mocks.getTrpcClient();
+
+ await ensureCreatedGoalTaskModel(
+ client,
+ { config: {}, id: 'goal_1' },
+ { model: 'gpt-5', provider: 'openai' },
+ );
+
+ expect(mocks.setTaskModel).toHaveBeenCalledWith({
+ id: 'goal_1',
+ modelConfig: { model: 'gpt-5', provider: 'openai' },
+ });
+ });
+
+ // A follow-up write would change the config the turn's snapshot covers, and
+ // the printed token's first plan would be rejected as stale_input.
+ it('keeps the planning token valid when the server dropped the field', async () => {
+ const client = await mocks.getTrpcClient();
+
+ await ensureCreatedGoalTaskModel(
+ client,
+ { config: {}, id: 'goal_1' },
+ { model: 'gpt-5', provider: 'openai' },
+ 'turn-token',
+ );
+
+ expect(mocks.setTaskModel).not.toHaveBeenCalled();
+ expect(mocks.warn).toHaveBeenCalledWith(expect.stringContaining('Submit the plan first'));
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('keeps a created goal when its task model is refused, with a retry hint', async () => {
+ const client = await mocks.getTrpcClient();
+ mocks.setTaskModel.mockRejectedValueOnce(new Error('model is fixed'));
+
+ await ensureCreatedGoalTaskModel(
+ client,
+ { id: 'goal_1' },
+ { model: 'gpt-5', provider: 'openai' },
+ );
+
+ expect(mocks.warn).toHaveBeenCalledWith(
+ expect.stringContaining('lh goal set-task-model goal_1'),
+ );
+ expect(process.exitCode).toBe(1);
+ });
+});
diff --git a/apps/cli/src/commands/goal/assignment.ts b/apps/cli/src/commands/goal/assignment.ts
new file mode 100644
index 00000000000..5a7725e15b2
--- /dev/null
+++ b/apps/cli/src/commands/goal/assignment.ts
@@ -0,0 +1,91 @@
+import type { Command } from 'commander';
+
+import type { TrpcClient } from '../../api/client';
+import { getTrpcClient } from '../../api/client';
+import { log } from '../../utils/logger';
+
+const CLEAR_VALUES = new Set(['none', 'null']);
+
+/**
+ * `--model` / `--provider` as the goal model mutations take them: both set, or
+ * `null` (model "none"/"null") to drop the override. Unlike a Task, a goal
+ * override is always stored as a pair, so a model needs its provider.
+ */
+export const parseGoalModelConfig = (
+ options: { model?: string; provider?: string },
+ flags = { model: '--model', provider: '--provider' },
+): { model: string; provider: string } | null | undefined => {
+ const model = options.model?.trim();
+ const provider = options.provider?.trim();
+ if (!model) {
+ if (provider) throw new Error(`${flags.provider} requires ${flags.model}`);
+ return undefined;
+ }
+ if (CLEAR_VALUES.has(model.toLowerCase())) return null;
+ if (!provider) throw new Error(`${flags.model} requires ${flags.provider}`);
+ return { model, provider };
+};
+
+/**
+ * `lh goal create --task-model` travels with the create call, so the server
+ * applies it before the first coordinator step. This CLI ships on its own: a
+ * server that predates the field drops it, which shows as a goal without the
+ * model, and only then does the follow-up mutation apply it. That late write
+ * can miss a Task already started; a refusal keeps the goal and says how to retry.
+ * It is skipped while a planning turn is open: the turn's snapshot covers the goal
+ * config, so writing now would make the printed token's first plan stale.
+ */
+export const ensureCreatedGoalTaskModel = async (
+ client: TrpcClient,
+ goal: { config?: { taskModel?: string | null } | null; id: string },
+ modelConfig: { model: string; provider: string } | null | undefined,
+ turnToken?: string,
+) => {
+ if (!modelConfig || goal.config?.taskModel === modelConfig.model) return;
+ if (turnToken) {
+ log.warn(
+ `This server did not apply --task-model. Submit the plan first, then run: lh goal set-task-model ${goal.id} --model ${modelConfig.model} --provider ${modelConfig.provider}`,
+ );
+ process.exitCode = 1;
+ return;
+ }
+ try {
+ await client.goal.setTaskModel.mutate({ id: goal.id, modelConfig });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log.warn(
+ `Goal created, but its task model was not set (${message}). Retry: lh goal set-task-model ${goal.id} --model ${modelConfig.model} --provider ${modelConfig.provider}`,
+ );
+ // The goal exists, so finish the output, but scripts must see the flag did not apply.
+ process.exitCode = 1;
+ }
+};
+
+/** Which model a goal's planning and Tasks run on. Its agents live in `access.ts`. */
+export function registerGoalAssignmentCommands(goal: Command) {
+ goal
+ .command('set-model <id>')
+ .description(
+ 'Pick the model the goal agent plans with; --model none returns to the agent default',
+ )
+ .requiredOption('--model <model>', 'Model ID, or "none" to clear the override')
+ .option('--provider <provider>', 'Provider of --model (required unless clearing)')
+ .action(async (id: string, options: { model: string; provider?: string }) => {
+ const modelConfig = parseGoalModelConfig(options) ?? null;
+ const result = await (await getTrpcClient()).goal.setModel.mutate({ id, modelConfig });
+ log.info(result?.message ?? 'Goal model updated');
+ });
+
+ goal
+ .command('set-task-model <id>')
+ .description(
+ "Pick the model every task of the goal runs on (unfinished tasks switch too); --model none returns them to their executor's model",
+ )
+ .requiredOption('--model <model>', 'Model ID, or "none" to clear the override')
+ .option('--provider <provider>', 'Provider of --model (required unless clearing)')
+ .action(async (id: string, options: { model: string; provider?: string }) => {
+ const modelConfig = parseGoalModelConfig(options) ?? null;
+ const result = await (await getTrpcClient()).goal.setTaskModel.mutate({ id, modelConfig });
+ log.info(result?.message ?? 'Goal task model updated');
+ });
+}
diff --git a/apps/cli/src/commands/goal/index.ts b/apps/cli/src/commands/goal/index.ts
index 853cd41e586..eff6fa7219c 100644
--- a/apps/cli/src/commands/goal/index.ts
+++ b/apps/cli/src/commands/goal/index.ts
@@ -20,6 +20,11 @@ import { confirm, outputJson, printTable, truncate } from '../../utils/format';
import { log } from '../../utils/logger';
import { resolveAppUrlBuilder } from '../task/url';
import { registerGoalAccessCommands } from './access';
+import {
+ ensureCreatedGoalTaskModel,
+ parseGoalModelConfig,
+ registerGoalAssignmentCommands,
+} from './assignment';
import { registerGoalGraphEditCommands } from './graphEdit';
import {
type GoalMetricState,
@@ -591,6 +596,8 @@ export function registerGoalCommand(program: Command) {
'--task-agent <id>',
"Dedicated executor for the goal's tasks (defaults to the goal agent)",
)
+ .option('--task-model <model>', "Model the goal's tasks run on (needs --task-provider)")
+ .option('--task-provider <provider>', 'Provider of --task-model')
.option('--project <id>', 'Project ID')
.option(
'--visibility <visibility>',
@@ -643,6 +650,10 @@ export function registerGoalCommand(program: Command) {
...((options.task as string[] | undefined) ?? []),
...(options.taskFile ? parseTaskFile(await readFile(options.taskFile, 'utf8')) : []),
];
+ const taskModel = parseGoalModelConfig(
+ { model: options.taskModel, provider: options.taskProvider },
+ { model: '--task-model', provider: '--task-provider' },
+ );
const seedProblem = goalSeedDependencyProblem(seedTasks);
if (seedProblem) throw new Error(`--task-file: ${seedProblem}`);
const operationId = process.env.LOBEHUB_OPERATION_ID;
@@ -711,6 +722,7 @@ export function registerGoalCommand(program: Command) {
projectId: options.project,
requirement: options.requirement,
title,
+ taskModelConfig: taskModel ?? undefined,
tasks: seedTasks.length ? seedTasks : undefined,
visibility: options.visibility,
};
@@ -744,6 +756,7 @@ export function registerGoalCommand(program: Command) {
`The server did not draw these dependsOn edges (it may predate dependsOn); add them with \`lh goal add-edge\`: ${undrawn.join('; ')}`,
);
const turnToken = 'turnToken' in result ? result.turnToken : undefined;
+ await ensureCreatedGoalTaskModel(client, result.data!.goal, taskModel, turnToken);
// `goal.create` returns the whole graph snapshot, so the id is on its
// goal β€” `result.data.id` is undefined, and the CLI cannot resolve the
// router's types to catch that, which is how it reached a printed URL.
@@ -1172,6 +1185,7 @@ export function registerGoalCommand(program: Command) {
);
registerGoalAccessCommands(goal);
+ registerGoalAssignmentCommands(goal);
goal
.command('bind-topic <id>')
diff --git a/apps/cli/src/commands/task.model.test.ts b/apps/cli/src/commands/task.model.test.ts
new file mode 100644
index 00000000000..6981766bc67
--- /dev/null
+++ b/apps/cli/src/commands/task.model.test.ts
@@ -0,0 +1,137 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerTaskCommand } from './task';
+
+const mocks = vi.hoisted(() => ({
+ agentConfig: vi.fn(),
+ create: vi.fn(),
+ detail: vi.fn(),
+ getTrpcClient: vi.fn(),
+ update: vi.fn(),
+}));
+
+vi.mock('../api/client', () => ({ getTrpcClient: mocks.getTrpcClient }));
+vi.mock('../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));
+vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://app.example.com' }));
+vi.mock('../utils/logger', () => ({
+ log: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },
+}));
+
+const run = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerTaskCommand(program);
+ await program.parseAsync(['node', 'test', 'task', ...args]);
+};
+
+describe('task model flags', () => {
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const task = { id: 'task_1', identifier: 'T-1', name: 'Run' };
+ mocks.create.mockReset().mockResolvedValue({ data: task, success: true });
+ mocks.update.mockReset().mockResolvedValue({ data: task, success: true });
+ mocks.detail.mockReset();
+ mocks.agentConfig.mockReset();
+ mocks.getTrpcClient.mockResolvedValue({
+ agent: { getAgentConfigById: { query: mocks.agentConfig } },
+ task: {
+ create: { mutate: mocks.create },
+ detail: { query: mocks.detail },
+ update: { mutate: mocks.update },
+ },
+ });
+ });
+
+ afterEach(() => {
+ consoleSpy.mockRestore();
+ });
+
+ it('creates a task with --model and --provider in config', async () => {
+ await run(
+ 'create',
+ '-i',
+ 'Run',
+ '--agent',
+ 'agt_1',
+ '--model',
+ 'deepseek-flash',
+ '--provider',
+ 'lobehub',
+ );
+
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ config: { model: 'deepseek-flash', provider: 'lobehub' } }),
+ );
+ });
+
+ it('creates without config when no model flag is passed', async () => {
+ await run('create', '-i', 'Run', '--agent', 'agt_1');
+
+ expect(mocks.create.mock.calls[0][0]).not.toHaveProperty('config');
+ });
+
+ it('edits the model through a merged config patch', async () => {
+ await run('edit', 'T-1', '--model', 'deepseek-flash', '--provider', 'lobehub');
+
+ expect(mocks.update).toHaveBeenCalledWith({
+ configPatch: { model: 'deepseek-flash', provider: 'lobehub' },
+ id: 'T-1',
+ });
+ });
+
+ it('clears the override with --model null', async () => {
+ await run('edit', 'T-1', '--model', 'null');
+
+ expect(mocks.update).toHaveBeenCalledWith({
+ configPatch: { model: null, provider: null },
+ id: 'T-1',
+ });
+ });
+
+ it('shows the model of an unassigned task without looking up an agent', async () => {
+ mocks.detail.mockResolvedValue({
+ data: {
+ config: { model: 'deepseek-flash', provider: 'lobehub' },
+ id: 'task_1',
+ identifier: 'T-1',
+ instruction: 'Run',
+ name: 'Run',
+ priority: 0,
+ status: 'backlog',
+ },
+ });
+
+ await run('view', 'T-1');
+
+ expect(mocks.agentConfig).not.toHaveBeenCalled();
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.stringContaining('lobehub/deepseek-flash (pinned)'),
+ );
+ });
+
+ it('shows whether the task model overrides its agent in view', async () => {
+ mocks.detail.mockResolvedValue({
+ data: {
+ agentId: 'agt_1',
+ config: { model: 'deepseek-flash', provider: 'lobehub' },
+ id: 'task_1',
+ identifier: 'T-1',
+ instruction: 'Run',
+ name: 'Run',
+ priority: 0,
+ status: 'backlog',
+ },
+ });
+ mocks.agentConfig.mockResolvedValue({ model: 'claude-opus', provider: 'anthropic' });
+
+ await run('view', 'T-1');
+
+ expect(mocks.agentConfig).toHaveBeenCalledWith({ agentId: 'agt_1' });
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.stringContaining('lobehub/deepseek-flash (override)'),
+ );
+ });
+});
diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.ts
index e9843a2855e..d7ce5ca315c 100644
--- a/apps/cli/src/commands/task/index.ts
+++ b/apps/cli/src/commands/task/index.ts
@@ -21,6 +21,7 @@ import { registerDepCommands } from './dep';
import { registerDocCommands } from './doc';
import { briefIcon, priorityLabel, statusBadge } from './helpers';
import { registerLifecycleCommands } from './lifecycle';
+import { formatTaskModel, toCreateModelConfig, toModelConfigPatch } from './model';
import { registerReviewCommands } from './review';
import { registerTopicCommands } from './topic';
import { resolveAppUrl, resolveAppUrlBuilder, taskPath } from './url';
@@ -296,6 +297,12 @@ export function registerTaskCommand(program: Command) {
console.log(`${pc.dim('Instruction:')} ${t.instruction}`);
if (t.description) console.log(`${pc.dim('Description:')} ${t.description}`);
if (t.agentId) console.log(`${pc.dim('Agent:')} ${t.agentId}`);
+ // Comparing against the agent's current default tells an override apart
+ // from the snapshot every assigned task gets at creation.
+ const agentConfig = t.agentId
+ ? await client.agent.getAgentConfigById.query({ agentId: t.agentId }).catch(() => null)
+ : null;
+ console.log(`${pc.dim('Model:')} ${formatTaskModel(t.config, agentConfig)}`);
if (t.userId) console.log(`${pc.dim('User:')} ${t.userId}`);
if (t.parent) {
console.log(`${pc.dim('Parent:')} ${t.parent.identifier} ${t.parent.name || ''}`);
@@ -542,15 +549,19 @@ export function registerTaskCommand(program: Command) {
.option('--user <idOrEmail>', 'Assign to a workspace member (user id, email or username)')
.option('--parent <id>', 'Parent task ID')
.option('--priority <n>', 'Priority (0=none, 1=urgent, 2=high, 3=normal, 4=low)', '0')
+ .option('--model <model>', "Model to run with (default: the assignee agent's model)")
+ .option('--provider <provider>', 'Provider for --model (default: resolved from the agent)')
.option('--json [fields]', 'Output JSON')
.action(
async (options: {
agent?: string;
instruction: string;
json?: string | boolean;
+ model?: string;
name?: string;
parent?: string;
priority?: string;
+ provider?: string;
user?: string;
}) => {
const client = await getTrpcClient();
@@ -566,6 +577,8 @@ export function registerTaskCommand(program: Command) {
if (assigneeUserId) input.assigneeUserId = assigneeUserId;
if (options.parent) input.parentTaskId = options.parent;
if (options.priority) input.priority = Number.parseInt(options.priority, 10);
+ const modelConfig = toCreateModelConfig(options);
+ if (modelConfig) input.config = modelConfig;
const result = await client.task.create.mutate(input);
const url = buildUrl(taskPath(result.data.identifier, result.data.name));
@@ -594,6 +607,8 @@ export function registerTaskCommand(program: Command) {
.option('--heartbeat-interval <n>', 'Heartbeat interval in seconds')
.option('--heartbeat-timeout <n>', 'Heartbeat timeout in seconds (0 to disable)')
.option('--description <text>', 'Task description')
+ .option('--model <model>', 'Model to run with ("null" to follow the assignee agent again)')
+ .option('--provider <provider>', 'Provider for the model (default: resolved from the agent)')
.option(
'--status <status>',
'Set status (backlog, running, paused, completed, failed, canceled)',
@@ -609,8 +624,10 @@ export function registerTaskCommand(program: Command) {
heartbeatTimeout?: string;
instruction?: string;
json?: string | boolean;
+ model?: string;
name?: string;
priority?: string;
+ provider?: string;
status?: string;
user?: string;
},
@@ -632,6 +649,9 @@ export function registerTaskCommand(program: Command) {
const val = Number.parseInt(options.heartbeatTimeout, 10);
input.heartbeatTimeout = val === 0 ? null : val;
}
+ // Deep-merged into config, so checkpoint / review / execution keys survive.
+ const configPatch = toModelConfigPatch(options);
+ if (configPatch) input.configPatch = configPatch;
const hasFieldEdits = Object.keys(input).length > 1;
// Status-only edits use the lifecycle API. Combined edits go through
diff --git a/apps/cli/src/commands/task/model.test.ts b/apps/cli/src/commands/task/model.test.ts
new file mode 100644
index 00000000000..d24275c4555
--- /dev/null
+++ b/apps/cli/src/commands/task/model.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatTaskModel, toCreateModelConfig, toModelConfigPatch } from './model';
+
+describe('toCreateModelConfig', () => {
+ it('sends only the flags given', () => {
+ expect(toCreateModelConfig({})).toBeUndefined();
+ expect(toCreateModelConfig({ model: 'deepseek-flash' })).toEqual({ model: 'deepseek-flash' });
+ expect(toCreateModelConfig({ model: 'deepseek-flash', provider: 'lobehub' })).toEqual({
+ model: 'deepseek-flash',
+ provider: 'lobehub',
+ });
+ });
+
+ it('treats "null" on create as no override', () => {
+ expect(toCreateModelConfig({ model: 'null' })).toBeUndefined();
+ });
+
+ it('refuses --provider without --model', () => {
+ expect(() => toCreateModelConfig({ provider: 'lobehub' })).toThrow(
+ '--provider requires --model',
+ );
+ });
+});
+
+describe('toModelConfigPatch', () => {
+ it('clears model and provider for --model null or none', () => {
+ expect(toModelConfigPatch({ model: 'null' })).toEqual({ model: null, provider: null });
+ expect(toModelConfigPatch({ model: 'NONE' })).toEqual({ model: null, provider: null });
+ });
+
+ it('drops the stored provider for a model-only edit', () => {
+ expect(toModelConfigPatch({ model: 'gpt-5' })).toEqual({ model: 'gpt-5', provider: null });
+ });
+
+ it('patches the pair or the provider alone', () => {
+ expect(toModelConfigPatch({ model: 'gpt-5', provider: 'openai' })).toEqual({
+ model: 'gpt-5',
+ provider: 'openai',
+ });
+ expect(toModelConfigPatch({ provider: 'openai' })).toEqual({ provider: 'openai' });
+ expect(toModelConfigPatch({})).toBeUndefined();
+ expect(toModelConfigPatch({ model: '' })).toBeUndefined();
+ });
+});
+
+describe('formatTaskModel', () => {
+ it('says the task follows its agent when no model is stored', () => {
+ expect(formatTaskModel({})).toBe('follows assignee agent');
+ expect(formatTaskModel({ model: null })).toBe('follows assignee agent');
+ });
+
+ it('labels a model that differs from the agent default as an override', () => {
+ expect(
+ formatTaskModel(
+ { model: 'deepseek-flash', provider: 'lobehub' },
+ { model: 'claude-opus', provider: 'anthropic' },
+ ),
+ ).toBe('lobehub/deepseek-flash (override)');
+ });
+
+ it('labels the creation snapshot as pinned to the agent default', () => {
+ expect(
+ formatTaskModel(
+ { model: 'claude-opus', provider: 'anthropic' },
+ { model: 'claude-opus', provider: 'anthropic' },
+ ),
+ ).toBe('anthropic/claude-opus (pinned, same as agent default)');
+ expect(formatTaskModel({ model: 'claude-opus' }, null)).toBe('claude-opus (pinned)');
+ });
+});
diff --git a/apps/cli/src/commands/task/model.ts b/apps/cli/src/commands/task/model.ts
new file mode 100644
index 00000000000..52354a2c310
--- /dev/null
+++ b/apps/cli/src/commands/task/model.ts
@@ -0,0 +1,73 @@
+/**
+ * `--model` / `--provider` values. `null` or `none` clears the field; an
+ * omitted flag leaves it alone.
+ */
+export interface TaskModelOptions {
+ model?: string;
+ provider?: string;
+}
+
+type ModelConfig = { model?: string | null; provider?: string | null };
+
+const CLEAR_VALUES = new Set(['none', 'null']);
+
+// An empty value is no flag at all; only an explicit none/null clears.
+const readFlag = (value: string | undefined): string | null | undefined => {
+ const trimmed = value?.trim();
+ if (!trimmed) return undefined;
+ return CLEAR_VALUES.has(trimmed.toLowerCase()) ? null : trimmed;
+};
+
+/**
+ * `config` for `task create`. Only explicit values are sent; a missing model or
+ * provider is filled from the assignee agent's snapshot by the server, as for a
+ * task created in the app.
+ */
+export const toCreateModelConfig = (options: TaskModelOptions) => {
+ const model = readFlag(options.model);
+ const provider = readFlag(options.provider);
+ // The server would pair it with the agent's model, which that provider may not serve.
+ if (provider && !model) throw new Error('--provider requires --model');
+ const config: { model?: string; provider?: string } = {};
+ if (model) config.model = model;
+ if (provider) config.provider = provider;
+ return Object.keys(config).length > 0 ? config : undefined;
+};
+
+/**
+ * Deep-merge `configPatch` for `task edit`, matching the app's model picker:
+ * - `--model null` clears model and provider; the next run uses the assignee
+ * agent's model again.
+ * - `--model` without `--provider` clears the stored provider, so the server
+ * resolves it from the assignee agent rather than pairing the new model with
+ * the previous provider.
+ */
+export const toModelConfigPatch = (options: TaskModelOptions): ModelConfig | undefined => {
+ const model = readFlag(options.model);
+ const provider = readFlag(options.provider);
+ if (model === undefined && provider === undefined) return undefined;
+ if (model === null) return { model: null, provider: null };
+ if (model === undefined) return { provider };
+ return { model, provider: provider ?? null };
+};
+
+/**
+ * The model line of `task view`. A model on the task is pinned to it β€” set
+ * explicitly or snapshotted from the assignee at creation; without one the
+ * next run takes the assignee agent's current model.
+ */
+export const formatTaskModel = (
+ config: Record<string, unknown> | null | undefined,
+ agentModel?: { model?: string | null; provider?: string | null } | null,
+): string => {
+ const model = typeof config?.model === 'string' ? config.model : undefined;
+ const provider = typeof config?.provider === 'string' ? config.provider : undefined;
+ if (!model) return 'follows assignee agent';
+
+ const label = provider ? `${provider}/${model}` : model;
+ if (!agentModel?.model) return `${label} (pinned)`;
+ const sameAsAgent =
+ agentModel.model === model &&
+ (!provider || !agentModel.provider || agentModel.provider === provider);
+ return `${label} (${sameAsAgent ? 'pinned, same as agent default' : 'override'})`;
+};
diff --git a/apps/server/src/routers/lambda/goal/creation.taskModel.test.ts b/apps/server/src/routers/lambda/goal/creation.taskModel.test.ts
new file mode 100644
index 00000000000..3fa6b59a97d
--- /dev/null
+++ b/apps/server/src/routers/lambda/goal/creation.taskModel.test.ts
@@ -0,0 +1,84 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(function () {
+ return (opts: any) => opts.next({ ctx: opts.ctx });
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {
+ const { authedProcedure } = await import('@/libs/trpc/lambda');
+ return { ...(await importOriginal<object>()), wsCompatProcedure: authedProcedure };
+});
+
+const mocks = vi.hoisted(() => ({
+ create: vi.fn(),
+ delete: vi.fn(),
+ scheduleGoalAdvance: vi.fn(),
+ setTaskModel: vi.fn(),
+}));
+
+vi.mock('@/server/services/goal', () => ({
+ GoalService: vi.fn(function () {
+ return { create: mocks.create, delete: mocks.delete, setTaskModel: mocks.setTaskModel };
+ }),
+}));
+vi.mock('@/server/services/goal/scheduler', () => ({
+ scheduleGoalAdvance: mocks.scheduleGoalAdvance,
+}));
+vi.mock('@/database/models/goal', () => ({ GoalModel: vi.fn() }));
+
+const { creationRouter } = await import('./creation');
+
+const modelConfig = { model: 'deepseek-flash', provider: 'lobehub' };
+const caller = () =>
+ creationRouter.createCaller({ serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' } as any);
+
+describe('goal.create with a task model', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.create.mockResolvedValue({ goal: { config: {}, id: 'goal_1' }, nodes: [] });
+ mocks.delete.mockResolvedValue(undefined);
+ mocks.scheduleGoalAdvance.mockResolvedValue(undefined);
+ mocks.setTaskModel.mockResolvedValue({
+ config: { taskModel: 'deepseek-flash', taskProvider: 'lobehub' },
+ id: 'goal_1',
+ });
+ });
+
+ it('applies the model before the first coordinator step is scheduled', async () => {
+ const result = await caller().create({ taskModelConfig: modelConfig, title: 'Goal' });
+
+ expect(mocks.setTaskModel).toHaveBeenCalledWith('goal_1', modelConfig);
+ expect(mocks.setTaskModel.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.scheduleGoalAdvance.mock.invocationCallOrder[0],
+ );
+ expect(mocks.create.mock.calls[0][0]).not.toHaveProperty('taskModelConfig');
+ expect(result?.data.goal.config?.taskModel).toBe('deepseek-flash');
+ });
+
+ it('removes the goal and schedules nothing when the model is refused', async () => {
+ mocks.setTaskModel.mockRejectedValue(new Error('This model is not available'));
+
+ await expect(
+ caller().create({ taskModelConfig: modelConfig, title: 'Goal' }),
+ ).rejects.toThrow();
+
+ expect(mocks.delete).toHaveBeenCalledWith('goal_1');
+ expect(mocks.scheduleGoalAdvance).not.toHaveBeenCalled();
+ });
+
+ it('leaves a goal without a task model on the existing path', async () => {
+ await caller().create({ title: 'Goal' });
+
+ expect(mocks.setTaskModel).not.toHaveBeenCalled();
+ expect(mocks.scheduleGoalAdvance).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/server/src/routers/lambda/goal/creation.ts b/apps/server/src/routers/lambda/goal/creation.ts
index b93088260c6..7537ec7489f 100644
--- a/apps/server/src/routers/lambda/goal/creation.ts
+++ b/apps/server/src/routers/lambda/goal/creation.ts
@@ -1,4 +1,5 @@
import { ROLLOUT_MAX_CANARY_SIZE } from '@lobechat/const/goal';
+import type { GoalItem } from '@lobechat/types';
import { GOAL_VISIBILITIES, MAX_GOAL_METRIC_CRITERIA } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -16,6 +17,33 @@ import {
import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
import { goalWriteProcedure, idInput, mapGoalError } from '../goalProcedures';
+/**
+ * The model the goal's Tasks run on, picked at creation. Applied before the
+ * first coordinator step is scheduled, through the same checks as
+ * `setTaskModel`, so no Task can start on the executor's default first.
+ */
+const taskModelConfigInput = z.object({ model: z.string().min(1), provider: z.string().min(1) });
+
+/**
+ * Apply a creation-time task model, or remove the goal it was refused for: the
+ * caller asked for a goal on that model, and the coordinator has not been
+ * scheduled yet, so nothing of it has run.
+ */
+const applyCreatedTaskModel = async <T extends { goal: GoalItem }>(
+ service: GoalService,
+ graph: T,
+ modelConfig: z.infer<typeof taskModelConfigInput> | undefined,
+): Promise<T> => {
+ if (!modelConfig) return graph;
+ try {
+ // The returned goal carries the model, so the caller can confirm it applied.
+ return { ...graph, goal: await service.setTaskModel(graph.goal.id, modelConfig) };
+ } catch (error) {
+ await service.delete(graph.goal.id).catch(() => {});
+ throw error;
+ }
+};
+
/** Everything a goal is created from except who owns it. */
const conversationGoalInput = z.object({
config: z
@@ -108,6 +136,7 @@ const conversationGoalInput = z.object({
projectId: z.string().optional(),
requirement: z.string().optional(),
title: z.string().min(1),
+ taskModelConfig: taskModelConfigInput.optional(),
/** Seed task nodes; `dependsOn` names other seeds by title. */
tasks: z
.array(
@@ -319,13 +348,16 @@ export const creationRouter = router({
}),
)
.mutation(
- async ({ ctx, input: { conversationOperationId, conversationTopicId, ...input } }) => {
+ async ({
+ ctx,
+ input: { conversationOperationId, conversationTopicId, taskModelConfig, ...input },
+ }) => {
try {
if (conversationOperationId) {
const { agentId, createdByAgentId: _createdBy, ...goalInput } = input;
const { graph, turnToken } = await ctx.goalService.createFromConversation(
conversationOperationId,
- goalInput,
+ { ...goalInput, taskModelConfig },
conversationTopicId && agentId
? { agentId, topicId: conversationTopicId }
: undefined,
@@ -339,7 +371,11 @@ export const creationRouter = router({
return { data: graph, message: 'Goal created', success: true, turnToken };
}
const { draft: _draft, ...standaloneInput } = input;
- const data = await ctx.goalService.create(standaloneInput);
+ const data = await applyCreatedTaskModel(
+ ctx.goalService,
+ await ctx.goalService.create(standaloneInput),
+ taskModelConfig,
+ );
// A goal is not a document β€” creating one means starting it. The
// coordinator takes it from here without a client holding a loop open.
await scheduleGoalAdvance({
diff --git a/apps/server/src/services/goal/GoalService/createFromConversation.taskModel.test.ts b/apps/server/src/services/goal/GoalService/createFromConversation.taskModel.test.ts
new file mode 100644
index 00000000000..76419fe36b9
--- /dev/null
+++ b/apps/server/src/services/goal/GoalService/createFromConversation.taskModel.test.ts
@@ -0,0 +1,73 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createFromConversation } from './creation';
+
+const mocks = vi.hoisted(() => ({ adoptConversationTurn: vi.fn() }));
+
+vi.mock('../manager', () => ({
+ GoalManagerService: vi.fn(function () {
+ return { adoptConversationTurn: mocks.adoptConversationTurn };
+ }),
+}));
+
+const modelConfig = { model: 'deepseek-flash', provider: 'lobehub' };
+
+const setup = () => ({
+ create: vi.fn().mockResolvedValue({ goal: { id: 'goal_1' } }),
+ db: {},
+ goalModel: { delete: vi.fn().mockResolvedValue(undefined) },
+ graphModel: { getGraph: vi.fn().mockResolvedValue({ goal: { id: 'goal_1' } }) },
+ resolveTopicRun: vi.fn().mockResolvedValue({ agentId: 'agt_1', topicId: 'tpc_1' }),
+ setTaskModel: vi.fn().mockResolvedValue({ id: 'goal_1' }),
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+});
+
+describe('createFromConversation with a task model', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.adoptConversationTurn.mockResolvedValue({ token: 'turn-token' });
+ });
+
+ // The turn snapshot covers the goal config; writing the model after adoption
+ // made the run's first plan fail as stale_input.
+ it('applies the model before adopting the planning turn', async () => {
+ const ctx = setup();
+
+ const result = await createFromConversation(ctx as any, 'op_1', {
+ taskModelConfig: modelConfig,
+ title: 'Goal',
+ } as any);
+
+ expect(ctx.setTaskModel).toHaveBeenCalledWith('goal_1', modelConfig);
+ expect(ctx.setTaskModel.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.adoptConversationTurn.mock.invocationCallOrder[0],
+ );
+ expect(ctx.create.mock.calls[0][0]).not.toHaveProperty('taskModelConfig');
+ expect(result.turnToken).toBe('turn-token');
+ });
+
+ it('removes the goal and adopts no turn when the model is refused', async () => {
+ const ctx = setup();
+ ctx.setTaskModel.mockRejectedValue(new Error('This model is not available'));
+
+ await expect(
+ createFromConversation(ctx as any, 'op_1', {
+ taskModelConfig: modelConfig,
+ title: 'Goal',
+ } as any),
+ ).rejects.toThrow('not available');
+
+ expect(ctx.goalModel.delete).toHaveBeenCalledWith('goal_1');
+ expect(mocks.adoptConversationTurn).not.toHaveBeenCalled();
+ });
+
+ it('leaves a goal without a task model on the existing path', async () => {
+ const ctx = setup();
+
+ await createFromConversation(ctx as any, 'op_1', { title: 'Goal' } as any);
+
+ expect(ctx.setTaskModel).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/goal/GoalService/creation.ts b/apps/server/src/services/goal/GoalService/creation.ts
index 77147d5efac..b5caf3da912 100644
--- a/apps/server/src/services/goal/GoalService/creation.ts
+++ b/apps/server/src/services/goal/GoalService/creation.ts
@@ -28,7 +28,12 @@ import type { CreateGoalGraphInput, GoalServiceContext } from './types';
export const createFromConversation = async (
ctx: GoalServiceContext,
operationId: string,
- input: Omit<CreateGoalGraphInput, 'agentId' | 'createdByAgentId' | 'topicId'>,
+ {
+ taskModelConfig,
+ ...input
+ }: Omit<CreateGoalGraphInput, 'agentId' | 'createdByAgentId' | 'topicId'> & {
+ taskModelConfig?: { model: string; provider: string };
+ },
/**
* A local desktop run keeps its operation client-side, so no server row
* exists for `operationId`. Its conversation env names the topic and agent
@@ -55,6 +60,9 @@ export const createFromConversation = async (
topicId,
});
try {
+ // Before the turn is adopted: its snapshot covers the goal config, so a
+ // later write would make the run's first plan stale.
+ if (taskModelConfig) await ctx.setTaskModel(created.goal.id, taskModelConfig);
const state = await new GoalManagerService(
ctx.db,
ctx.userId,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.model.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.model.test.ts
new file mode 100644
index 00000000000..b3849f5515c
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.model.test.ts
@@ -0,0 +1,133 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createTaskRuntime } from '../task';
+
+vi.mock('@/business/server/task/notifyTaskAssigned', () => ({ notifyTaskAssigned: vi.fn() }));
+
+// Server-only env, read for absolute task links.
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.lobehub.com' } }));
+
+// The real router imports the runtime registry back; the runtime only needs a caller.
+vi.mock('@/server/routers/lambda/task', () => ({ taskRouter: { createCaller: vi.fn() } }));
+
+// TaskService pulls ModelRuntime at module load; each test passes its own stub.
+vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
+
+const createdTask = {
+ assigneeUserId: null,
+ id: 'task-1',
+ identifier: 'T-1',
+ name: 'Run',
+ priority: 0,
+ status: 'backlog',
+};
+
+const setup = () => {
+ const taskService = { createTask: vi.fn().mockResolvedValue(createdTask) };
+ const taskCaller = { update: vi.fn().mockResolvedValue({ data: { id: 'task-1' } }) };
+ const taskModel = { resolve: vi.fn().mockResolvedValue(createdTask) };
+ const runtime = createTaskRuntime({
+ agentId: 'agt-1',
+ agentModel: { existsById: vi.fn().mockResolvedValue(true) } as any,
+ db: {} as any,
+ taskCaller: taskCaller as any,
+ taskModel: taskModel as any,
+ taskService: taskService as any,
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ });
+ return { runtime, taskCaller, taskService };
+};
+
+describe('task runtime β€” task model', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('creates a task with the requested model in config', async () => {
+ const { runtime, taskService } = setup();
+
+ await runtime.createTask({
+ instruction: 'Run',
+ model: 'deepseek-chat',
+ name: 'Run',
+ provider: 'lobehub',
+ });
+
+ expect(taskService.createTask).toHaveBeenCalledWith(
+ expect.objectContaining({ config: { model: 'deepseek-chat', provider: 'lobehub' } }),
+ );
+ });
+
+ it('leaves config to the assignee snapshot when no model is given', async () => {
+ const { runtime, taskService } = setup();
+
+ await runtime.createTask({ instruction: 'Run', name: 'Run' });
+
+ expect(taskService.createTask.mock.calls[0][0].config).toBeUndefined();
+ });
+
+ it('carries a per-item model through createTasks', async () => {
+ const { runtime, taskService } = setup();
+
+ await runtime.createTasks({
+ tasks: [
+ { instruction: 'A', model: 'gpt-5', name: 'A' },
+ { instruction: 'B', name: 'B' },
+ ],
+ });
+
+ expect(taskService.createTask.mock.calls[0][0].config).toEqual({ model: 'gpt-5' });
+ expect(taskService.createTask.mock.calls[1][0].config).toBeUndefined();
+ });
+
+ it('refuses a provider without a model before creating anything', async () => {
+ const { runtime, taskService } = setup();
+
+ const result = await runtime.createTask({
+ instruction: 'Run',
+ name: 'Run',
+ provider: 'openai',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('provider needs model');
+ expect(taskService.createTask).not.toHaveBeenCalled();
+ });
+
+ it('merges a model edit as a config patch', async () => {
+ const { runtime, taskCaller } = setup();
+
+ const result = await runtime.editTask({
+ identifier: 'T-1',
+ model: 'deepseek-chat',
+ provider: 'lobehub',
+ });
+
+ expect(result.success).toBe(true);
+ expect(taskCaller.update).toHaveBeenCalledWith({
+ configPatch: { model: 'deepseek-chat', provider: 'lobehub' },
+ id: 'task-1',
+ });
+ expect(result.content).toContain('model β†’ lobehub/deepseek-chat');
+ });
+
+ it('clears both keys so the task follows its assignee again', async () => {
+ const { runtime, taskCaller } = setup();
+
+ await runtime.editTask({ identifier: 'T-1', model: null });
+
+ expect(taskCaller.update).toHaveBeenCalledWith({
+ configPatch: { model: null, provider: null },
+ id: 'task-1',
+ });
+ });
+
+ it('sends no config patch for edits without a model', async () => {
+ const { runtime, taskCaller } = setup();
+
+ await runtime.editTask({ identifier: 'T-1', name: 'Renamed' });
+
+ expect(taskCaller.update).toHaveBeenCalledWith({ id: 'task-1', name: 'Renamed' });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index 5473b70150e..ded45116638 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -1,11 +1,14 @@
import type { ListWorkspaceMembersParams } from '@lobechat/builtin-tool-task';
import {
+ describeTaskModelChange,
MISSING_TASK_NAME_ERROR,
normalizeListTasksParams,
normalizeListWorkspaceMembersParams,
normalizeSetTaskVerifyParams,
selectAssignableMembers,
TaskIdentifier,
+ toCreateTaskModelConfig,
+ toTaskModelConfigPatch,
} from '@lobechat/builtin-tool-task';
import type { LobeChatDatabase } from '@lobechat/database';
import type { TaskAssignableMember, TaskCreatedItem } from '@lobechat/prompts';
@@ -116,9 +119,11 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
requirement?: string | null;
title?: string;
};
+ model?: string;
name: string;
parentIdentifier?: string;
priority?: number;
+ provider?: string;
sortOrder?: number;
};
@@ -136,6 +141,12 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
// `name` is required by the manifest but nothing enforced it: nameless
// tasks listed as "(unnamed)" and the receipt printed `"null"`.
if (!args.name?.trim()) return { content: MISSING_TASK_NAME_ERROR, success: false };
+ let modelConfig: ReturnType<typeof toCreateTaskModelConfig>;
+ try {
+ modelConfig = toCreateTaskModelConfig(args);
+ } catch (error) {
+ return { content: (error as Error).message, success: false };
+ }
let parentLabel: string | undefined;
// Pre-resolve parent identifier so we can surface a tool-friendly error
@@ -179,6 +190,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
task = await taskService().createTask({
assigneeAgentId: args.assigneeAgentId ?? (scope === 'task' ? undefined : agentId),
assigneeUserId: args.assigneeUserId,
+ config: modelConfig,
context: origin ? { origin } : undefined,
createdByAgentId: agentId,
instruction: args.instruction,
@@ -353,9 +365,11 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
description?: string;
identifier: string;
instruction?: string;
+ model?: string | null;
name?: string;
parentIdentifier?: string | null;
priority?: number;
+ provider?: string | null;
removeDependencies?: string[];
}) => {
const task = await taskModel().resolve(args.identifier);
@@ -416,10 +430,20 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
changes.push(`priority β†’ ${priorityLabel(args.priority)}`);
}
- if (Object.keys(updateData).length > 0) {
+ // Deep-merged into `config` so checkpoint / review / execution keys survive.
+ const configPatch = toTaskModelConfigPatch(args);
+ if (configPatch) changes.push(describeTaskModelChange(configPatch));
+
+ if (Object.keys(updateData).length > 0 || configPatch) {
// Attribution rides the caller's context, not this payload β€” see
// `AuthContext.actingAgentId`.
- ops.push(taskCaller().update({ id: task.id, ...updateData }));
+ ops.push(
+ taskCaller().update({
+ id: task.id,
+ ...updateData,
+ ...(configPatch && { configPatch }),
+ }),
+ );
}
const applyDeps = async (
diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.ts
index 5b7c16069af..2622ec41d79 100644
--- a/packages/builtin-tool-task/src/client/executor/index.ts
+++ b/packages/builtin-tool-task/src/client/executor/index.ts
@@ -38,6 +38,11 @@ import { normalizeListTasksParams } from '../../listTasks';
import { selectAssignableMembers } from '../../listWorkspaceMembers';
import { TaskIdentifier } from '../../manifest';
import { normalizeSetTaskVerifyParams } from '../../setTaskVerify';
+import {
+ describeTaskModelChange,
+ toCreateTaskModelConfig,
+ toTaskModelConfigPatch,
+} from '../../taskModel';
import { resolveTaskOpenTarget } from '../../taskRef';
import type {
AddTaskCommentParams,
@@ -202,10 +207,11 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
instruction: string;
assigneeAgentId?: string;
assigneeUserId?: string;
- // Bind a goal entity to the created task (see TaskService.createTask).
+ model?: string;
name: string;
parentIdentifier?: string;
priority?: number;
+ provider?: string;
sortOrder?: number;
},
ctx?: BuiltinToolContext,
@@ -232,6 +238,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const task = await getTaskStoreState().createTask({
assigneeAgentId: assigneeAgentId ?? (ctx?.scope === 'task' ? undefined : ctx?.agentId),
assigneeUserId,
+ config: toCreateTaskModelConfig(params),
createdByAgentId: ctx?.agentId,
instruction: params.instruction,
name: params.name,
@@ -294,9 +301,11 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
instruction: string;
assigneeAgentId?: string;
assigneeUserId?: string;
+ model?: string;
name: string;
parentIdentifier?: string;
priority?: number;
+ provider?: string;
sortOrder?: number;
},
ctx?: BuiltinToolContext,
@@ -413,9 +422,11 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
description?: string;
identifier: string;
instruction?: string;
+ model?: string | null;
name?: string;
parentIdentifier?: string | null;
priority?: number;
+ provider?: string | null;
removeDependencies?: string[];
},
ctx?: BuiltinToolContext,
@@ -496,6 +507,13 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
);
}
+ // Merged into `config` so checkpoint / review / execution keys survive.
+ const modelPatch = toTaskModelConfigPatch(params);
+ if (modelPatch) {
+ ops.push(store.updateTaskModelConfig(identifier, modelPatch, { rethrow: true }));
+ changes.push(describeTaskModelChange(modelPatch));
+ }
+
const applyDependencies = async (refs: string[], remove: boolean) => {
const tasks = await Promise.all(
refs.map(async (ref) => (await taskService.find(ref)).data),
diff --git a/packages/builtin-tool-task/src/client/executor/model.test.ts b/packages/builtin-tool-task/src/client/executor/model.test.ts
new file mode 100644
index 00000000000..d379cfe1313
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/executor/model.test.ts
@@ -0,0 +1,131 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ createTask: vi.fn(),
+ updateTask: vi.fn(),
+ updateTaskModelConfig: vi.fn(),
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ getActiveWorkspaceSlug: vi.fn(() => undefined),
+}));
+vi.mock('@/business/client/hooks/useWorkspaceMembers', () => ({
+ getWorkspaceMembers: vi.fn(() => []),
+}));
+vi.mock('@/store/user', () => ({ useUserStore: { getState: () => ({}) } }));
+vi.mock('@/store/user/selectors', () => ({
+ userProfileSelectors: { displayUserName: () => '', userId: () => undefined },
+}));
+vi.mock('@/store/chat', () => ({ getChatStoreState: vi.fn() }));
+vi.mock('@/store/task', () => ({
+ getTaskStoreState: () => ({
+ createTask: mocks.createTask,
+ updateTask: mocks.updateTask,
+ updateTaskModelConfig: mocks.updateTaskModelConfig,
+ }),
+}));
+vi.mock('@/store/task/slices/detail/reducer', () => ({
+ findSubtaskParentId: vi.fn(() => undefined),
+}));
+vi.mock('@/services/task', () => ({
+ taskService: { find: vi.fn(async () => ({ data: { id: 'task-1', identifier: 'T-1' } })) },
+}));
+
+const { taskExecutor } = await import('./index');
+
+describe('TaskExecutor β€” task model', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createTask.mockResolvedValue({
+ id: 'task-1',
+ identifier: 'T-1',
+ name: 'Run',
+ priority: 0,
+ status: 'backlog',
+ });
+ mocks.updateTask.mockResolvedValue(undefined);
+ mocks.updateTaskModelConfig.mockResolvedValue(undefined);
+ });
+
+ describe('createTask', () => {
+ it('writes an explicit model and provider into config', async () => {
+ await taskExecutor.createTask(
+ { instruction: 'Run', model: 'deepseek-chat', name: 'Run', provider: 'lobehub' },
+ { agentId: 'agt-1' } as any,
+ );
+
+ expect(mocks.createTask).toHaveBeenCalledWith(
+ expect.objectContaining({ config: { model: 'deepseek-chat', provider: 'lobehub' } }),
+ );
+ });
+
+ it('sends no config without a model, keeping the assignee snapshot path', async () => {
+ await taskExecutor.createTask({ instruction: 'Run', name: 'Run' }, {
+ agentId: 'agt-1',
+ } as any);
+
+ expect(mocks.createTask.mock.calls[0][0].config).toBeUndefined();
+ });
+
+ it('applies the model to each createTasks item independently', async () => {
+ await taskExecutor.createTasks(
+ {
+ tasks: [
+ { instruction: 'A', model: 'gpt-5', name: 'A' },
+ { instruction: 'B', name: 'B' },
+ ],
+ },
+ { agentId: 'agt-1' } as any,
+ );
+
+ expect(mocks.createTask.mock.calls[0][0].config).toEqual({ model: 'gpt-5' });
+ expect(mocks.createTask.mock.calls[1][0].config).toBeUndefined();
+ });
+ });
+
+ describe('editTask', () => {
+ it('merges the model into config without touching other fields', async () => {
+ const result = await taskExecutor.editTask({
+ identifier: 'T-1',
+ model: 'deepseek-chat',
+ provider: 'lobehub',
+ });
+
+ expect(result.success).toBe(true);
+ expect(mocks.updateTaskModelConfig).toHaveBeenCalledWith(
+ 'task-1',
+ { model: 'deepseek-chat', provider: 'lobehub' },
+ { rethrow: true },
+ );
+ expect(mocks.updateTask).not.toHaveBeenCalled();
+ expect(result.content).toContain('model β†’ lobehub/deepseek-chat');
+ });
+
+ it('clears model and provider for model: null', async () => {
+ const result = await taskExecutor.editTask({ identifier: 'T-1', model: null });
+
+ expect(mocks.updateTaskModelConfig).toHaveBeenCalledWith(
+ 'task-1',
+ { model: null, provider: null },
+ { rethrow: true },
+ );
+ expect(result.content).toContain('follows the assignee agent');
+ });
+
+ it('leaves the model alone when no model field is passed', async () => {
+ await taskExecutor.editTask({ identifier: 'T-1', name: 'Renamed' });
+ await taskExecutor.editTask({ identifier: 'T-1', model: '', name: 'Renamed', provider: '' });
+
+ expect(mocks.updateTaskModelConfig).not.toHaveBeenCalled();
+ });
+
+ it('reports a model write that did not land as a failure', async () => {
+ mocks.updateTaskModelConfig.mockRejectedValueOnce(new Error('network down'));
+
+ const result = await taskExecutor.editTask({ identifier: 'T-1', model: 'gpt-5' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('network down');
+ });
+ });
+});
diff --git a/packages/builtin-tool-task/src/index.ts b/packages/builtin-tool-task/src/index.ts
index 39a63a1b365..63f56857385 100644
--- a/packages/builtin-tool-task/src/index.ts
+++ b/packages/builtin-tool-task/src/index.ts
@@ -21,6 +21,11 @@ export {
export { TaskIdentifier, TaskManifest } from './manifest';
export { normalizeSetTaskVerifyParams } from './setTaskVerify';
export { systemPrompt } from './systemRole';
+export {
+ describeTaskModelChange,
+ toCreateTaskModelConfig,
+ toTaskModelConfigPatch,
+} from './taskModel';
export { resolveTaskOpenTarget, taskResultState } from './taskRef';
export type {
CreateGoalParams,
diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.ts
index 30dd52e5a9e..d5b3f5c4a5b 100644
--- a/packages/builtin-tool-task/src/manifest.ts
+++ b/packages/builtin-tool-task/src/manifest.ts
@@ -30,6 +30,11 @@ export const TaskManifest: BuiltinToolManifest = {
"Optional workspace member (user ID) to set as the task's human owner. Coexists with assigneeAgentId β€” the agent executes the task, the member owns the outcome. Resolve the ID with listWorkspaceMembers first; never guess it.",
type: 'string',
},
+ model: {
+ description:
+ 'Optional model ID this task runs with (e.g. "deepseek-chat"), instead of the assignee agent\'s default. Only set it when the user asks for a specific model. Omit to pin the assignee agent\'s current model.',
+ type: 'string',
+ },
name: {
description: 'A short, descriptive name for the task.',
type: 'string',
@@ -43,6 +48,11 @@ export const TaskManifest: BuiltinToolManifest = {
description: 'Priority level: 0=none, 1=urgent, 2=high, 3=normal, 4=low. Default is 0.',
type: 'number',
},
+ provider: {
+ description:
+ 'Provider ID for `model` (e.g. "lobehub", "openai"). Pass it together with model when known; omit to let the server resolve it from the assignee agent.',
+ type: 'string',
+ },
sortOrder: {
description:
'Sort order within parent task. Lower values appear first. Use to control display order (e.g. chapter 1=0, chapter 2=1, etc.).',
@@ -82,6 +92,11 @@ export const TaskManifest: BuiltinToolManifest = {
"Optional workspace member (user ID) to set as the task's human owner (coexists with assigneeAgentId). Resolve the ID with listWorkspaceMembers first.",
type: 'string',
},
+ model: {
+ description:
+ 'Optional model ID this task runs with (e.g. "deepseek-chat"), instead of the assignee agent\'s default. Only set it when the user asks for a specific model. Omit to pin the assignee agent\'s current model.',
+ type: 'string',
+ },
name: {
description: 'A short, descriptive name for the task.',
type: 'string',
@@ -96,6 +111,11 @@ export const TaskManifest: BuiltinToolManifest = {
'Priority level: 0=none, 1=urgent, 2=high, 3=normal, 4=low. Default is 0.',
type: 'number',
},
+ provider: {
+ description:
+ 'Provider ID for `model` (e.g. "lobehub", "openai"). Pass it together with model when known; omit to let the server resolve it from the assignee agent.',
+ type: 'string',
+ },
sortOrder: {
description:
'Sort order within parent task. Lower values appear first. Use to control display order.',
@@ -247,7 +267,7 @@ export const TaskManifest: BuiltinToolManifest = {
},
{
description:
- "Edit a task's fields (name, description, instruction, priority), assignee (agent or workspace member), parent, or dependencies (batched). Status changes go through updateTaskStatus; schedule configuration goes through setTaskSchedule.",
+ "Edit a task's fields (name, description, instruction, priority, model/provider), assignee (agent or workspace member), parent, or dependencies (batched). Status changes go through updateTaskStatus; schedule configuration goes through setTaskSchedule.",
name: TaskApiName.editTask,
parameters: {
properties: {
@@ -281,6 +301,11 @@ export const TaskManifest: BuiltinToolManifest = {
description: 'Updated instruction for the task.',
type: 'string',
},
+ model: {
+ description:
+ "Model ID this task should run with from now on. Pass null to clear the override so the next run uses the assignee agent's model. Pass provider alongside when known; a model without provider has its provider resolved from the assignee agent.",
+ type: ['string', 'null'],
+ },
name: {
description: 'Updated name for the task.',
type: 'string',
@@ -294,6 +319,11 @@ export const TaskManifest: BuiltinToolManifest = {
description: 'Updated priority level: 0=none, 1=urgent, 2=high, 3=normal, 4=low.',
type: 'number',
},
+ provider: {
+ description:
+ 'Provider ID for the task model (e.g. "lobehub", "openai"). Pass null to clear it.',
+ type: ['string', 'null'],
+ },
removeDependencies: {
description:
'Identifiers of existing dependencies to remove. Accepts identifiers or ids returned by previous results; prefer stable ids.',
diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.ts
index 168e5f7d872..8f7933e6007 100644
--- a/packages/builtin-tool-task/src/systemRole.ts
+++ b/packages/builtin-tool-task/src/systemRole.ts
@@ -1,12 +1,12 @@
export const systemPrompt = `You have access to Task management tools. Use them to:
-- **createTask**: Create a new task. Use parentIdentifier to make it a subtask
+- **createTask**: Create a new task. Use parentIdentifier to make it a subtask. Set model (and provider) only when the user asks for a specific model; omitted, the task runs on its assignee agent's model
- **createTasks**: Create multiple tasks in one call. Prefer this when you are about to create more than one task in a row (e.g. all subtasks under one parent, or all chapters of an outline) β€” it cuts the number of tool calls and keeps the batch atomic from the user's perspective
- **listTasks**: List tasks. With no filters, defaults to top-level unfinished tasks of the current agent in normal agent conversations, or top-level unfinished tasks across all agents in task manager conversations. If you provide any filter, omitted filters are not applied implicitly
- **viewTask**: View details of a specific task. Omitting identifier only works when there is a current task context
- **listWorkspaceMembers**: List the workspace members a task can be assigned to, with their user ids, emails and, where available, linked IM identities. Call it before assigning a task to a person so the name or IM handle the user gave is resolved to a real id β€” an exact im/email match (e.g. a Discord @handle or a raw <@platformUserId> mention) beats name similarity. Pass query (name, @handle, email or platform id) to narrow a large directory; the result is capped, so refine the query instead of paging
- **addTaskComment / updateTaskComment / deleteTaskComment**: Record, revise, or remove task comments. Use viewTask to inspect existing comments and their comment ids
-- **editTask**: Modify a task's fields (name, description, instruction, priority), parent (parentIdentifier), or dependencies (addDependencies/removeDependencies, batch). Use parentIdentifier=null to move a task to the top level. For status changes use updateTaskStatus; for schedule configuration use setTaskSchedule
+- **editTask**: Modify a task's fields (name, description, instruction, priority, model/provider β€” model=null returns it to the assignee agent's model), parent (parentIdentifier), or dependencies (addDependencies/removeDependencies, batch). Use parentIdentifier=null to move a task to the top level. For status changes use updateTaskStatus; for schedule configuration use setTaskSchedule
- **setTaskSchedule**: Configure (or clear) the recurring schedule of a task. Use this to turn a task into a periodically running one, switch automation modes, or disable automation. See "Schedule fields" below for the supported params
- **setTaskVerify**: Configure (or clear) a task's delivery-acceptance (verify) gate. Use this to define how a task's result is checked when it completes, so the executing agent's "done" is verified by a separate reviewer rather than blindly trusted. See "Verify fields" below
- **runTask**: Actually START a task β€” kicks off the assigned agent in a new (or continued) topic. Use this to launch execution; do NOT use updateTaskStatus(running) to start a task, that only flips a flag without executing. The task must have an assigneeAgentId
diff --git a/packages/builtin-tool-task/src/taskModel.test.ts b/packages/builtin-tool-task/src/taskModel.test.ts
new file mode 100644
index 00000000000..e5c0b81fdc0
--- /dev/null
+++ b/packages/builtin-tool-task/src/taskModel.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ describeTaskModelChange,
+ toCreateTaskModelConfig,
+ toTaskModelConfigPatch,
+} from './taskModel';
+
+describe('toCreateTaskModelConfig', () => {
+ it('keeps explicit values only', () => {
+ expect(toCreateTaskModelConfig({ model: ' gpt-5 ', provider: 'openai' })).toEqual({
+ model: 'gpt-5',
+ provider: 'openai',
+ });
+ expect(toCreateTaskModelConfig({ model: 'gpt-5' })).toEqual({ model: 'gpt-5' });
+ });
+
+ it('omits config for blank, "null" or missing values', () => {
+ expect(toCreateTaskModelConfig({})).toBeUndefined();
+ expect(toCreateTaskModelConfig({ model: '', provider: 'null' })).toBeUndefined();
+ expect(toCreateTaskModelConfig({ model: null, provider: null })).toBeUndefined();
+ });
+
+ it('refuses a provider without a model instead of pairing it with the agent model', () => {
+ expect(() => toCreateTaskModelConfig({ provider: 'openai' })).toThrow('provider needs model');
+ });
+});
+
+describe('toTaskModelConfigPatch', () => {
+ it('returns nothing when neither field is passed', () => {
+ expect(toTaskModelConfigPatch({})).toBeUndefined();
+ });
+
+ it('clears both keys when the model is cleared', () => {
+ expect(toTaskModelConfigPatch({ model: null })).toEqual({ model: null, provider: null });
+ expect(toTaskModelConfigPatch({ model: 'null', provider: 'openai' })).toEqual({
+ model: null,
+ provider: null,
+ });
+ });
+
+ it('drops the stored provider for a model-only change', () => {
+ expect(toTaskModelConfigPatch({ model: 'gpt-5' })).toEqual({ model: 'gpt-5', provider: null });
+ });
+
+ it('sets the pair, or the provider alone', () => {
+ expect(toTaskModelConfigPatch({ model: 'gpt-5', provider: 'openai' })).toEqual({
+ model: 'gpt-5',
+ provider: 'openai',
+ });
+ expect(toTaskModelConfigPatch({ provider: 'openai' })).toEqual({ provider: 'openai' });
+ expect(toTaskModelConfigPatch({ provider: null })).toEqual({ provider: null });
+ });
+
+ // Models fill optional fields with "": a rename must not wipe the task model.
+ it('treats blank strings as not passed', () => {
+ expect(toTaskModelConfigPatch({ model: '', provider: '' })).toBeUndefined();
+ expect(toTaskModelConfigPatch({ model: ' ' })).toBeUndefined();
+ });
+});
+
+describe('describeTaskModelChange', () => {
+ it('summarizes each patch shape', () => {
+ expect(describeTaskModelChange({ model: null, provider: null })).toContain('cleared');
+ expect(describeTaskModelChange({ model: 'gpt-5', provider: 'openai' })).toBe(
+ 'model β†’ openai/gpt-5',
+ );
+ expect(describeTaskModelChange({ model: 'gpt-5', provider: null })).toBe('model β†’ gpt-5');
+ expect(describeTaskModelChange({ provider: 'openai' })).toBe('provider β†’ openai');
+ });
+});
diff --git a/packages/builtin-tool-task/src/taskModel.ts b/packages/builtin-tool-task/src/taskModel.ts
new file mode 100644
index 00000000000..4b94d1351d0
--- /dev/null
+++ b/packages/builtin-tool-task/src/taskModel.ts
@@ -0,0 +1,68 @@
+/**
+ * Task-level model override as the task tools accept it. `null` clears the
+ * override; omitted keeps whatever the task already carries.
+ */
+export interface TaskModelParams {
+ model?: string | null;
+ provider?: string | null;
+}
+
+// A type alias, not an interface, so it stays assignable to `config` records.
+export type TaskModelConfig = {
+ model?: string | null;
+ provider?: string | null;
+};
+
+// Models fill optional strings with "" β€” that means "not passed", never a clear,
+// or an edit that only renames the task would wipe its model. Only `null` (or
+// the string "null", which some models send instead) clears.
+const readValue = (value: string | null | undefined): string | null | undefined => {
+ if (value === null) return null;
+ const trimmed = value?.trim();
+ if (!trimmed) return undefined;
+ return trimmed.toLowerCase() === 'null' ? null : trimmed;
+};
+
+const TASK_PROVIDER_WITHOUT_MODEL_ERROR =
+ 'provider needs model: pass the model it serves, or omit both to use the assignee agent model.';
+
+/**
+ * `config` fields for a new task. Only explicit values are written; anything
+ * missing is filled from the assignee agent's snapshot by the server
+ * (`resolveMissingTaskModelConfig`), the same as a task created without one.
+ */
+export const toCreateTaskModelConfig = (params: TaskModelParams): TaskModelConfig | undefined => {
+ const model = readValue(params.model);
+ const provider = readValue(params.provider);
+ // The server would pair it with the agent's model, which that provider may not serve.
+ if (provider && !model) throw new Error(TASK_PROVIDER_WITHOUT_MODEL_ERROR);
+ const config: TaskModelConfig = {};
+ if (model) config.model = model;
+ if (provider) config.provider = provider;
+ return Object.keys(config).length > 0 ? config : undefined;
+};
+
+/**
+ * Deep-merge patch for an existing task's `config`.
+ *
+ * - `model: null` clears model and provider: the next run snapshots the
+ * assignee agent's model again.
+ * - A model without a provider clears the stored provider, so the run resolves
+ * it the way a model-only task always has instead of pairing the new model
+ * with the previous provider.
+ */
+export const toTaskModelConfigPatch = (params: TaskModelParams): TaskModelConfig | undefined => {
+ const model = readValue(params.model);
+ const provider = readValue(params.provider);
+ if (model === undefined && provider === undefined) return undefined;
+ if (model === null) return { model: null, provider: null };
+ if (model === undefined) return { provider };
+ return { model, provider: provider ?? null };
+};
+
+/** One-line change summary for an applied {@link toTaskModelConfigPatch} result. */
+export const describeTaskModelChange = (patch: TaskModelConfig): string => {
+ if (patch.model === null) return 'model cleared (follows the assignee agent)';
+ if (patch.model) return `model β†’ ${patch.provider ? `${patch.provider}/` : ''}${patch.model}`;
+ return patch.provider ? `provider β†’ ${patch.provider}` : 'provider cleared';
+};
diff --git a/packages/builtin-tool-task/src/types.ts b/packages/builtin-tool-task/src/types.ts
index 32a9c159f6c..6ec0900564b 100644
--- a/packages/builtin-tool-task/src/types.ts
+++ b/packages/builtin-tool-task/src/types.ts
@@ -59,9 +59,13 @@ export interface CreateTaskParams {
/** Workspace member (user id) who owns the task outcome; coexists with `assigneeAgentId` (the executing agent). */
assigneeUserId?: string;
instruction: string;
+ /** Model the task runs with; omitted pins the assignee agent's current model. */
+ model?: string;
name: string;
parentIdentifier?: string;
priority?: number;
+ /** Provider for `model`; omitted is resolved from the assignee agent. */
+ provider?: string;
sortOrder?: number;
}
@@ -226,9 +230,13 @@ export interface EditTaskParams {
description?: string;
identifier: string;
instruction?: string;
+ /** Task model override; `null` clears it so the task follows the assignee agent again. */
+ model?: string | null;
name?: string;
parentIdentifier?: string | null;
priority?: number;
+ /** Provider for the task model; `null` clears it. */
+ provider?: string | null;
removeDependencies?: string[];
}
diff --git a/src/store/task/slices/config/action.ts b/src/store/task/slices/config/action.ts
index 6610833c8f1..737055d07f9 100644
--- a/src/store/task/slices/config/action.ts
+++ b/src/store/task/slices/config/action.ts
@@ -256,10 +256,12 @@ export class TaskConfigSliceActionImpl {
});
};
- // Safely merges model/provider into config via task.updateConfig without overwriting checkpoint/review
+ // Safely merges model/provider into config via task.updateConfig without overwriting checkpoint/review.
+ // `null` clears a key, so the next run snapshots the assignee agent's model again.
updateTaskModelConfig = async (
id: string,
- modelConfig: { model?: string; provider?: string },
+ modelConfig: { model?: string | null; provider?: string | null },
+ options?: { rethrow?: boolean },
): Promise<void> => {
// Serialized with every other `config` writer, and with no refetch: switching
// the model while picking a run location is the same column, and a late
@@ -276,6 +278,8 @@ export class TaskConfigSliceActionImpl {
if (!target) return;
target.config = { ...target.config, ...modelConfig };
},
+ // Agent tools must report a write that did not land instead of claiming it.
+ rethrow: options?.rethrow,
});
};