diff --git a/.changeset/tower-mode-mutex.md b/.changeset/tower-mode-mutex.md new file mode 100644 index 00000000000..3ddd2be4166 --- /dev/null +++ b/.changeset/tower-mode-mutex.md @@ -0,0 +1,7 @@ +--- +'@moonshot-ai/agent-core-v2': patch +'@moonshot-ai/kimi-code': patch +'kimi-code-app': patch +--- + +Fix Tower mode mutual exclusion with Plan, Swarm, and Goal modes, and remove the NotifyUser tool from Tower worker profiles. diff --git a/apps/kimi-code/src/tui/commands/config.ts b/apps/kimi-code/src/tui/commands/config.ts index 68f437d465f..dd2bb0eff9f 100644 --- a/apps/kimi-code/src/tui/commands/config.ts +++ b/apps/kimi-code/src/tui/commands/config.ts @@ -149,7 +149,7 @@ export async function handlePlanCommand(host: SlashCommandHost, args: string): P async function applyPlanMode(host: SlashCommandHost, session: Session, enabled: boolean): Promise { try { await session.setPlanMode(enabled); - host.setAppState({ planMode: enabled }); + host.setAppState(enabled ? { planMode: true, towerMode: false } : { planMode: false }); if (enabled) { const plan = await session.getPlan().catch(() => null); host.showNotice( diff --git a/apps/kimi-code/src/tui/commands/swarm.ts b/apps/kimi-code/src/tui/commands/swarm.ts index 7604e1ba479..a1cce1548bd 100644 --- a/apps/kimi-code/src/tui/commands/swarm.ts +++ b/apps/kimi-code/src/tui/commands/swarm.ts @@ -143,7 +143,7 @@ async function setSwarmMode( ); return false; } - host.setAppState({ swarmMode: enabled }); + host.setAppState(enabled ? { swarmMode: true, towerMode: false } : { swarmMode: false }); host.state.swarmModeEntry = enabled ? trigger : undefined; return true; } diff --git a/apps/kimi-code/src/tui/commands/tower.ts b/apps/kimi-code/src/tui/commands/tower.ts index 97a6283f68b..213ba442161 100644 --- a/apps/kimi-code/src/tui/commands/tower.ts +++ b/apps/kimi-code/src/tui/commands/tower.ts @@ -71,14 +71,23 @@ async function setTowerMode( ); return false; } + if (enabled) { + host.setAppState({ + towerMode: true, + planMode: status.planMode, + swarmMode: status.swarmMode ?? false, + }); + if (status.swarmMode !== true) host.state.swarmModeEntry = undefined; + } else { + host.setAppState({ towerMode: false }); + } + return true; } catch (error) { host.showError( `Failed to ${enabled ? 'enable' : 'disable'} tower mode: ${formatErrorMessage(error)}`, ); return false; } - host.setAppState({ towerMode: enabled }); - return true; } async function requireSessionEnsured(host: SlashCommandHost): Promise { diff --git a/apps/kimi-code/test/tui/commands/swarm.test.ts b/apps/kimi-code/test/tui/commands/swarm.test.ts index c0536010de1..f439d444c3a 100644 --- a/apps/kimi-code/test/tui/commands/swarm.test.ts +++ b/apps/kimi-code/test/tui/commands/swarm.test.ts @@ -25,6 +25,7 @@ function makeHost( hasSession?: boolean; permissionMode?: 'manual' | 'auto' | 'yolo'; swarmMode?: boolean; + towerMode?: boolean; } = {}, ) { const session = { @@ -38,6 +39,7 @@ function makeHost( model: overrides.model ?? 'kimi-model', permissionMode: overrides.permissionMode ?? 'auto', swarmMode: overrides.swarmMode ?? false, + towerMode: overrides.towerMode ?? false, }, theme: currentTheme, transcriptContainer: { addChild: vi.fn() }, @@ -104,13 +106,22 @@ describe('handleSwarmCommand', () => { expect(host.sendNormalUserInput).toHaveBeenCalledWith('Ship feature X'); }); + it('clears tower state when swarm mode turns on', async () => { + const { host } = makeHost({ permissionMode: 'auto', towerMode: true }); + + await handleSwarmCommand(host, 'on'); + + expect(host.state.appState.swarmMode).toBe(true); + expect(host.state.appState.towerMode).toBe(false); + }); + it('turns swarm mode on without sending a prompt', async () => { const { host, session } = makeHost({ model: '' }); await handleSwarmCommand(host, 'on'); expect(session.setSwarmMode).toHaveBeenCalledWith(true, 'manual'); - expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true }); + expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true, towerMode: false }); expect(host.state.swarmModeEntry).toBe('manual'); expectSwarmMarker(host, 'Swarm activated'); expect(host.showStatus).toHaveBeenCalledOnce(); @@ -140,7 +151,7 @@ describe('handleSwarmCommand', () => { expect(session.setPermission).toHaveBeenCalledWith('auto'); expect(session.setSwarmMode).toHaveBeenCalledTimes(1); expect(host.setAppState).toHaveBeenCalledWith({ permissionMode: 'auto' }); - expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true }); + expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true, towerMode: false }); expect(host.state.swarmModeEntry).toBe('manual'); expectSwarmMarker(host, 'Swarm activated'); expect(host.showStatus).toHaveBeenCalledWith(USAGE_NOTICE, 'warning'); @@ -153,7 +164,7 @@ describe('handleSwarmCommand', () => { await handleSwarmCommand(host, ''); expect(session.setSwarmMode).toHaveBeenCalledWith(true, 'manual'); - expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true }); + expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true, towerMode: false }); expect(host.state.swarmModeEntry).toBe('manual'); expectSwarmMarker(host, 'Swarm activated'); expect(host.showError).not.toHaveBeenCalled(); @@ -245,7 +256,7 @@ describe('handleSwarmCommand', () => { expect(session.setSwarmMode).toHaveBeenCalledWith(true, 'task'); expect(session.setSwarmMode).toHaveBeenCalledTimes(1); expect(host.setAppState).toHaveBeenCalledWith({ permissionMode: 'auto' }); - expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true }); + expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true, towerMode: false }); expect(host.showNotice).toHaveBeenCalledWith('Permission mode: Never Ask'); expect(host.showStatus).toHaveBeenCalledWith(PERMISSION_MODE_DESCRIPTIONS.auto, 'warning'); expect(host.state.swarmModeEntry).toBe('task'); @@ -290,7 +301,7 @@ describe('handleSwarmCommand', () => { expect(session.setSwarmMode).toHaveBeenCalledWith(true, 'task'); expect(session.setSwarmMode).toHaveBeenCalledTimes(1); expect(host.setAppState).toHaveBeenCalledWith({ permissionMode: 'yolo' }); - expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true }); + expect(host.setAppState).toHaveBeenCalledWith({ swarmMode: true, towerMode: false }); expect(host.showNotice).toHaveBeenCalledWith('Permission mode: Ask When Needed'); expect(host.showStatus).toHaveBeenCalledWith(PERMISSION_MODE_DESCRIPTIONS.yolo, 'warning'); expect(host.state.swarmModeEntry).toBe('task'); diff --git a/apps/kimi-code/test/tui/commands/tower.test.ts b/apps/kimi-code/test/tui/commands/tower.test.ts index c3b953f890f..bd335f840e7 100644 --- a/apps/kimi-code/test/tui/commands/tower.test.ts +++ b/apps/kimi-code/test/tui/commands/tower.test.ts @@ -10,6 +10,8 @@ function makeHost( overrides: { hasSession?: boolean; towerMode?: boolean; + planMode?: boolean; + swarmMode?: boolean; refuseTowerEntry?: boolean; model?: string; } = {}, @@ -19,7 +21,11 @@ function makeHost( setTowerMode: vi.fn(async (enabled: boolean) => { if (!(overrides.refuseTowerEntry && enabled)) engineMode = enabled; }), - getStatus: vi.fn(async () => ({ towerMode: engineMode })), + getStatus: vi.fn(async () => ({ + towerMode: engineMode, + planMode: engineMode ? false : (overrides.planMode ?? false), + swarmMode: engineMode ? false : (overrides.swarmMode ?? false), + })), getTowerStatus: vi.fn(async (): Promise => engineMode ? 'Tower mode: ON\nTower is not initialized.' : 'Tower mode: OFF', ), @@ -29,8 +35,11 @@ function makeHost( state: { appState: { towerMode: overrides.towerMode ?? false, + planMode: overrides.planMode ?? false, + swarmMode: overrides.swarmMode ?? false, model: overrides.model ?? 'test-model', }, + swarmModeEntry: overrides.swarmMode ? ('manual' as const) : undefined, }, session: hasSession ? session : undefined, ensureSession: vi.fn(async () => { @@ -152,12 +161,27 @@ describe('handleTowerCommand', () => { await handleTowerCommand(host, 'on'); expect(session.setTowerMode).toHaveBeenCalledWith(true, undefined); - expect(host.setAppState).toHaveBeenCalledWith({ towerMode: true }); + expect(host.setAppState).toHaveBeenCalledWith({ + towerMode: true, + planMode: false, + swarmMode: false, + }); expect(host.showNotice).toHaveBeenCalledWith('Tower mode: ON'); expect(host.showError).not.toHaveBeenCalled(); expect(host.sendNormalUserInput).not.toHaveBeenCalled(); }); + it('clears plan and swarm state when tower mode turns on', async () => { + const { host } = makeHost({ towerMode: false, planMode: true, swarmMode: true }); + + await handleTowerCommand(host, 'on'); + + expect(host.state.appState.towerMode).toBe(true); + expect(host.state.appState.planMode).toBe(false); + expect(host.state.appState.swarmMode).toBe(false); + expect(host.state.swarmModeEntry).toBeUndefined(); + }); + it('turns tower mode off with an explicit off subcommand', async () => { const { host, session } = makeHost({ towerMode: true }); @@ -195,7 +219,11 @@ describe('handleTowerCommand', () => { await handleTowerCommand(host, 'develop'); expect(session.setTowerMode).toHaveBeenCalledWith(true, 'develop'); - expect(host.setAppState).toHaveBeenCalledWith({ towerMode: true }); + expect(host.setAppState).toHaveBeenCalledWith({ + towerMode: true, + planMode: false, + swarmMode: false, + }); expect(host.showNotice).toHaveBeenCalledWith('Tower mode: ON (base: develop)'); expect(host.sendNormalUserInput).not.toHaveBeenCalled(); }); diff --git a/apps/kimi-code/test/tui/kimi-tui-message-flow.test.ts b/apps/kimi-code/test/tui/kimi-tui-message-flow.test.ts index 4e6f9956e13..e81763bc179 100644 --- a/apps/kimi-code/test/tui/kimi-tui-message-flow.test.ts +++ b/apps/kimi-code/test/tui/kimi-tui-message-flow.test.ts @@ -2958,6 +2958,33 @@ describe('KimiTUI message flow', () => { expect(driver.state.appState.planMode).toBe(true); }); + it('clears tower state when /plan on enables plan mode', async () => { + const session = makeSession({ + getPlan: vi.fn(async () => null), + getStatus: vi.fn(async () => ({ + model: 'k2', + thinkingEffort: 'off', + permission: 'auto', + planMode: false, + swarmMode: false, + towerMode: true, + contextTokens: 0, + maxContextTokens: 100, + contextUsage: 0, + })), + }); + const { driver } = await makeDriver(session); + expect(driver.state.appState.towerMode).toBe(true); + + driver.handleUserInput('/plan on'); + + await vi.waitFor(() => { + expect(driver.state.appState.planMode).toBe(true); + }); + expect(session.setPlanMode).toHaveBeenCalledWith(true); + expect(driver.state.appState.towerMode).toBe(false); + }); + it('clears the stale permission default when it is removed from config (v2 engine)', async () => { const homeDir = await makeTempHome(); process.env['KIMI_CODE_HOME'] = homeDir; diff --git a/packages/agent-core-v2/src/agent/modeMutex/modeMutex.ts b/packages/agent-core-v2/src/agent/modeMutex/modeMutex.ts index 1d6f5825650..b254c3ce88d 100644 --- a/packages/agent-core-v2/src/agent/modeMutex/modeMutex.ts +++ b/packages/agent-core-v2/src/agent/modeMutex/modeMutex.ts @@ -2,6 +2,9 @@ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiatio export interface IAgentModeMutexService { readonly _serviceBrand: undefined; + beforePlanEnter(): Promise; + beforeSwarmEnter(): void; + beforeTowerEnter(): Promise; } export const IAgentModeMutexService: ServiceIdentifier = diff --git a/packages/agent-core-v2/src/agent/modeMutex/modeMutexService.ts b/packages/agent-core-v2/src/agent/modeMutex/modeMutexService.ts index bd8b3a1ce1b..418a473e1e4 100644 --- a/packages/agent-core-v2/src/agent/modeMutex/modeMutexService.ts +++ b/packages/agent-core-v2/src/agent/modeMutex/modeMutexService.ts @@ -1,3 +1,4 @@ +import { IInstantiationService } from '#/_base/di/instantiation'; import { Disposable } from '#/_base/di/lifecycle'; import { ScopeActivation, registerScopedService } from '#/_base/di/scope'; import { IAgentStateService } from '#/agent/state/agentState'; @@ -7,11 +8,9 @@ import { LifecycleScope } from '#/app/scopes'; import { GoalUpdated } from '#/features/goal/goalOps'; import { IAgentGoalService } from '#/features/goal/goalService'; import { IAgentPlanService } from '#/features/plan/plan'; -import { PlanModeEnter, planKey } from '#/features/plan/planOps'; +import { planKey } from '#/features/plan/planOps'; import { IAgentSwarmService } from '#/features/swarm/agent/swarm'; -import { SwarmModeEnter } from '#/features/swarm/swarmOps'; import { IAgentTowerService } from '#/features/tower/tower'; -import { TowerModeEnter } from '#/features/tower/towerOps'; import { IEventDispatcher } from '#/state/eventDispatcher'; import { IAgentModeMutexService } from './modeMutex'; @@ -20,34 +19,13 @@ export class AgentModeMutexService extends Disposable implements IAgentModeMutex declare readonly _serviceBrand: undefined; constructor( - @IAgentPlanService private readonly plan: IAgentPlanService, - @IAgentSwarmService private readonly swarm: IAgentSwarmService, @IAgentTowerService private readonly tower: IAgentTowerService, - @IAgentGoalService private readonly goal: IAgentGoalService | undefined, + @IInstantiationService private readonly instantiation: IInstantiationService, @IAgentStateService private readonly agentState: IAgentStateService, @IEventDispatcher private readonly dispatcher: IEventDispatcher, @IEventBus eventBus: IEventBus, ) { super(); - this._register( - eventBus.subscribe(PlanModeEnter, () => { - if (this.tower.isActive) void this.tower.exit('mode-mutex'); - }), - ); - this._register( - eventBus.subscribe(SwarmModeEnter, () => { - if (this.tower.isActive) void this.tower.exit('mode-mutex'); - }), - ); - this._register( - eventBus.subscribe(TowerModeEnter, () => { - if (this.agentState.get(planKey).active) this.plan.exit(); - if (this.swarm.isActive) this.swarm.exit(); - if (this.goal?.getGoal().goal?.status === 'active') { - void this.goal.pauseGoal({ reason: 'Paused after tower mode entered' }, 'system'); - } - }), - ); this._register( eventBus.subscribe(GoalUpdated, (event) => { if (event.snapshot?.status !== 'active') return; @@ -62,6 +40,36 @@ export class AgentModeMutexService extends Disposable implements IAgentModeMutex void this.tower.exit('mode-mutex'); }), ); + this._register( + this.dispatcher.hooks.onDidRestore.register('modeMutex', async (_ctx, next) => { + if (this.tower.isActive) await this.beforeTowerEnter(); + await next(); + }), + ); + } + + async beforePlanEnter(): Promise { + if (this.tower.isActive) await this.tower.exit('mode-mutex'); + } + + beforeSwarmEnter(): void { + if (this.tower.isActive) void this.tower.exit('mode-mutex'); + } + + async beforeTowerEnter(): Promise { + if (this.agentState.get(planKey).active) { + this.instantiation.invokeFunction((accessor) => accessor.get(IAgentPlanService)).exit(); + } + const swarm = this.instantiation.invokeFunction((accessor) => + accessor.get(IAgentSwarmService), + ); + if (swarm.isActive) swarm.exit(); + const goal = this.instantiation.invokeFunction((accessor) => + accessor.get(IAgentGoalService), + ); + if (goal?.getGoal().goal?.status === 'active') { + await goal.pauseGoal({ reason: 'Paused after tower mode entered' }, 'system'); + } } } diff --git a/packages/agent-core-v2/src/features/plan/planService.ts b/packages/agent-core-v2/src/features/plan/planService.ts index 0443d3596d7..5f037df2ac0 100644 --- a/packages/agent-core-v2/src/features/plan/planService.ts +++ b/packages/agent-core-v2/src/features/plan/planService.ts @@ -3,11 +3,13 @@ import * as win32Path from 'node:path/win32'; import { createHash, randomUUID } from 'node:crypto'; +import { ref, type LiveRef } from '#/_base/di/instantiation'; import { type IDisposable } from '#/_base/di/lifecycle'; import { Service } from '#/_base/di/service'; import { Error2, ErrorCodes } from '#/errors'; import { generateHeroSlug } from '#/_base/utils/hero-slug'; import { IAgentLoopService } from '#/agent/loop/loop'; +import { IAgentModeMutexService } from '#/agent/modeMutex/modeMutex'; import { IAgentReminderService } from '#/features/reminder/reminderService'; import { PlanModeInjection } from '#/features/plan/injection/planModeInjection'; import { IHostEnvironment } from '#/os/interface/hostEnvironment'; @@ -67,6 +69,7 @@ export class AgentPlanService extends Service implements IAgentPlanService { @IAgentToolApprovalService private readonly toolApproval: IAgentToolApprovalService, @ITelemetryService private readonly telemetry: ITelemetryService, @IAgentStateService private readonly agentState: IAgentStateService, + @ref(IAgentModeMutexService) private readonly modeMutex: LiveRef, ) { super(); this.agentState.contributeState(planKey); @@ -189,13 +192,13 @@ export class AgentPlanService extends Service implements IAgentPlanService { if (this.isActive) { throw new Error2(ErrorCodes.SESSION_PLAN_MODE_INVALID, 'Already in plan mode'); } - const target = this.planFileTarget(id); let enterRecorded = false; try { if (target !== undefined) { await this.ensurePlanDirectory(target); } + await this.modeMutex.current?.beforePlanEnter(); await this.dispatcher.dispatch(new PlanModeEnter({ agentId: this.agentCtx.agentId, id })); this.telemetry.setContext({ mode: 'plan' }); enterRecorded = true; diff --git a/packages/agent-core-v2/src/features/swarm/agent/swarmService.ts b/packages/agent-core-v2/src/features/swarm/agent/swarmService.ts index 681230c5d71..aa1770e7325 100644 --- a/packages/agent-core-v2/src/features/swarm/agent/swarmService.ts +++ b/packages/agent-core-v2/src/features/swarm/agent/swarmService.ts @@ -1,3 +1,4 @@ +import { ref, type LiveRef } from '#/_base/di/instantiation'; import { Service } from '#/_base/di/service'; import { IAgentReminderService } from '#/features/reminder/reminderService'; import { TurnEnded } from '#/agent/loop/turnOps'; @@ -6,6 +7,7 @@ import { IAgentLoopService } from '#/agent/loop/loop'; import { IEventBus } from '#/app/event/eventBus'; import type { SwarmModeTransitionEvent } from '#/app/telemetry/events'; import { ITelemetryService } from '#/app/telemetry/telemetry'; +import { IAgentModeMutexService } from '#/agent/modeMutex/modeMutex'; import { IAgentScopeContext } from '#/agent/scopeContext/scopeContext'; import { IAgentStateService } from '#/agent/state/agentState'; import { Error2, ErrorCodes } from '#/errors'; @@ -27,6 +29,7 @@ export class AgentSwarmService extends Service implements IAgentSwarmService { @IAgentScopeContext private readonly agentCtx: IAgentScopeContext, @IAgentStateService private readonly agentState: IAgentStateService, @ITelemetryService private readonly telemetry: ITelemetryService, + @ref(IAgentModeMutexService) private readonly modeMutex: LiveRef, ) { super(); this.agentState.contributeState(swarmKey); @@ -74,6 +77,7 @@ export class AgentSwarmService extends Service implements IAgentSwarmService { throw new Error2(ErrorCodes.VALIDATION_FAILED, 'Only the user can turn on swarm mode.'); } if (this.agentState.get(swarmKey) !== null) return; + this.modeMutex.current?.beforeSwarmEnter(); void this.dispatcher.dispatch(new SwarmModeEnter({ agentId: this.agentCtx.agentId, trigger })); const properties: SwarmModeTransitionEvent = { trigger }; this.telemetry.track2('swarm_mode_entered', properties); diff --git a/packages/agent-core-v2/src/features/tower/towerService.ts b/packages/agent-core-v2/src/features/tower/towerService.ts index 3ec6860bc34..5597ceaf7a3 100644 --- a/packages/agent-core-v2/src/features/tower/towerService.ts +++ b/packages/agent-core-v2/src/features/tower/towerService.ts @@ -1,6 +1,6 @@ import { isAbsolute, join, resolve } from 'node:path'; -import { IInstantiationService } from '#/_base/di/instantiation'; +import { IInstantiationService, ref, type LiveRef } from '#/_base/di/instantiation'; import { Disposable, toDisposable } from '#/_base/di/lifecycle'; import { ScopeActivation, registerScopedService, type ISessionScopeHandle } from '#/_base/di/scope'; import { ILogService } from '#/_base/log/log'; @@ -8,6 +8,7 @@ import { userCancellationReason } from '#/_base/utils/abort'; import { IAgentReminderService } from '#/features/reminder/reminderService'; import { IAgentLifecycleService } from '#/session/agentLifecycle/agentLifecycle'; import { IAgentLoopService, type LoopNotifyHandle } from '#/agent/loop/loop'; +import { IAgentModeMutexService } from '#/agent/modeMutex/modeMutex'; import { TurnStarted } from '#/agent/loop/turnEvents'; import { TurnEnded } from '#/agent/loop/turnOps'; import { PromptSubmitted } from '#/agent/prompt/promptEvents'; @@ -129,6 +130,7 @@ export class AgentTowerService extends Disposable implements IAgentTowerService @ISessionWorkspaceContext private readonly workspaceCtx: ISessionWorkspaceContext | undefined, @IInstantiationService private readonly instantiation: IInstantiationService, @IAgentToolRegistryService private readonly toolRegistry: IAgentToolRegistryService, + @ref(IAgentModeMutexService) private readonly modeMutex: LiveRef, ) { super(); this.agentState.contributeState(towerKey); @@ -455,6 +457,12 @@ export class AgentTowerService extends Disposable implements IAgentTowerService } await this.adoptTowerRoster(); this.registerTowerTools(); + try { + await this.modeMutex.current?.beforeTowerEnter(); + } catch (error) { + this.unregisterTowerTools(); + throw error; + } this.lastPublished = true; this.dispatchEnter(); return { entered: true }; diff --git a/packages/agent-core-v2/src/features/tower/workerProfile.ts b/packages/agent-core-v2/src/features/tower/workerProfile.ts index 3604441b496..c415142d046 100644 --- a/packages/agent-core-v2/src/features/tower/workerProfile.ts +++ b/packages/agent-core-v2/src/features/tower/workerProfile.ts @@ -33,7 +33,6 @@ const TOWER_WORKER_TOOLS = [ 'TaskOutput', 'TaskStop', 'TodoList', - 'NotifyUser', 'WaitFor', 'WebSearch', 'FetchURL', diff --git a/packages/agent-core-v2/test/agent/modeMutex/modeMutex.integration.test.ts b/packages/agent-core-v2/test/agent/modeMutex/modeMutex.integration.test.ts new file mode 100644 index 00000000000..c388b254788 --- /dev/null +++ b/packages/agent-core-v2/test/agent/modeMutex/modeMutex.integration.test.ts @@ -0,0 +1,241 @@ +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { describe, expect, it, vi, type TestContext } from 'vitest'; + +import type { ISessionScopeHandle } from '#/_base/di/scope'; +import { Event } from '#/_base/event'; +import { IAgentModeMutexService } from '#/agent/modeMutex/modeMutex'; +import { IAgentToolRegistryService } from '#/agent/toolRegistry/toolRegistry'; +import { ISessionManager } from '#/app/sessionManager/sessionManager'; +import { IEventBus } from '#/app/event/eventBus'; +import { IFlagService } from '#/app/flag/flag'; +import { GoalUpdated } from '#/features/goal/goalOps'; +import { IAgentGoalService } from '#/features/goal/goalService'; +import { IAgentPlanService } from '#/features/plan/plan'; +import { IAgentSwarmService } from '#/features/swarm/agent/swarm'; +import { IAgentTowerService, TOWER_FLAG_ID } from '#/features/tower/tower'; +import { _setTowerFeatureAssembledForTests } from '#/features/tower/towerFeature'; +import { IHostFileSystem } from '#/os/interface/hostFileSystem'; +import type { WireRecord } from '#/wire/record'; + +import { stubFlag } from '../../app/flag/stubs'; +import { + appService, + InMemoryWireRecordPersistence, + sessionService, + testkitAgentFixtures, + wireRecordPersistenceServices, + type TestAgentContext, + type TestAgentInput, +} from '../../harness'; + +_setTowerFeatureAssembledForTests(true); + +async function withAgent( + context: TestContext, + body: (agent: TestAgentContext) => Promise, + ...extraInputs: readonly TestAgentInput[] +): Promise { + const cwd = await mkdtemp(join(tmpdir(), 'mode-mutex-e2e-')); + try { + const fixtures = testkitAgentFixtures( + appService(IFlagService, stubFlag((id) => id === TOWER_FLAG_ID)), + { cwd }, + ...extraInputs, + ); + await fixtures.model(context, async (model) => { + await fixtures.agent({ model }, async (agent) => { + await agent.restorePersisted(); + await body(agent); + }); + }); + } finally { + await rm(cwd, { recursive: true, force: true }); + } +} + +describe('AgentModeMutexService integration', () => { + it('instantiates the mutex service in a real agent scope', async (context) => { + await withAgent(context, async (agent) => { + expect(agent.get(IAgentModeMutexService)).toBeDefined(); + }); + }); + + it('entering plan exits active tower', async (context) => { + await withAgent(context, async (agent) => { + await agent.get(IAgentTowerService).enter(); + expect(agent.get(IAgentTowerService).isActive).toBe(true); + + await agent.get(IAgentPlanService).enter(); + + expect(await agent.get(IAgentPlanService).status()).not.toBeNull(); + expect(agent.get(IAgentTowerService).isActive).toBe(false); + }); + }); + + it('entering swarm exits active tower', async (context) => { + await withAgent(context, async (agent) => { + await agent.get(IAgentTowerService).enter(); + expect(agent.get(IAgentTowerService).isActive).toBe(true); + + agent.get(IAgentSwarmService).enter('manual'); + + expect(agent.get(IAgentSwarmService).isActive).toBe(true); + expect(agent.get(IAgentTowerService).isActive).toBe(false); + }); + }); + + it('entering tower exits active plan', async (context) => { + await withAgent(context, async (agent) => { + await agent.get(IAgentPlanService).enter(); + + await agent.get(IAgentTowerService).enter(); + + expect(agent.get(IAgentTowerService).isActive).toBe(true); + expect(await agent.get(IAgentPlanService).status()).toBeNull(); + }); + }); + + it('entering tower exits active swarm', async (context) => { + await withAgent(context, async (agent) => { + agent.get(IAgentSwarmService).enter('manual'); + + await agent.get(IAgentTowerService).enter(); + + expect(agent.get(IAgentTowerService).isActive).toBe(true); + expect(agent.get(IAgentSwarmService).isActive).toBe(false); + }); + }); + + it('entering tower pauses an active goal and publishes the paused snapshot', async (context) => { + await withAgent(context, async (agent) => { + await agent.get(IAgentGoalService).createGoal({ objective: 'ship it' }); + const updates: Array = []; + agent.get(IEventBus).subscribe(GoalUpdated, (event) => { + updates.push(event.snapshot?.status); + }); + + await agent.get(IAgentTowerService).enter(); + + expect(agent.get(IAgentTowerService).isActive).toBe(true); + expect(agent.get(IAgentGoalService).getGoal().goal?.status).toBe('paused'); + expect(updates).toEqual(['paused']); + }); + }); + + it('creating a goal exits active tower', async (context) => { + await withAgent(context, async (agent) => { + await agent.get(IAgentTowerService).enter(); + + await agent.get(IAgentGoalService).createGoal({ objective: 'ship it' }); + + expect(agent.get(IAgentGoalService).getGoal().goal?.status).toBe('active'); + expect(agent.get(IAgentTowerService).isActive).toBe(false); + }); + }); + + it('resuming a goal exits active tower', async (context) => { + await withAgent(context, async (agent) => { + await agent.get(IAgentGoalService).createGoal({ objective: 'ship it' }); + await agent.get(IAgentGoalService).pauseGoal(); + await agent.get(IAgentTowerService).enter(); + + await agent.get(IAgentGoalService).resumeGoal(); + + expect(agent.get(IAgentGoalService).getGoal().goal?.status).toBe('active'); + expect(agent.get(IAgentTowerService).isActive).toBe(false); + }); + }); + + it('reconciles legacy sessions restored with tower and other modes active together', async (context) => { + const records: WireRecord[] = [ + { type: 'tower_mode.enter', agentId: 'main', sessionId: 'test-session', time: 1 }, + { type: 'plan_mode.enter', agentId: 'main', id: 'legacy-plan', time: 2 }, + { type: 'swarm_mode.enter', agentId: 'main', trigger: 'manual', time: 3 }, + { type: 'goal.create', agentId: 'main', goalId: 'g1', objective: 'legacy goal', time: 4 }, + ]; + await withAgent( + context, + async (agent) => { + expect(agent.get(IAgentTowerService).isActive).toBe(true); + expect(await agent.get(IAgentPlanService).status()).toBeNull(); + expect(agent.get(IAgentSwarmService).isActive).toBe(false); + expect(agent.get(IAgentGoalService).getGoal().goal?.status).toBe('paused'); + }, + { autoStart: false }, + wireRecordPersistenceServices(new InMemoryWireRecordPersistence(records)), + ); + }); + + it('reconciles a live foreign tower owner before applying mutex on restore', async (context) => { + const records: WireRecord[] = [ + { type: 'tower_mode.enter', agentId: 'main', sessionId: 'session-original', time: 1 }, + { type: 'plan_mode.enter', agentId: 'main', id: 'fork-plan', time: 2 }, + { type: 'swarm_mode.enter', agentId: 'main', trigger: 'manual', time: 3 }, + { type: 'goal.create', agentId: 'main', goalId: 'g1', objective: 'keep me intact', time: 4 }, + ]; + const persistence = new InMemoryWireRecordPersistence(records); + await withAgent( + context, + async (agent) => { + expect(agent.get(IAgentTowerService).isActive).toBe(false); + expect(await agent.get(IAgentPlanService).status()).toMatchObject({ id: 'fork-plan' }); + expect(agent.get(IAgentSwarmService).isActive).toBe(true); + expect(agent.get(IAgentGoalService).getGoal().goal?.status).toBe('paused'); + const goalUpdates = persistence.records.filter( + (record) => record.type === 'goal.update', + ); + expect(goalUpdates).toEqual([ + expect.objectContaining({ reason: 'Paused after agent resume', actor: 'runtime' }), + ]); + }, + { autoStart: false }, + wireRecordPersistenceServices(persistence), + sessionService(ISessionManager, { + get: (id: string) => + id === 'session-original' ? ({} as ISessionScopeHandle) : undefined, + list: () => [], + onDidCreateSession: Event.None, + onWillCloseSession: Event.None, + } as unknown as ISessionManager), + ); + }); + + it('leaves existing modes intact when tower tool registration fails', async (context) => { + await withAgent(context, async (agent) => { + await agent.get(IAgentPlanService).enter(); + await agent.get(IAgentGoalService).createGoal({ objective: 'keep it' }); + const register = vi + .spyOn(agent.get(IAgentToolRegistryService), 'register') + .mockImplementationOnce(() => { + throw new Error('Tool "TowerStatus" is already registered'); + }); + try { + await expect(agent.get(IAgentTowerService).enter()).rejects.toThrow('already registered'); + expect(agent.get(IAgentTowerService).isActive).toBe(false); + expect(await agent.get(IAgentPlanService).status()).not.toBeNull(); + expect(agent.get(IAgentGoalService).getGoal().goal?.status).toBe('active'); + } finally { + register.mockRestore(); + } + }); + }); + + it('keeps tower active when plan directory creation fails', async (context) => { + await withAgent(context, async (agent) => { + await agent.get(IAgentTowerService).enter(); + const mkdir = vi + .spyOn(agent.get(IHostFileSystem), 'mkdir') + .mockRejectedValueOnce(new Error('EACCES: read-only file system')); + try { + await expect(agent.get(IAgentPlanService).enter()).rejects.toThrow('EACCES'); + expect(await agent.get(IAgentPlanService).status()).toBeNull(); + expect(agent.get(IAgentTowerService).isActive).toBe(true); + } finally { + mkdir.mockRestore(); + } + }); + }); +}); diff --git a/packages/agent-core-v2/test/agent/modeMutex/modeMutex.test.ts b/packages/agent-core-v2/test/agent/modeMutex/modeMutex.test.ts index 1d8c862b077..9f0b45a88ff 100644 --- a/packages/agent-core-v2/test/agent/modeMutex/modeMutex.test.ts +++ b/packages/agent-core-v2/test/agent/modeMutex/modeMutex.test.ts @@ -15,11 +15,10 @@ import { GoalUpdated } from '#/features/goal/goalOps'; import { IAgentGoalService } from '#/features/goal/goalService'; import type { GoalSnapshot } from '#/features/goal/types'; import { IAgentPlanService } from '#/features/plan/plan'; -import { PlanModeEnter, planKey } from '#/features/plan/planOps'; +import { planKey } from '#/features/plan/planOps'; import { IAgentSwarmService } from '#/features/swarm/agent/swarm'; -import { SwarmModeEnter } from '#/features/swarm/swarmOps'; import { IAgentTowerService } from '#/features/tower/tower'; -import { TowerModeEnter } from '#/features/tower/towerOps'; +import { OrderedHookSlot } from '#/hooks'; import { IEventDispatcher } from '#/state/eventDispatcher'; import { registerTestAgentWire, testWireScope } from '../../wire/stubs'; @@ -32,6 +31,7 @@ describe('AgentModeMutexService', () => { let towerExit: ReturnType; let goalPause: ReturnType; let dispatch: ReturnType; + let onDidRestore: OrderedHookSlot>; let swarmActive: boolean; let towerActive: boolean; let goalStatus: string | undefined; @@ -46,9 +46,10 @@ describe('AgentModeMutexService', () => { }); planExit = vi.fn(); swarmExit = vi.fn(); - towerExit = vi.fn(); - goalPause = vi.fn(); + towerExit = vi.fn(async () => {}); + goalPause = vi.fn(async () => {}); dispatch = vi.fn(); + onDidRestore = new OrderedHookSlot(); swarmActive = false; towerActive = false; goalStatus = undefined; @@ -69,109 +70,131 @@ describe('AgentModeMutexService', () => { pauseGoal: goalPause, getGoal: () => ({ goal: goalStatus === undefined ? null : { status: goalStatus } }), } as unknown as IAgentGoalService); - ix.stub(IEventDispatcher, { dispatch } as unknown as IEventDispatcher); + ix.stub(IEventDispatcher, { + dispatch, + hooks: { onDidRestore }, + } as unknown as IEventDispatcher); ix.get(IAgentStateService).contributeState(planKey); ix.set(IAgentModeMutexService, new SyncDescriptor(AgentModeMutexService)); ix.get(IAgentModeMutexService); }); afterEach(() => disposables.dispose()); - function publish(event: PlanModeEnter | SwarmModeEnter | TowerModeEnter | GoalUpdated): void { + function publishGoal(snapshot: GoalSnapshot): void { const agentContext = ix.get(IAgentScopeContext).agentContext; - ix.get(IEventBus).publish(event, agentContext); + ix.get(IEventBus).publish( + new GoalUpdated({ agentId: 'test-agent', snapshot }), + agentContext, + ); } - it('plan mode entry exits an active tower mode', () => { + it('plan entry exits an active tower mode', async () => { towerActive = true; - publish(new PlanModeEnter({ agentId: 'test-agent', id: 'plan_1' })); + await ix.get(IAgentModeMutexService).beforePlanEnter(); expect(towerExit).toHaveBeenCalledTimes(1); expect(towerExit).toHaveBeenCalledWith('mode-mutex'); }); - it('plan mode entry leaves an inactive tower mode alone', () => { - publish(new PlanModeEnter({ agentId: 'test-agent', id: 'plan_1' })); + it('plan entry leaves an inactive tower mode alone', async () => { + await ix.get(IAgentModeMutexService).beforePlanEnter(); expect(towerExit).not.toHaveBeenCalled(); }); - it('swarm mode entry exits an active tower mode', () => { + it('swarm entry exits an active tower mode', () => { towerActive = true; - publish(new SwarmModeEnter({ agentId: 'test-agent', trigger: 'manual' })); + ix.get(IAgentModeMutexService).beforeSwarmEnter(); expect(towerExit).toHaveBeenCalledTimes(1); expect(towerExit).toHaveBeenCalledWith('mode-mutex'); }); - it('swarm mode entry leaves an inactive tower mode alone', () => { - publish(new SwarmModeEnter({ agentId: 'test-agent', trigger: 'manual' })); + it('swarm entry leaves an inactive tower mode alone', () => { + ix.get(IAgentModeMutexService).beforeSwarmEnter(); expect(towerExit).not.toHaveBeenCalled(); }); - it('tower mode entry exits an active plan mode and an active swarm mode', () => { + it('tower entry exits an active plan mode and an active swarm mode', async () => { ix.get(IAgentStateService).set(planKey, { active: true, id: 'plan_1' }); swarmActive = true; - publish(new TowerModeEnter({ agentId: 'test-agent' })); + await ix.get(IAgentModeMutexService).beforeTowerEnter(); expect(planExit).toHaveBeenCalledTimes(1); expect(swarmExit).toHaveBeenCalledTimes(1); }); - it('tower mode entry leaves inactive plan and swarm modes alone', () => { - publish(new TowerModeEnter({ agentId: 'test-agent' })); + it('tower entry leaves inactive plan and swarm modes alone', async () => { + await ix.get(IAgentModeMutexService).beforeTowerEnter(); expect(planExit).not.toHaveBeenCalled(); expect(swarmExit).not.toHaveBeenCalled(); }); - it('tower mode entry pauses an active goal', () => { + it('tower entry pauses an active goal', async () => { goalStatus = 'active'; - publish(new TowerModeEnter({ agentId: 'test-agent' })); + await ix.get(IAgentModeMutexService).beforeTowerEnter(); expect(goalPause).toHaveBeenCalledTimes(1); + expect(goalPause).toHaveBeenCalledWith( + { reason: 'Paused after tower mode entered' }, + 'system', + ); }); - it('tower mode entry leaves a non-active goal alone', () => { + it('tower entry leaves a non-active goal alone', async () => { goalStatus = 'paused'; - publish(new TowerModeEnter({ agentId: 'test-agent' })); + await ix.get(IAgentModeMutexService).beforeTowerEnter(); expect(goalPause).not.toHaveBeenCalled(); }); it('goal activation exits an active tower mode with the mode-mutex reason', () => { towerActive = true; - publish( - new GoalUpdated({ - agentId: 'test-agent', - snapshot: { status: 'active' } as GoalSnapshot, - }), - ); + publishGoal({ status: 'active' } as GoalSnapshot); expect(towerExit).toHaveBeenCalledTimes(1); expect(towerExit).toHaveBeenCalledWith('mode-mutex'); expect(dispatch).toHaveBeenCalledTimes(1); const status = dispatch.mock.calls[0]![0] as AgentStatusUpdated; expect(status).toBeInstanceOf(AgentStatusUpdated); - expect(status.agentId).toBe('test-agent'); - expect(status.towerMode).toBe(false); - expect(status.towerExitReason).toBe('mode-mutex'); + expect(status).toMatchObject({ + agentId: 'test-agent', + towerMode: false, + towerExitReason: 'mode-mutex', + }); expect(dispatch.mock.invocationCallOrder[0]).toBeLessThan( towerExit.mock.invocationCallOrder[0]!, ); }); it('goal activation leaves an inactive tower mode alone', () => { - publish( - new GoalUpdated({ - agentId: 'test-agent', - snapshot: { status: 'active' } as GoalSnapshot, - }), - ); + publishGoal({ status: 'active' } as GoalSnapshot); expect(towerExit).not.toHaveBeenCalled(); - expect(dispatch).not.toHaveBeenCalled(); }); it('a non-active goal update does not exit tower mode', () => { towerActive = true; - publish( - new GoalUpdated({ - agentId: 'test-agent', - snapshot: { status: 'paused' } as GoalSnapshot, - }), - ); + publishGoal({ status: 'paused' } as GoalSnapshot); + expect(towerExit).not.toHaveBeenCalled(); + }); + + it('restore reconciles conflicting modes when tower is active', async () => { + towerActive = true; + swarmActive = true; + goalStatus = 'active'; + ix.get(IAgentStateService).set(planKey, { active: true, id: 'plan_1' }); + + await onDidRestore.run({}); + + expect(planExit).toHaveBeenCalledTimes(1); + expect(swarmExit).toHaveBeenCalledTimes(1); + expect(goalPause).toHaveBeenCalledTimes(1); + expect(towerExit).not.toHaveBeenCalled(); + }); + + it('restore leaves non-tower modes alone when tower is inactive', async () => { + swarmActive = true; + goalStatus = 'active'; + ix.get(IAgentStateService).set(planKey, { active: true, id: 'plan_1' }); + + await onDidRestore.run({}); + + expect(planExit).not.toHaveBeenCalled(); + expect(swarmExit).not.toHaveBeenCalled(); + expect(goalPause).not.toHaveBeenCalled(); expect(towerExit).not.toHaveBeenCalled(); - expect(dispatch).not.toHaveBeenCalled(); }); }); diff --git a/packages/agent-core-v2/test/features/tower/workerProfile.test.ts b/packages/agent-core-v2/test/features/tower/workerProfile.test.ts index 3737785e925..47263394921 100644 --- a/packages/agent-core-v2/test/features/tower/workerProfile.test.ts +++ b/packages/agent-core-v2/test/features/tower/workerProfile.test.ts @@ -11,16 +11,17 @@ function builtinProfile(name: string) { } describe('tower-worker profile', () => { - it('gives tower-worker the coder tools (minus Agent and AgentSwarm) plus the seven shared tower tools', () => { + it('gives tower-worker the coder tools (minus Agent, AgentSwarm, and NotifyUser) plus the seven shared tower tools', () => { const coder = builtinProfile('coder'); const tools = TOWER_WORKER_PROFILE_DEF.tools ?? []; for (const name of coder.tools ?? []) { - if (name === 'Agent' || name === 'AgentSwarm') continue; + if (name === 'Agent' || name === 'AgentSwarm' || name === 'NotifyUser') continue; expect(tools).toContain(name); } expect(tools).not.toContain('Agent'); expect(tools).not.toContain('AgentSwarm'); + expect(tools).not.toContain('NotifyUser'); for (const name of [ 'TowerComplete', 'TowerSend', diff --git a/packages/app-client/src/client/usePromptPipeline.ts b/packages/app-client/src/client/usePromptPipeline.ts index 83abac5d421..114c3cea032 100644 --- a/packages/app-client/src/client/usePromptPipeline.ts +++ b/packages/app-client/src/client/usePromptPipeline.ts @@ -395,8 +395,12 @@ export function usePromptPipeline(rawState: ExtendedState, deps: PromptPipelineD if (!(await commitArmedPlanMode(sid))) return rollBackSubmit(sid, tempId); if ((modeStore().goalModeBySession[sid] ?? false) && text) { - if (!(await persistSessionProfile({ goalObjective: text.trim(), planMode: false }, sid))) return rollBackSubmit(sid, tempId); + if (!(await persistSessionProfile({ goalObjective: text.trim(), planMode: false, towerMode: false }, sid))) return rollBackSubmit(sid, tempId); modeStore().planModeBySession = { ...modeStore().planModeBySession, [sid]: false }; + if (modeStore().towerModeBySession[sid]) { + modeStore().towerModeBySession = { ...modeStore().towerModeBySession, [sid]: false }; + modeStore().saveTowerModeToStorage(); + } modeStore().goalModeBySession = { ...modeStore().goalModeBySession, [sid]: false }; modeStore().saveGoalModeToStorage(); } diff --git a/packages/app-client/src/stores/goal.ts b/packages/app-client/src/stores/goal.ts index ad0895bd28b..394f12d4c8d 100644 --- a/packages/app-client/src/stores/goal.ts +++ b/packages/app-client/src/stores/goal.ts @@ -79,8 +79,16 @@ export const useGoalStore = defineStore('kimi.goal', () => { async function createGoalObjective(sessionId: string, objective: string): Promise { try { - await getKimiWebApi().updateSession(sessionId, { goalObjective: objective, planMode: false }); + await getKimiWebApi().updateSession(sessionId, { + goalObjective: objective, + planMode: false, + towerMode: false, + }); modeStore().planModeBySession = { ...modeStore().planModeBySession, [sessionId]: false }; + if (modeStore().towerModeBySession[sessionId]) { + modeStore().towerModeBySession = { ...modeStore().towerModeBySession, [sessionId]: false }; + modeStore().saveTowerModeToStorage(); + } } catch (err) { goalHooks?.pushOperationFailure('createGoal', err, { sessionId, @@ -98,7 +106,18 @@ export const useGoalStore = defineStore('kimi.goal', () => { function controlGoal(action: 'pause' | 'resume' | 'cancel'): void { const sid = sessionsStore().activeSessionId; if (!sid) return; - void Promise.resolve(getKimiWebApi().updateSession(sid, { goalControl: action })) + void Promise.resolve( + getKimiWebApi().updateSession(sid, { + goalControl: action, + ...(action === 'resume' ? { towerMode: false } : {}), + }), + ) + .then(() => { + if (action === 'resume' && modeStore().towerModeBySession[sid]) { + modeStore().towerModeBySession = { ...modeStore().towerModeBySession, [sid]: false }; + modeStore().saveTowerModeToStorage(); + } + }) .catch((err) => { goalHooks?.pushOperationFailure('controlGoal', err, { sessionId: sid, diff --git a/packages/app-client/src/stores/mode.ts b/packages/app-client/src/stores/mode.ts index 81636c9480d..55c09093bf1 100644 --- a/packages/app-client/src/stores/mode.ts +++ b/packages/app-client/src/stores/mode.ts @@ -156,6 +156,7 @@ export const useModeStore = defineStore('kimi.mode', () => { function setTowerMode(on: boolean, base?: string): Promise { const sid = sessionsStore().activeSessionId; if (sid) { + const armedGoal = on && (goalModeBySession.value[sid] ?? false); if (on) { swarmModeBySession.value = { ...swarmModeBySession.value, [sid]: false }; saveSwarmModeToStorage(); @@ -166,11 +167,15 @@ export const useModeStore = defineStore('kimi.mode', () => { planModeBySession.value = { ...planModeBySession.value, [sid]: false }; savePlanModeToStorage(); markPlanPending({ pendingPlanBySession: pendingPlanBySession.value }, sid); + if (armedGoal) { + goalModeBySession.value = { ...goalModeBySession.value, [sid]: false }; + saveGoalModeToStorage(); + } } towerModeBySession.value = { ...towerModeBySession.value, [sid]: on }; saveTowerModeToStorage(); markTowerPending({ pendingTowerBySession: pendingTowerBySession.value }, sid); - return ( + const persisted = modeHooks?.persistSessionProfile( { towerMode: on, @@ -179,11 +184,26 @@ export const useModeStore = defineStore('kimi.mode', () => { planMode: on ? false : undefined, }, sid, - ) ?? Promise.resolve(true) + ) ?? Promise.resolve(true); + if (!armedGoal) return persisted; + const restoreArmedGoal = (): void => { + goalModeBySession.value = { ...goalModeBySession.value, [sid]: true }; + saveGoalModeToStorage(); + }; + return persisted.then( + (ok) => { + if (!ok && !(towerModeBySession.value[sid] ?? false)) restoreArmedGoal(); + return ok; + }, + (error: unknown) => { + if (!(towerModeBySession.value[sid] ?? false)) restoreArmedGoal(); + throw error; + }, ); } if (on && draftModes.swarmMode) draftModes.swarmMode = false; if (on && draftModes.planMode) draftModes.planMode = false; + if (on && draftModes.goalMode) draftModes.goalMode = false; draftModes.towerMode = on; draftModes.towerBase = on ? base : undefined; return Promise.resolve(true); @@ -192,9 +212,14 @@ export const useModeStore = defineStore('kimi.mode', () => { function setGoalMode(on: boolean): void { const sid = sessionsStore().activeSessionId; if (sid) { + if (on && (towerModeBySession.value[sid] ?? false)) void setTowerMode(false); goalModeBySession.value = { ...goalModeBySession.value, [sid]: on }; saveGoalModeToStorage(); } else { + if (on && draftModes.towerMode) { + draftModes.towerMode = false; + draftModes.towerBase = undefined; + } draftModes.goalMode = on; } } diff --git a/packages/app-client/test/goal-store.test.ts b/packages/app-client/test/goal-store.test.ts index 11d216a249c..ed503ad1561 100644 --- a/packages/app-client/test/goal-store.test.ts +++ b/packages/app-client/test/goal-store.test.ts @@ -86,6 +86,7 @@ describe('goalStore createGoalObjective', () => { expect(apiMock.updateSession).toHaveBeenCalledExactlyOnceWith('s1', { goalObjective: 'improve coverage', planMode: false, + towerMode: false, }); expect(modeStore().planModeBySession.s1).toBe(false); expect(modeStore().goalModeBySession.s1).toBe(false); @@ -100,6 +101,20 @@ describe('goalStore createGoalObjective', () => { expect(modeStore().planModeBySession.s1).toBe(false); }); + it('atomically disables tower in the same write when creating a goal on a tower session', async () => { + modeStore().towerModeBySession = { s1: true }; + + const created = await goalStore().createGoalObjective('s1', 'improve coverage'); + + expect(created).toBe(true); + expect(apiMock.updateSession).toHaveBeenCalledExactlyOnceWith('s1', { + goalObjective: 'improve coverage', + planMode: false, + towerMode: false, + }); + expect(modeStore().towerModeBySession.s1).toBe(false); + }); + it('reports an existing goal without creating a duplicate', async () => { apiMock.updateSession.mockRejectedValue( new DaemonApiError({ code: 40913, msg: 'goal already exists', requestId: 'r' }), @@ -148,6 +163,21 @@ describe('goalStore controlGoal', () => { expect(apiMock.updateSession).not.toHaveBeenCalled(); }); + it('clears tower mode locally when resuming a goal on a tower session', async () => { + sessionsStore().setActiveSessionId('s1'); + modeStore().towerModeBySession = { s1: true }; + + goalStore().controlGoal('resume'); + + await vi.waitFor(() => + expect(apiMock.updateSession).toHaveBeenCalledExactlyOnceWith('s1', { + goalControl: 'resume', + towerMode: false, + }), + ); + expect(modeStore().towerModeBySession.s1).toBe(false); + }); + it('reports a control failure', async () => { sessionsStore().setActiveSessionId('s1'); apiMock.updateSession.mockRejectedValue( diff --git a/packages/app-client/test/mode-store.test.ts b/packages/app-client/test/mode-store.test.ts index af7f3ac9e19..3791e91c7ca 100644 --- a/packages/app-client/test/mode-store.test.ts +++ b/packages/app-client/test/mode-store.test.ts @@ -214,6 +214,119 @@ describe('mode store setGoalMode', () => { modeStore().setGoalMode(true); expect(modeStore().draftModes.goalMode).toBe(true); }); + + it('disarms an active tower mode when enabling goal mode for a session', () => { + sessionsStore().setActiveSessionId('sess_1'); + const persist = vi.fn().mockResolvedValue(true); + setModeHooks({ persistSessionProfile: persist }); + modeStore().towerModeBySession = { sess_1: true }; + + modeStore().setGoalMode(true); + + expect(modeStore().goalModeBySession.sess_1).toBe(true); + expect(modeStore().towerModeBySession.sess_1).toBe(false); + expect(persist).toHaveBeenCalledWith({ towerMode: false }, 'sess_1'); + }); + + it('disarms draft tower mode when enabling draft goal mode', () => { + modeStore().draftModes.towerMode = true; + modeStore().draftModes.towerBase = 'main'; + + modeStore().setGoalMode(true); + + expect(modeStore().draftModes.goalMode).toBe(true); + expect(modeStore().draftModes.towerMode).toBe(false); + expect(modeStore().draftModes.towerBase).toBeUndefined(); + }); +}); + +describe('mode store setTowerMode', () => { + it('disarms plan, swarm, and goal modes when enabling tower mode for a session', async () => { + sessionsStore().setActiveSessionId('sess_1'); + const persist = vi.fn().mockResolvedValue(true); + setModeHooks({ persistSessionProfile: persist }); + modeStore().planArmedBySession = { sess_1: true }; + modeStore().planModeBySession = { sess_1: true }; + modeStore().swarmModeBySession = { sess_1: true }; + modeStore().goalModeBySession = { sess_1: true }; + + await modeStore().setTowerMode(true); + + expect(modeStore().towerModeBySession.sess_1).toBe(true); + expect(modeStore().planArmedBySession.sess_1).toBe(false); + expect(modeStore().planModeBySession.sess_1).toBe(false); + expect(modeStore().swarmModeBySession.sess_1).toBe(false); + expect(modeStore().goalModeBySession.sess_1).toBe(false); + expect(JSON.parse(localStorage.getItem(STORAGE_KEYS.goalMode)!)).toEqual({}); + expect(persist).toHaveBeenCalledWith( + { towerMode: true, towerBase: undefined, swarmMode: false, planMode: false }, + 'sess_1', + ); + }); + + it('restores armed goal mode when enabling tower mode fails for a session', async () => { + sessionsStore().setActiveSessionId('sess_1'); + const persist = vi.fn().mockImplementation(async () => { + modeStore().towerModeBySession = { sess_1: false }; + return false; + }); + setModeHooks({ persistSessionProfile: persist }); + modeStore().goalModeBySession = { sess_1: true }; + modeStore().saveGoalModeToStorage(); + + const ok = await modeStore().setTowerMode(true); + + expect(ok).toBe(false); + expect(modeStore().goalModeBySession.sess_1).toBe(true); + expect(JSON.parse(localStorage.getItem(STORAGE_KEYS.goalMode)!)).toEqual({ sess_1: true }); + }); + + it('restores armed goal mode when enabling tower mode rejects for a session', async () => { + sessionsStore().setActiveSessionId('sess_1'); + const persist = vi.fn().mockImplementation(async () => { + modeStore().towerModeBySession = { sess_1: false }; + throw new Error('network down'); + }); + setModeHooks({ persistSessionProfile: persist }); + modeStore().goalModeBySession = { sess_1: true }; + modeStore().saveGoalModeToStorage(); + + await expect(modeStore().setTowerMode(true)).rejects.toThrow('network down'); + + expect(modeStore().goalModeBySession.sess_1).toBe(true); + expect(JSON.parse(localStorage.getItem(STORAGE_KEYS.goalMode)!)).toEqual({ sess_1: true }); + }); + + it('does not re-arm goal when tower is active but an earlier profile write failed', async () => { + sessionsStore().setActiveSessionId('sess_1'); + const persist = vi.fn().mockResolvedValue(false); + setModeHooks({ persistSessionProfile: persist }); + modeStore().goalModeBySession = { sess_1: true }; + modeStore().saveGoalModeToStorage(); + + const ok = await modeStore().setTowerMode(true); + + expect(ok).toBe(false); + expect(modeStore().towerModeBySession.sess_1).toBe(true); + expect(modeStore().goalModeBySession.sess_1).toBe(false); + expect(JSON.parse(localStorage.getItem(STORAGE_KEYS.goalMode)!)).toEqual({}); + }); + + it('disarms draft plan, swarm, and goal modes when enabling draft tower mode', async () => { + modeStore().draftModes.planMode = true; + modeStore().draftModes.swarmMode = true; + modeStore().draftModes.goalMode = true; + + await modeStore().setTowerMode(true); + + expect(modeStore().draftModes).toEqual({ + planMode: false, + swarmMode: false, + towerMode: true, + towerBase: undefined, + goalMode: false, + }); + }); }); describe('mode store projections', () => { diff --git a/packages/app-client/test/workspace-state.test.ts b/packages/app-client/test/workspace-state.test.ts index 1906ee5caec..6daaff446a5 100644 --- a/packages/app-client/test/workspace-state.test.ts +++ b/packages/app-client/test/workspace-state.test.ts @@ -1379,7 +1379,7 @@ describe('useWorkspaceState — createGoal from an empty composer', () => { await ws.createGoal({ text, snapshot, attachments: [] }); - expect(apiMock.updateSession).toHaveBeenCalledWith('sess_new', { goalObjective: 'Fix Button: Save · Rename this', planMode: false }); + expect(apiMock.updateSession).toHaveBeenCalledWith('sess_new', { goalObjective: 'Fix Button: Save · Rename this', planMode: false, towerMode: false }); const sent = apiMock.submitPrompt.mock.calls[0]?.[1] as { content: { text?: string }[] }; expect(sent.content.map((part) => part.text ?? '').join('\n')).toContain(''); expect(pushFailureSpy).not.toHaveBeenCalled(); @@ -1396,6 +1396,7 @@ describe('useWorkspaceState — createGoal from an empty composer', () => { expect(apiMock.updateSession).toHaveBeenCalledWith('sess_new', { goalObjective: 'improve test coverage', planMode: false, + towerMode: false, }); expect(apiMock.submitPrompt).toHaveBeenCalledWith( 'sess_new', @@ -1417,6 +1418,7 @@ describe('useWorkspaceState — createGoal from an empty composer', () => { expect(apiMock.updateSession).toHaveBeenCalledWith('sess_new', { goalObjective: 'improve test coverage', planMode: false, + towerMode: false, }); expect(apiMock.submitPrompt).toHaveBeenCalledOnce(); }); @@ -1433,6 +1435,7 @@ describe('useWorkspaceState — createGoal from an empty composer', () => { expect(apiMock.updateSession).toHaveBeenCalledWith('sess_1', { goalObjective: 'improve test coverage', planMode: false, + towerMode: false, }); expect(apiMock.submitPrompt).not.toHaveBeenCalled(); expect(promptStore().queuedBySession['sess_1']).toEqual([ @@ -1528,6 +1531,7 @@ describe('useWorkspaceState — createGoal from an empty composer', () => { expect(apiMock.updateSession).toHaveBeenCalledWith('sess_new', { goalObjective: 'improve test coverage', planMode: false, + towerMode: false, }); expect(apiMock.submitPrompt).toHaveBeenCalledTimes(1); expect(apiMock.submitPrompt).toHaveBeenCalledWith( @@ -2472,6 +2476,7 @@ describe('useWorkspaceState — snapshot prompt recovery', () => { expect(apiMock.updateSession).toHaveBeenCalledWith('sess_1', { goalObjective: prompt.text, planMode: false, + towerMode: false, }); expect(state.goalModeBySession.sess_1).toBe(false); expect(saveGoalSpy).toHaveBeenCalledOnce();