Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: allow model settings on archived tasks
Dash568b388220ba
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.tsindex 530e9ecf2d..b7f0cfcfa6 100644--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts@@ -1,5 +1,6 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import ts from 'typescript';import { describe, expect, it, vi } from 'vitest';const mainRoot = resolve(__dirname, '..');@@ -40,6 +41,82 @@ function handlerBody(source: string, channel: string, nextChannel: string): strireturn source.slice(start, end);}+// Run the production axis closures without importing the Electron bootstrap.+// Guard tier: verifies the lifecycle/persistence contract shared by Desktop and+// Device Link. The previous tests only checked that terminal guards existed;+// an archived row plus a remote effort/Fast write is the minimal regression.+const axisHandlers = new Map<string, string>();+const registerAst = ts.createSourceFile('register.ts', registerSource, ts.ScriptTarget.Latest, true);+function collectAxisHandlers(node: ts.Node): void {+ if (ts.isVariableDeclaration(node) && node.initializer &&+ ['applyEffort', 'applyFastMode'].includes(node.name.getText(registerAst))) {+ axisHandlers.set(node.name.getText(registerAst), ts.transpileModule(+ `return ${node.initializer.getText(registerAst)};`,+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+ ).outputText);+ }+ ts.forEachChild(node, collectAxisHandlers);+}+collectAxisHandlers(registerAst);++describe.each([+ ['applyEffort', 'persistEffort', 'effort', 'high'],+ ['applyFastMode', 'persistFastMode', 'fastMode', true],+] as const)('archived settings: %s', (handler, persistName, field, value) => {+ function setup(status: 'archived' | 'deleted') {+ const row = { status, effort: 'low', fastMode: false } as Record<string, unknown>;+ const pending = new Map();+ const persist = vi.fn(async () => { row[field] = value; });+ const response = {};+ const query = { from: () => query, where: () => query, limit: async () => [row] };+ const getSession = vi.fn(() => { throw new Error('archived runtime must remain untouched'); });+ const bindings = {+ sessionId: 'archived-task', effort: 'high', enabled: true,+ sessions: {}, eq: vi.fn(), getDbClient: () => ({ drizzle: { select: () => query } }),+ remoteResponse: response, [persistName]: persist, agentSwitchPending: pending,+ assertOwnerCurrent: vi.fn(), assertSharedTaskCurrent: { admit: vi.fn() },+ markRemoteSettingPersistedInsideHandler: vi.fn(), maker: { getSession },+ agentSwitchDeps: { selectSameAgentModel: async (id: string, intent: unknown) => { pending.set(id, intent); } },+ throwIpcError: (code: string, message: string) => { throw new Error(`[${code}] ${message}`); },+ };+ const run = new Function(...Object.keys(bindings), axisHandlers.get(handler)!)(...Object.values(bindings));+ return { run, row, persist, response, getSession, pending };+ }++ it('acknowledges the saved axis while the task stays archived and the runtime stays untouched', async () => {+ const h = setup('archived');+ await expect(h.run()).resolves.toBe(h.response);+ expect(h.row).toMatchObject({ status: 'archived', [field]: value });+ expect(h.persist).toHaveBeenCalledOnce();+ expect(h.getSession).not.toHaveBeenCalled();+ });++ it('updates an already selected model instead of writing its axis onto the old route', async () => {+ const h = setup('archived');+ h.pending.set('archived-task', { sameAgentSelection: true, model: 'next-model' });+ await h.run();+ expect(h.pending.get('archived-task')).toMatchObject({ model: 'next-model', [field]: value });+ expect(h.row).toMatchObject({ status: 'archived', effort: 'low', fastMode: false });+ expect(h.persist).not.toHaveBeenCalled();+ expect(h.getSession).not.toHaveBeenCalled();+ });++ it('rejects a deleted task before saving anything', async () => {+ const h = setup('deleted');+ await expect(h.run()).rejects.toThrow('PRECONDITION_FAILED');+ expect(h.persist).not.toHaveBeenCalled();+ expect(h.getSession).not.toHaveBeenCalled();+ });++ it('reports a persistence failure without applying the axis to a runtime', async () => {+ const h = setup('archived');+ h.persist.mockRejectedValueOnce(new Error('sqlite rejected'));+ await expect(h.run()).rejects.toThrow('sqlite rejected');+ expect(h.row).toMatchObject({ status: 'archived', effort: 'low', fastMode: false });+ expect(h.getSession).not.toHaveBeenCalled();+ });+});+describe('session runtime control wiring', () => {it('replays Windows attention after the main window is shown independently of inventory loading', () => {const body = handlerBody(@@ -771,7 +848,10 @@ describe('session runtime control wiring', () => {);});- it('rejects terminal tasks inside the shared route lock before runtime mutations', () => {+ // Guard tier: archive/delete and settings share the route lock. A picker may+ // stage an archived task, but automatic changes and send-time application must+ // still stop before recreating runtime state. The old guard rejected all three.+ it('allows only user picker staging on archived tasks inside the shared route lock', () => {const setModel = handlerBody(registerSource,'const handleSetModel = async (',@@ -784,6 +864,12 @@ describe('session runtime control wiring', () => {expect(setModel).toContain('internalOptions.sessionLockHeld ? applyLocked() : withSendToSessionLock(sessionId, applyLocked)',);+ const archiveAdmission = setModel.slice(setModel.indexOf('const canStageArchivedSelection'), terminalGuard);+ expect(archiveAdmission).toContain("runtimeStatus.status === 'archived'");+ expect(archiveAdmission).toContain("internalOptions.source === 'user'");+ expect(archiveAdmission).toContain('!internalOptions.applyingUserSelectionOnSend');+ expect(setModel).toContain("runtimeStatus.status !== 'active' && !canStageArchivedSelection");+ expect(setModel).toContain("(!runtimeStatus.remoteHostId || canStageArchivedSelection)");});it('stages user routes before every runtime mutation and prevents remote persistence of the source route', () => {@@ -827,7 +913,10 @@ describe('session runtime control wiring', () => {);});- it('rejects terminal tasks before effort or Fast mutations recreate runtime state', () => {+ // Regression: desktop persisted effort before the rejected runtime IPC, while+ // Mobile rejected the whole action. Archived axes must acknowledge persistence+ // without restoring the runtime stores cleared by archive cleanup.+ it('saves archived effort and Fast without recreating runtime state, and rejects deleted tasks', () => {const effort = handlerBody(registerSource,'ipcMain.handle(MAKER_INVOKE.SET_EFFORT',@@ -838,15 +927,25 @@ describe('session runtime control wiring', () => {'MAKER_INVOKE.SET_FAST_MODE','MAKER_INVOKE.SET_THINKING_ENABLED',);- for (const [body, commit] of [- [effort, 'commit: commitEffort'],- [fast, 'commit: commitFastMode'],+ for (const [body, commit, persist] of [+ [effort, 'commit: commitEffort', 'persistEffort'],+ [fast, 'commit: commitFastMode', 'persistFastMode'],] as const) {const terminalGuard = body.indexOf("runtimeStatus.status !== 'active'");expect(terminalGuard).toBeGreaterThan(-1);expect(terminalGuard).toBeLessThan(body.indexOf(commit));expect(body.indexOf('.select({ status: sessions.status })')).toBeLessThan(terminalGuard);expect(body).toContain('return withSendToSessionLock(sessionId');+ expect(body).toContain("runtimeStatus.status !== 'active' && runtimeStatus.status !== 'archived'");+ const archiveStart = body.indexOf("if (runtimeStatus.status === 'archived')");+ expect(archiveStart).toBeGreaterThan(body.indexOf('if (userIntent?.sameAgentSelection)'));+ const archiveEnd = body.indexOf('const livePatch:', archiveStart);+ const archive = body.slice(archiveStart, archiveEnd);+ expect(archive).toContain(`await ${persist}();`);+ expect(archive).toContain('return remoteResponse;');+ expect(archive).not.toContain('setSession');+ expect(archive).not.toContain('recordUserSessionRuntime');+ expect(archiveStart).toBeLessThan(body.indexOf('const sess = maker.getSession'));}});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.tsindex 2a63c84f91..525fb6f2df 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts@@ -69,6 +69,9 @@ describe('Orca model-only picker intent admission', () => {expect(pending.get('s1')).toMatchObject({ sameAgentSelection: true, targetAgentKind: 'codex',model: 'new', providerId: 'provider', effort: 'high', fastMode: true });expect(changed).toHaveBeenCalledTimes(1);+ // A deferred choice must not let Device Link overwrite the source route,+ // including when this task's Agent runs on another computer.+ expect(bindings.markRemoteSettingPersistedInsideHandler).toHaveBeenCalledOnce();expect(applyLive).not.toHaveBeenCalled();expect(runtimeStatus.model).toBe('old');if (!onOtherDevice) {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 99fc9469db..af33cbf749 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -20439,6 +20439,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentSwitchDeps.onPendingSwitchChanged?.(sessionId, projectPendingAgentSwitchIntent(intent));wakeSessionInputAfterCredentialSwitch(sessionId);const response = { deferred: true, superseded: false, pendingUntilSend: true };+ if (isDeviceLinkInvoke()) markRemoteSettingPersistedInsideHandler(response);return response;}if (supersededByOwnerBoundary()) return { deferred: false, superseded: true };@@ -20651,9 +20652,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (supersededByOwnerBoundary()) {return { deferred: false, superseded: true };}- // 归档/删除写入与本 handler 共用同一把 session route lock。拿锁后重读持久- // 状态可封住两种次序:本请求先拿锁时终态写等待并在之后清理 override;终态- // 先拿锁时旧请求看到非 active,不能在 cleanup 后重新建立 pending/override。+ // 归档/删除写入与本 handler 共用 session route lock。归档后仍允许用户+ // 暂存下一次发送的选择,但不得应用 runtime 或允许自动更新重建 override。+ // 删除任务始终拒绝;先选后归档时仍由归档 cleanup 清除旧意图。const [runtimeStatus] = await getDbClient().drizzle.select({status: sessions.status,@@ -20678,7 +20679,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (!runtimeStatus) {return { deferred: false, superseded: true };}- if (runtimeStatus.status !== 'active') {+ const canStageArchivedSelection = runtimeStatus.status === 'archived' &&+ internalOptions.source === 'user' && !internalOptions.applyingUserSelectionOnSend;+ if (runtimeStatus.status !== 'active' && !canStageArchivedSelection) {if (internalOptions.source === 'user') {throwIpcError('PRECONDITION_FAILED',@@ -20865,7 +20868,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// A picker click records intent only. Keep the persisted route and native binding// authoritative until a real send holds this same lock and consumes the final choice.if (internalOptions.source === 'user' && !internalOptions.applyingUserSelectionOnSend &&- !runtimeStatus.remoteHostId) {+ (!runtimeStatus.remoteHostId || canStageArchivedSelection)) {if (internalOptions.beforeMutation) await internalOptions.beforeMutation();assertRuntimeOwnerCurrent();assertSharedTaskCurrent.admit();@@ -22160,10 +22163,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);return remoteResponse;}- if (runtimeStatus.status !== 'active') {+ if (runtimeStatus.status !== 'active' && runtimeStatus.status !== 'archived') {throwIpcError('PRECONDITION_FAILED',- 'archived or deleted task cannot change runtime effort',+ 'deleted task cannot change runtime effort',);}const userIntent = agentSwitchPending.get(sessionId);@@ -22175,6 +22178,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);return remoteResponse ?? result;}+ if (runtimeStatus.status === 'archived') {+ // 本地由 renderer 落库,远控在此等待落库;不重建归档时清掉的 runtime 状态。+ await persistEffort();+ return remoteResponse;+ }const livePatch: SessionRuntimeAxisPatch = {effort: effort as SessionRuntimeProfile['effort'],};@@ -22685,10 +22693,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);return remoteResponse;}- if (runtimeStatus.status !== 'active') {+ if (runtimeStatus.status !== 'active' && runtimeStatus.status !== 'archived') {throwIpcError('PRECONDITION_FAILED',- 'archived or deleted task cannot change runtime Fast mode',+ 'deleted task cannot change runtime Fast mode',);}const userIntent = agentSwitchPending.get(sessionId);@@ -22700,6 +22708,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);return remoteResponse ?? result;}+ if (runtimeStatus.status === 'archived') {+ await persistFastMode();+ return remoteResponse;+ }const livePatch: SessionRuntimeAxisPatch = { fastMode: enabled };const pendingPatch = await resolvePendingRuntimeAxisPatch(sessionId, livePatch);const commitFastMode = () => {diff --git a/docs/dev-rules/model-catalog-runtime.md b/docs/dev-rules/model-catalog-runtime.mdindex 48b55b5ce1..70cb3e9702 100644--- a/docs/dev-rules/model-catalog-runtime.md+++ b/docs/dev-rules/model-catalog-runtime.md@@ -47,6 +47,15 @@ thread 配置,同时设置窗口和 90% 自动压缩预算,保留原生 5%相关规则:[`configuration-and-overrides.md`](configuration-and-overrides.md)、[`pi-harness.md`](pi-harness.md)、[`remote-and-mobile-adaptation.md`](remote-and-mobile-adaptation.md)。+### 归档任务的模型设置++归档任务允许用户调整模型、推理强度与 Fast,不要求先恢复,也不因设置变化恢复任务。+模型选择沿用活动任务的暂存意图,下一次发送先恢复任务再应用;暂存意图仍只在被控端+内存中保留,不新增跨进程恢复。已有模型意图时,推理强度与 Fast 更新该意图;否则+只保存任务字段,不重建归档时清掉的 runtime 状态。自动模型变更与已删除任务仍拒绝。+本机桌面、设备互联与手机共用此处理,见 `maker-ipc/register.ts` 和+`sessionRuntimeControlWiring.test.ts` 的归档生命周期回归。+### 默认型号与预览版的选择以下描述既有默认陈列策略;默认开启的产品合同与实现差异见