Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): validate scheduled model restores on the execution device
ylliuuu6675d71e44feac
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelRemoteRoute.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelRemoteRoute.test.tsnew file mode 100644index 0000000000..7498ca744e--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelRemoteRoute.test.ts@@ -0,0 +1,152 @@+import { readFileSync } from 'node:fs';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';+import type { ProviderView } from '@cindy/model-providers';+import { applyScheduledModelSelection, createScheduledModelScope, resolveScheduledModelSelection, type ScheduledModelSelection } from '../scheduledModelSelection';++// #6745: execute the production adapter and persisted-scope restore together.+// A shared-provider baseline must use the execution computer's catalog.+const source = ts.createSourceFile('register.ts', readFileSync(new URL('../register.ts', import.meta.url), 'utf8'), ts.ScriptTarget.Latest, true);+const adapters = new Map<string, string>();+function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.initializer) {+ if (node.name.getText(source) === 'applyScheduledProfile') adapters.set('scheduled', node.initializer.getText(source));+ if (node.name.getText(source) === 'reconcileBotModelRoute' && ts.isCallExpression(node.initializer)) {+ const deps = node.initializer.arguments[0] as ts.ObjectLiteralExpression;+ const apply = deps.properties.find(p => ts.isPropertyAssignment(p) && p.name.getText(source) === 'apply') as ts.PropertyAssignment;+ adapters.set('bot', apply.initializer.getText(source));+ }+ }+ ts.forEachChild(node, visit);+}+visit(source);+function compile(key: string, bindings: Record<string, unknown>) {+ const js = ts.transpileModule(`return ${adapters.get(key)};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ return new Function(...Object.keys(bindings), js)(...Object.values(bindings));+}+const choice: ScheduledModelSelection = {+ agentKind: 'codex', model: 'test-model', providerId: 'openai-shared', effort: 'high', fastMode: false,+};+function catalog(id: string): ProviderView[] {+ return [{ id, connected: true, agents: ['codex'], source: 'user', models: { codex: [{+ id: 'test-model', efforts: ['low', 'high'], defaultEffort: 'low', supportsFastMode: false,+ }] } }] as ProviderView[];+}+function fixture(device: string | null = 'share:test') {+ let current = { ...choice, agentDeviceId: device };+ let baseline: string | null = JSON.stringify({ ...choice, scopeId: 'old-run' });+ const local = catalog('openai');+ const remote = vi.fn(async () => catalog('openai-shared'));+ const guard = vi.fn(async (_agent: string, _model: string, providerId: string | null) => {+ if (!local.some(p => p.id === providerId)) throw new Error('provider unavailable on this computer');+ return undefined;+ });+ const query = { from: () => query, where: () => query, limit: async () => [{ planMode: false }] };+ const switchHarness = vi.fn(async (_deps: unknown, route: { agentDeviceId?: string | null }) => {+ if (route.agentDeviceId !== undefined) current.agentDeviceId = route.agentDeviceId;+ return { engineReady: true };+ });+ const applyModel = vi.fn(async (_id: string, model: string, providerId: string | null, axes: object) => {+ current = { ...current, model, providerId, ...axes };+ return {};+ });+ const apply = compile('scheduled', {+ applyScheduledModelSelection, resolveScheduledModelSelection,+ agentSwitchDeps: { getSessionRow: async () => ({ ...current, status: 'active' }) },+ dbToMakerAgentKind: (kind: string) => kind,+ isSessionInTurn: () => false, maker: { getSession: () => undefined },+ assertModelRouteUsable: guard, shouldApplyExclusiveProviderRerouteLive: () => false,+ resolveScheduledModelSelectionLive: async (route: ScheduledModelSelection) => resolveScheduledModelSelection(route, local),+ readUsableAgentDeviceProviders: remote,+ performSessionAgentSwitch: switchHarness, getDbClient: () => ({ drizzle: { select: () => query } }),+ sessions: {}, eq: vi.fn(), persistSessionFields: vi.fn(),+ applySessionRuntimeSelection: applyModel, runtimeSelectionRequiresModelWindowConfirmation: () => false,+ });+ const deps = {+ read: async () => ({ profile: current, baseline }),+ write: async (_id: string, value: unknown) => { baseline = value ? JSON.stringify(value) : null; },+ isBusy: () => false, createId: () => 'new-run', apply,+ };+ return { deps, remote, guard, switchHarness, applyModel, scope: createScheduledModelScope(deps),+ state: () => ({ current, baseline }), save: (value: unknown) => { baseline = JSON.stringify(value); } };+}++describe('automation restore uses the execution computer', () => {+ it.each(['share:test', 'other-device'])('restores a legacy baseline on %s after restart', async device => {+ const h = fixture(device);+ await createScheduledModelScope(h.deps).restore('task');+ expect(h.remote).toHaveBeenCalledWith(device, 'codex', 'test-model', 'openai-shared');+ expect(h.guard).not.toHaveBeenCalled();+ expect(h.applyModel).toHaveBeenCalledOnce();+ expect(h.state().baseline).toBeNull();+ expect(h.state().current).toMatchObject(choice);+ });+ it('validates an automation choice on the same remote execution computer', async () => {+ const h = fixture();+ await h.deps.apply('task', choice);+ expect(h.remote).toHaveBeenCalledWith('share:test', 'codex', 'test-model', 'openai-shared');+ expect(h.guard).not.toHaveBeenCalled();+ expect(h.switchHarness).not.toHaveBeenCalled();+ expect(h.state().current.agentDeviceId).toBe('share:test');+ });+ it('keeps ordinary local-provider validation for a local task', async () => {+ const h = fixture(null);+ h.save({ ...choice, providerId: 'openai', scopeId: 'old-run' });+ await h.scope.restore('task');+ expect(h.guard).toHaveBeenCalledWith('codex', 'test-model', 'openai');+ expect(h.remote).not.toHaveBeenCalled();+ expect(h.state().current.providerId).toBe('openai');+ expect(h.state().baseline).toBeNull();+ });+ it('does not substitute a local provider when the remote catalog no longer contains the source', async () => {+ const h = fixture();+ h.remote.mockResolvedValueOnce(catalog('another-source'));+ await expect(h.scope.restore('task')).rejects.toThrow('unavailable');+ expect(h.applyModel).not.toHaveBeenCalled();+ expect(h.guard).not.toHaveBeenCalled();+ expect(h.state().baseline).not.toBeNull();+ });+ it('retains the scope and task when the sharing host rejects access', async () => {+ const h = fixture();+ h.remote.mockRejectedValueOnce(new Error('REMOTE_AGENT_SHARE_PAUSED'));+ await expect(h.scope.restore('task')).rejects.toThrow('REMOTE_AGENT_SHARE_PAUSED');+ expect(h.state().baseline).not.toBeNull();+ expect(h.applyModel).not.toHaveBeenCalled();+ expect(h.guard).not.toHaveBeenCalled();+ });+ it('rejects a missing local provider without guessing a remote source', async () => {+ const h = fixture(null);+ await expect(h.scope.restore('task')).rejects.toThrow('provider unavailable');+ expect(h.remote).not.toHaveBeenCalled();+ expect(h.state().baseline).not.toBeNull();+ });+});++describe('a new teammate preference supersedes the old automation baseline', () => {+ it.each([false, true])('clears the scope only after selection succeeds (fails=%s)', async fails => {+ const h = fixture();+ const originalBaseline = h.state().baseline;+ const stage = vi.fn(async () => {+ if (fails) throw new Error('unavailable');+ h.state().current.providerId = 'new-preference';+ });+ const clear = vi.fn(h.deps.write);+ const apply = compile('bot', {+ stageSessionRouteSelection: stage, updateScheduledPreference: clear, isSessionIdleForRouteApply: () => false,+ });+ const request = apply('task', { ...choice, agentDeviceId: 'share:new' }, choice);+ if (fails) {+ await expect(request).rejects.toThrow('unavailable');+ expect(clear).not.toHaveBeenCalled();+ expect(h.state().baseline).toBe(originalBaseline);+ } else {+ await request;+ expect(clear).toHaveBeenCalledExactlyOnceWith('task', null);+ expect(h.state().baseline).toBeNull();+ // The ordinary send's restore must leave the newly selected route intact.+ await h.scope.restore('task');+ expect(h.state().current.providerId).toBe('new-preference');+ expect(h.applyModel).not.toHaveBeenCalled();+ }+ });+});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 1187a7da43..fa8afdfb7f 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -195,7 +195,7 @@ import {readInputDeliveryClientIds,} from '@cindy/device-link';import { and, asc, desc, eq, gte, inArray, isNull, like, lt, or, sql } from 'drizzle-orm';-import { applyScheduledModelSelection, createScheduledModelScope, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';+import { applyScheduledModelSelection, createScheduledModelScope, resolveScheduledModelSelection, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';import { parseScheduledModelBaseline } from '../../shared/scheduledModelBaseline';import { recordTurnModelChange, type TurnModelIdentity } from './turnModelChange';import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';@@ -10873,10 +10873,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)getTarget: async () => {const row = await agentSwitchDeps.getSessionRow(sessionId);return row ? { agentKind: dbToMakerAgentKind(row.agentKind), status: row.status,- remoteHostId: row.remoteHostId, orcaRole: row.orcaRole } : null;+ remoteHostId: row.remoteHostId, agentDeviceId: row.agentDeviceId, orcaRole: row.orcaRole } : null;},isBusy: () => isSessionInTurn(sessionId) || !!maker.getSession(sessionId)?.isTurnRunning(),- resolveSelection: async (route) => {+ resolveSelection: async (route, target) => {+ if (target?.agentDeviceId && !target.remoteHostId) {+ const providers = await readUsableAgentDeviceProviders(+ target.agentDeviceId, route.agentKind, route.model, route.providerId,+ );+ return resolveScheduledModelSelection(route, providers);+ }const reroute = await assertModelRouteUsable(route.agentKind, route.model, route.providerId);return resolveScheduledModelSelectionLive({ ...route,providerId: reroute && shouldApplyExclusiveProviderRerouteLive(route.providerId)@@ -15933,6 +15939,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},apply: async (sessionId, route, current) => {await stageSessionRouteSelection(sessionId, { ...route, agentDeviceId: route.agentDeviceId ?? null }, current.agentKind);+ // The permanent teammate route has superseded the pre-automation preference.+ // Do not restore that stale source before the next ordinary send (#6745).+ await updateScheduledPreference(sessionId, null);// Consume the same model/Harness intent as the normal send path. Its// verified window protection and history handoff also apply here; a Bot// settings save need not wait for a second user message. Busy runtimesdiff --git a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.tsindex 4e7901f5f6..f18989297e 100644--- a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts@@ -68,6 +68,7 @@ interface ScheduledModelTarget {agentKind: AgentKind;status: string;remoteHostId?: string | null;+ agentDeviceId?: string | null;orcaRole?: string | null;}@@ -108,7 +109,7 @@ export async function applyScheduledModelSelection(deps: {getTarget: () => Promise<ScheduledModelTarget | null>;isBusy: () => boolean;- resolveSelection: (selection: ScheduledModelSelection) => Promise<ScheduledModelSelection>;+ resolveSelection: (selection: ScheduledModelSelection, target?: ScheduledModelTarget | null) => Promise<ScheduledModelSelection>;switchHarness: (selection: ScheduledModelSelection) => Promise<{ engineReady: boolean; retryPending?: boolean }>;applyModel: (selection: ScheduledModelSelection) => Promise<void>;},@@ -116,11 +117,13 @@ export async function applyScheduledModelSelection(const target = await deps.getTarget();// The runner owns missing/archived target recovery, including persistent-task rebinding.if (!target || target.status === 'archived' || target.status === 'deleted') {- return deps.resolveSelection(selection);+ return deps.resolveSelection(selection, target);}if (deps.isBusy()) throw new ScheduledModelSelectionBusyError('Scheduled model selection waits for the current turn');assertScheduledHarnessSupported(target, selection.agentKind);- const resolved = await deps.resolveSelection(selection);+ // Automation changes model preferences within the bound task's execution location.+ // Persisted baselines from older clients have no location of their own.+ const resolved = await deps.resolveSelection(selection, target);if (target.agentKind !== resolved.agentKind) {const result = await deps.switchHarness(resolved);if (!result.engineReady || result.retryPending) throw new Error('Scheduled Harness switch did not become ready');diff --git a/docs/product-rules/model-selector-unified.md b/docs/product-rules/model-selector-unified.mdindex 78f4ac32ff..a060b14854 100644--- a/docs/product-rules/model-selector-unified.md+++ b/docs/product-rules/model-selector-unified.md@@ -207,6 +207,8 @@绑定已有任务的自动化在保存时只更新自动化配置,下次触发时才通过现有任务切换流程应用完整选择;目标正忙时顺延,不能抢占当前轮次。新增的 `modelAgentKind` 标识显式 Harness 选择;旧记录不补默认值,继续跟随绑定任务的 Harness。选择“跟随”会清除整套显式覆盖,切换新建/绑定模式往返时保留用户已选配置。+自动化应用模型以及恢复之前的模型偏好时,都按绑定任务当前的 Agent 执行位置校验来源与模型;同账号远程电脑和分享来源使用对应电脑的目录,不能拿本机目录判定不可用,也不能静默换成本机来源。重启后遗留的恢复记录沿用同一规则,无需补字段。伙伴永久模型链成功登记新路由后,清除被新选择取代的旧自动化恢复记录,避免下一条普通消息恢复旧来源;登记失败仍保留原记录。+项目自动化的 `schedules.json` 同样保存可选的 `modelAgentKind`,导出、加载与配置同步均保留该标记;删除标记时清除数据库中的覆盖,已有绑定任务不丢失。旧版 `version: 1` 文件无需补字段。自动触发前按实际来源、Harness 和模型的当前目录拷贝补齐或收敛 effort,并清除已不受支持的 Fast;仍有效的用户选择保持不变。---