Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(goal): 普通消息后继续目标并接通手机命令 (#5919)

Chris Zhang551e02554d57
diff --git a/apps/desktop/src/main/commands/builtins.ts b/apps/desktop/src/main/commands/builtins.ts
index 00aa05f103..2bf4133748 100644
--- a/apps/desktop/src/main/commands/builtins.ts
+++ b/apps/desktop/src/main/commands/builtins.ts
@@ -12,6 +12,7 @@
import { spawn } from 'node:child_process';
import { app, BrowserWindow, webContents } from 'electron';
+import { parseGoalCommand } from '@cindy/maker-shared/goal-command';
import { BRAND_NAME } from '@cindy/maker-shared/branding';
import { MAKER_PUSH } from '../maker-ipc/channels.js';
import { createLogger } from '../logger.js';
@@ -334,8 +335,6 @@ export async function runShellCommand(opts: RunCmdOptions): Promise<CmdExecution
* 在 bootstrap 阶段调一次, 把所有内置 desktop command 灌进 registry。
* 重复调会因为 registry.register 的去重保护抛错(开发期暴露问题)。
*/
-/** /goal clear 的别名(对齐 Claude Code /goal clear|stop|off|...)。 */
-const GOAL_CLEAR_ALIASES = new Set(['clear', 'stop', 'off', 'cancel', 'reset', 'none']);
export interface BuiltinDesktopCommandDeps {
/** null-safe 取 GoalController 单例(注册早于 startGoalController,invoke 时已就绪)。 */
@@ -657,9 +656,9 @@ export function registerBuiltinDesktopCommands(
broadcastDesktopCommand({ ...buildPayload('goal', ctx), error: 'goal-failed' });
return;
}
- const lower = arg.toLowerCase();
+ const command = parseGoalCommand(arg);
// /goal clear|stop|off|... → 清除目标。
- if (arg && GOAL_CLEAR_ALIASES.has(lower)) {
+ if (command.action === 'clear') {
try {
if (remoteGoal) await remoteGoal.clearGoal(sessionId);
else await controller!.clearGoal(sessionId);
@@ -674,7 +673,7 @@ export function registerBuiltinDesktopCommands(
return;
}
// /goal(无参)→ 等同点击「新建目标」:让 renderer 打开新建目标弹窗(此处已确保有 session)。
- if (!arg) {
+ if (command.action === 'open-dialog') {
broadcastDesktopCommand({ ...buildPayload('goal', ctx), goalAction: 'open-dialog' });
return;
}
diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
index debbd834ae..4b29ea17dd 100644
--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
@@ -107,11 +107,19 @@ function outcome(partial: Partial<TurnOutcome>): TurnOutcome {
}
describe('decideNextGoalState', () => {
- it('pauses when a non-goal (user) turn finishes', () => {
- const d = decideNextGoalState(BASE, outcome({ origin: 'other' }));
- expect(d.status).toBe('paused');
- expect(d.shouldFire).toBe(false);
- expect(d.turnsUsed).toBe(0); // user turn does not count toward goal turns
+ it('continues after ordinary input without consuming Goal counters', () => {
+ const d = decideNextGoalState(BASE, outcome({ origin: 'other', tokensThisTurn: 999,
+ verdict: { status: 'complete', reason: 'unrelated' } }));
+ expect(d).toMatchObject({ status: 'active', shouldFire: true, turnsUsed: 0, tokensUsed: 0, noProgressStreak: 0 });
+ });
+
+ it.each([
+ { errorMessage: 'boom', status: 'blocked' },
+ { errorMessage: 'AbortError: aborted', status: 'paused' },
+ { errorKind: 'usage_limit', status: 'usageLimited' },
+ ] as const)('keeps errors of ordinary turns on the existing stop path: $status', (error) => {
+ const d = decideNextGoalState(BASE, outcome({ origin: 'other', errored: true, ...error }));
+ expect(d).toMatchObject({ status: error.status, shouldFire: false, turnsUsed: 0, tokensUsed: 0 });
});
it('blocks on a terminal error', () => {
@@ -2101,7 +2109,7 @@ describe('GoalController', () => {
);
it.each(['same-turn steer', 'new turn'] as const)(
- 'still pauses for a new user message after Goal creation (%s)', async (delivery) => {
+ 'continues after a new user message after Goal creation (%s)', async (delivery) => {
await h.controller.pauseGoal('s1');
h.session.generation = 7;
h.session.running = true;
@@ -2110,9 +2118,9 @@ describe('GoalController', () => {
else h.session.generation = 8;
h.session.running = false;
h.session.emit({ type: 'done', data: {}, sessionTurnGeneration: h.session.generation });
- await vi.waitFor(async () => expect((await h.storage.get('s1'))?.status).toBe('paused'));
- expect((await h.storage.get('s1'))?.lastReason).toBe('paused: user sent a message during the goal');
- expect(h.session.sends).toHaveLength(0);
+ await vi.waitFor(() => expect(h.session.sends).toHaveLength(1));
+ expect(await h.storage.get('s1')).toMatchObject({ status: 'active', turnsUsed: 0, tokensUsed: 0 });
+ expect(h.session.sends).toHaveLength(1);
await h.controller.dispose();
},
);
@@ -2140,8 +2148,9 @@ describe('GoalController', () => {
} else {
await steer('s1', 'new direction');
expect(deliver).toHaveBeenCalledOnce();
- await vi.waitFor(async () => expect((await h.storage.get('s1'))?.status).toBe('paused'));
- expect(h.session.sends).toHaveLength(0);
+ await vi.waitFor(() => expect(h.session.sends).toHaveLength(1));
+ expect(await h.storage.get('s1')).toMatchObject({ status: 'active', turnsUsed: 0, tokensUsed: 0 });
+ expect(h.session.sends).toHaveLength(1);
}
await h.controller.dispose();
});
@@ -2159,8 +2168,9 @@ describe('GoalController', () => {
await startGoal(h);
h.session.running = false;
h.session.emit({ type: 'done', data: {}, sessionTurnGeneration: h.session.generation });
- await vi.waitFor(async () => expect((await h.storage.get('s1'))?.status).toBe('paused'));
- expect(h.session.sends).toHaveLength(0);
+ await vi.waitFor(() => expect(h.session.sends).toHaveLength(1));
+ expect(await h.storage.get('s1')).toMatchObject({ status: 'active', turnsUsed: 0, tokensUsed: 0 });
+ expect(h.session.sends).toHaveLength(1);
await h.controller.dispose();
},
);
@@ -2180,8 +2190,8 @@ describe('GoalController', () => {
await startGoal(local);
replacement.running = false;
replacement.emit({ type: 'done', data: {}, sessionTurnGeneration: 7 });
- await vi.waitFor(async () => expect((await local.storage.get('s1'))?.status).toBe('paused'));
- expect(replacement.sends).toHaveLength(0);
+ await vi.waitFor(() => expect(replacement.sends).toHaveLength(1));
+ expect((await local.storage.get('s1'))?.status).toBe('active');
await local.controller.dispose();
});
@@ -2950,14 +2960,8 @@ describe('GoalController', () => {
expect(local.session.sends).toHaveLength(1);
local.session.running = false;
local.session.emit({ type: 'done', data: {}, sessionTurnGeneration: local.session.generation });
- if (intervention === 'none') {
- await vi.waitFor(() => expect(local.session.sends).toHaveLength(2));
- expect(await local.storage.get('s1')).toMatchObject({ status: 'active', turnsUsed: 0 });
- } else {
- await vi.waitFor(async () => expect((await local.storage.get('s1'))?.status).toBe('paused'));
- expect(local.session.sends).toHaveLength(1);
- expect((await local.storage.get('s1'))?.lastReason).toBe('paused: user sent a message during the goal');
- }
+ await vi.waitFor(() => expect(local.session.sends).toHaveLength(2));
+ expect(await local.storage.get('s1')).toMatchObject({ status: 'active', turnsUsed: 0, tokensUsed: 0 });
await local.controller.dispose();
});
@@ -3663,12 +3667,80 @@ describe('GoalController', () => {
expect(h.session.sends.length).toBe(afterPause);
});
- it('pauses when a user-origin turn finishes mid-goal', async () => {
+ it('reports an input restoration failure without sending or silently staying active', async () => {
+ const local = makeController({ ensureInputReady: async () => { throw new Error('queue read failed'); } });
+ await expect(startGoal(local)).rejects.toThrow('queue read failed');
+ expect(await local.storage.get('s1')).toMatchObject({ status: 'blocked', lastReason: 'turn dispatch failed: unable to restore input queue' });
+ expect(local.session.sends).toHaveLength(0);
+ await local.controller.dispose();
+ });
+
+ it('yields to input arriving during the final pre-dispatch await, then sends once', async () => {
+ let inputBlocked = false;
+ let yielded = false;
+ const rollback = vi.fn();
+ const local = makeController({
+ ensureInputReady: async () => !inputBlocked, isInputBlocked: () => inputBlocked,
+ beforeDispatchUserTurn: async () => { if (!yielded) { inputBlocked = true; yielded = true; } }, onUndispatchedUserTurn: rollback,
+ });
+ await startGoal(local);
+ expect(local.session.sends).toHaveLength(0);
+ expect(rollback).toHaveBeenCalledOnce();
+ inputBlocked = false;
+ await local.controller.maybeContinueActiveGoal('s1');
+ await vi.waitFor(() => expect(local.session.sends).toHaveLength(1));
+ await local.controller.dispose();
+ });
+
+ it('continues after queued ordinary input and counts only the Goal turn', async () => {
+ let inputBlocked = false;
+ const local = makeController({ ensureInputReady: async () => !inputBlocked, isInputBlocked: () => inputBlocked });
+ await startGoal(local);
+ inputBlocked = true;
+ local.session.emitGoalTurn({ toolUse: true, tokens: 10 });
+ await tick();
+ expect(local.session.sends).toHaveLength(1);
+ local.session.emitGoalTurn({ origin: 'user', toolUse: true, tokens: 900 });
+ await tick();
+ expect(await local.storage.get('s1')).toMatchObject({ status: 'active', turnsUsed: 1, tokensUsed: 10 });
+ expect(local.session.sends).toHaveLength(1);
+ inputBlocked = false;
+ await Promise.all([local.controller.maybeContinueActiveGoal('s1'), local.controller.maybeContinueActiveGoal('s1')]);
+ await vi.waitFor(() => expect(local.session.sends).toHaveLength(2));
+ await tick();
+ expect(local.session.sends).toHaveLength(2);
+ await local.controller.dispose();
+ });
+
+ it.each(['pause', 'clear'] as const)('does not resume from a late queue release after %s', async action => {
+ let inputBlocked = true;
+ const ensureInputReady = vi.fn(async () => !inputBlocked);
+ const local = makeController({ ensureInputReady, isInputBlocked: () => inputBlocked });
+ await startGoal(local);
+ const attempts = ensureInputReady.mock.calls.length;
+ await tick();
+ expect(ensureInputReady).toHaveBeenCalledTimes(attempts); // no blocked-boundary polling
+ expect(local.session.sends).toHaveLength(0);
+ if (action === 'pause') await local.controller.pauseGoal('s1');
+ else await local.controller.clearGoal('s1');
+ inputBlocked = false;
+ await local.controller.maybeContinueActiveGoal('s1');
+ local.session.emit({ type: 'done', data: {}, turnOrigin: { kind: 'user' } });
+ await tick();
+ expect(local.session.sends).toHaveLength(0);
+ await local.controller.dispose();
+ });
+
+ it('ignores background output and terminal tails instead of treating them as input or Goal work', async () => {
await startGoal(h);
- h.session.emitGoalTurn({ origin: 'user', toolUse: true, verdictJson: '' });
+ h.session.emit({ type: 'text', turnScope: 'background', data: { text: '{"goal_status":"complete"}', isFinal: true } });
+ h.session.emit({ type: 'done', turnScope: 'background', data: {} });
await tick();
- expect((await h.storage.get('s1'))?.status).toBe('paused');
expect(h.session.sends).toHaveLength(1);
+ expect(h.completions).toHaveLength(0);
+ h.session.emitGoalTurn({ toolUse: true, tokens: 15 });
+ await vi.waitFor(() => expect(h.session.sends).toHaveLength(2));
+ expect(await h.storage.get('s1')).toMatchObject({ status: 'active', turnsUsed: 1, tokensUsed: 15 });
});
// ── applyClarificationAnswer(Option B:答完卡片即时改写目标)──
diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts
index 9f1e81823e..d4b853673f 100644
--- a/apps/desktop/src/main/goal-host/controller.ts
+++ b/apps/desktop/src/main/goal-host/controller.ts
@@ -9,7 +9,7 @@
* "裁决/续跑/止损"的确定性逻辑全在代码里(规则 9):
* - 续跑闸门:status=active ∧ 会话空闲 ∧ 未在 firing ∧ 守卫全过 才发下一轮
* - 防失控守卫(**全部 per-goal 可配置、可空,仅设了上限才生效**):token 预算 / 最大轮数
- * / 空轮抑制 / complete 自停 / blocked(模型自报 / 出错)/ 用户打断暂停 / in-flight 去重 + 防抖
+ * / 空轮抑制 / complete 自停 / blocked(模型自报 / 出错)/ 用户显式暂停 / in-flight 去重 + 防抖
* 交给模型的是"目标算不算完成 / 是否应 blocked"的语义判断;上限的确定 / 激活 /
* 持久化全代码驱动。
*/
@@ -223,7 +223,7 @@ export interface GoalCounters {
* 纯函数:给定上一状态 + 本轮结果 → 下一状态 + 是否续跑。无 IO、无副作用。
*
* 停止信号:
- * - 用户打断(origin 'other')→ paused
+ * - 普通输入(origin 'other')结束 → 继续目标,不计入目标轮数/用量
* - 终止型 error → paused(用户 Stop)/ blocked(真出错)
* - 模型自报 complete → complete(终态)/ blocked → blocked
* - **仅当设了对应上限**:token 撞预算 / 轮数撞 maxTurns → budgetLimited(终态);
@@ -232,20 +232,10 @@ export interface GoalCounters {
* 目标会一直续到 complete/blocked/用户停。
*/
export function decideNextGoalState(prev: GoalCounters, outcome: TurnOutcome): GoalDecision {
- // 用户/其它来源在 goal active 期间发起的 turn → 暂停,不计入 goal 计数。
- if (outcome.origin === 'other') {
- return {
- status: 'paused',
- lastReason: 'paused: user sent a message during the goal',
- turnsUsed: prev.turnsUsed,
- tokensUsed: prev.tokensUsed,
- noProgressStreak: prev.noProgressStreak,
- shouldFire: false,
- };
- }
-
- const turnsUsed = prev.turnsUsed + 1;
- const tokensUsed = prev.tokensUsed + Math.max(0, outcome.tokensThisTurn);
+ // Ordinary input keeps its real origin and does not consume Goal counters.
+ const goalTurn = outcome.origin === 'goal';
+ const turnsUsed = prev.turnsUsed + (goalTurn ? 1 : 0);
+ const tokensUsed = prev.tokensUsed + (goalTurn ? Math.max(0, outcome.tokensThisTurn) : 0);
// 终止型 error:区分"用户 Stop(abort)"与"真出错"。
// - 用户 Stop → paused(干净暂停,语义对);
@@ -281,6 +271,13 @@ export function decideNextGoalState(prev: GoalCounters, outcome: TurnOutcome): G
};
}
+ if (!goalTurn) {
+ return {
+ status: 'active', lastReason: null, turnsUsed, tokensUsed,
+ noProgressStreak: prev.noProgressStreak, shouldFire: true,
+ };
+ }
+
// 模型自报完成 → 终态,自停。
if (outcome.verdict?.status === 'complete') {
return {
@@ -481,7 +478,7 @@ export class GoalController {
this.now = deps.now ?? (() => Date.now());
this.debounceMs = deps.continuationDebounceMs ?? DEFAULT_DEBOUNCE_MS;
this.unsubscribeIntervention = onUiSessionIntervention((sessionId) => {
- // 新消息(包括同一轮内的插话)撤销旧轮豁免,保留原有用户打断语义。
+ // 新消息(包括同轮插话)撤销旧轮豁免;按真实来源结算后继续目标。
const turn = this.turns.get(sessionId);
if (turn) turn.precedingTurn = null;
});
@@ -1791,7 +1788,7 @@ export class GoalController {
}
private onEvent(sessionId: string, event: AgentEvent): void {
- if (this.disposed) return;
+ if (this.disposed || event.turnScope === 'background') return;
let turn = this.turns.get(sessionId);
if (!turn) {
turn = freshTurn();
@@ -2434,6 +2431,20 @@ export class GoalController {
return;
}
if (this.firing.has(sessionId)) return;
+ // FIFO, approvals, recovery and explicit input holds own dispatch priority.
+ // Queue projections/terminal observers wake us when that boundary releases.
+ try {
+ if (this.deps.ensureInputReady && !await this.deps.ensureInputReady(sessionId)) return;
+ } catch (error) {
+ if (!isCurrentLifecycle()) return;
+ const persisted = await this.blockDispatchFailure(
+ sessionId, lifecycleBoundary,
+ 'turn dispatch failed: unable to restore input queue', isCurrentLifecycle,
+ );
+ if (opts?.throwOnRestoreFailure || (!persisted && opts?.throwOnUnpersistedRestoreFailure)) throw error;
+ return;
+ }
+ if (!isCurrentLifecycle()) return;
// 首轮 vs 续轮由 state 派生(turnsUsed===0 = 首轮尚未真正跑完),不再由调用方指定。
// 关键:首轮被 busy 跳过 / 被暂停后再发时,只要首轮还没跑过就仍按 first 发,否则首轮
// 特有的"质量自检 + AskUserQuestion"约定(buildFirstTurnDirective)会丢,目标直接进
@@ -2443,8 +2454,7 @@ export class GoalController {
// 会话忙 → 重排一次防抖重试,别丢这一轮(而非直接放弃)。
// 首轮尤其关键:新建会话后 agent 可能仍在 spawn/init,isTurnRunning() 瞬时为真;旧实现
// 直接丢弃首轮 → 目标永久卡在 active/0 轮、首轮指令从未下发(用户侧表现为"没有交互卡片、
- // 目标不动")。重试期间若真有用户 turn 抢跑,其收尾会把目标置 paused,届时重试见
- // status≠active 自然停,不会空转。
+ // 目标不动")。重试期间若有普通输入抢跑,先完成输入,再由终态通知续跑目标。
this.deps.logger.info('[goal] session busy, retry fire soon', { sessionId, kind });
this.scheduleContinuation(sessionId);
return;
@@ -2477,6 +2487,7 @@ export class GoalController {
if (!isCurrentLifecycle()) return;
if (!session) throw new GoalSessionRestoreError();
restoringSession = false;
+ if (this.deps.isInputBlocked?.(sessionId)) return;
// deferred switch 可能刚把 live session 换成目标引擎的新对象;本会话若有 goal
// listener,必须迁到新 session,否则这轮 turn 的 done/error 事件进不了 finalizeTurn,
// 目标卡死在 active(reviewer P1)。attachListener 按 session 身份判等,未换则 no-op;
@@ -2505,7 +2516,7 @@ export class GoalController {
// 交接注入自己接——切换后 goal 循环的下一轮 directive 同样要带交接上下文
// (2026-07-20 审计)。
const pendingHandoff = await agentHandoffPending.peek(sessionId);
- if (!isCurrentDispatch()) {
+ if (!isCurrentDispatch() || this.deps.isInputBlocked?.(sessionId)) {
if (baselineStarted) {
this.deps.onUndispatchedUserTurn?.(sessionId);
baselineStarted = false;
@@ -2623,7 +2634,7 @@ export class GoalController {
if (!isCurrentFailure()) return;
if ((e as { code?: unknown } | null)?.code === 'SESSION_RUNNING') {
- // dispatch 前的窄 race;现有 turn 的终态会暂停 Goal,空闲检查则负责稍后重试。
+ // dispatch 前的窄 race;先处理当前输入;终态与输入空闲通知负责稍后续跑。
this.scheduleContinuation(sessionId);
return;
}
diff --git a/apps/desktop/src/main/goal-host/index.ts b/apps/desktop/src/main/goal-host/index.ts
index e3f8883410..05401b8e5c 100644
--- a/apps/desktop/src/main/goal-host/index.ts
+++ b/apps/desktop/src/main/goal-host/index.ts
@@ -14,6 +14,8 @@ import { createLogger } from '../logger.js';
import {
acquirePendingAgentSwitchForDirectSend,
isSessionInTurn,
+ ensureGoalInputReady,
+ isGoalInputBlocked,
resolveSessionRuntimeRoute,
stopActiveGoalTurnForClear,
} from '../maker-ipc/register.js';
@@ -64,6 +66,8 @@ export function startGoalController(deps: StartGoalControllerDeps): GoalControll
}),
acquirePendingAgentSwitch: acquirePendingAgentSwitchForDirectSend,
isSessionInTurn,
+ ensureInputReady: ensureGoalInputReady,
+ isInputBlocked: isGoalInputBlocked,
stopActiveGoalTurn: stopActiveGoalTurnForClear,
beforeDispatchUserTurn: deps.beforeDispatchUserTurn,
onUndispatchedUserTurn: deps.onUndispatchedUserTurn,
diff --git a/apps/desktop/src/main/goal-host/types.ts b/apps/desktop/src/main/goal-host/types.ts
index d74b393e3d..706a9c4d50 100644
--- a/apps/desktop/src/main/goal-host/types.ts
+++ b/apps/desktop/src/main/goal-host/types.ts
@@ -17,7 +17,7 @@ import type {
/**
* 目标状态机:
* - active 续跑中
- * - paused 用户打断 / 用户暂停 / rewind / 连续空轮触顶 —— 用户可恢复
+ * - paused 用户暂停 / rewind / 连续空轮触顶 —— 用户可恢复
* - blocked 需人工(审批 / 模型自报 blocked / turn 出错)—— 用户处理后可恢复
* - complete 达成(终态)
* - budgetLimited 撞 token 预算或轮数上限(**仅当该目标设了对应上限时才可能**;终态)
@@ -187,6 +187,9 @@ export interface GoalControllerDeps {
acquirePendingAgentSwitch?: (sessionId: string) => Promise<() => void>;
/** ← maker-ipc/register.isSessionInTurn(main 侧 turn 活跃跟踪)。 */
isSessionInTurn(sessionId: string): boolean;
+ /** Restore the existing input queue, then yield to its FIFO/locks/recovery. */
+ ensureInputReady?: (sessionId: string) => Promise<boolean>;
+ isInputBlocked?: (sessionId: string) => boolean;
/**
* 清除目标时中断由 GoalController 发起的当前 turn。生产环境接到 input coordinator
* 的 Stop 边界,以便 vendor abort、输入队列和迟到终态事件一起收口。
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 99c60bf1b1..0231193068 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -14157,3 +14157,36 @@ describe('provider group computer switch hold', () => {
expect(latestProjection(h.projections).autoResumePending).toBeUndefined();
});
});
+
+
+describe('Goal input boundary', () => {
+ const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8').replace(/\r\n/g, '\n');
+ const boundary = source.slice(source.indexOf('export function isGoalInputBlocked'), source.indexOf('export function isSessionInTurn'));
+ const compiled = transpileModule(boundary.replace(/export /g, '') + '\nreturn { isGoalInputBlocked, ensureGoalInputReady };', {
+ compilerOptions: { target: ScriptTarget.ES2022 },
+ }).outputText;
+ it('uses the actual coordinator FIFO, approval locks, Stop and restore boundaries', async () => {
+ const h = createHarness();
+ let pendingInteraction = false;
+ const gate = new Function('agentInputCoordinatorHolder', 'hasPendingAgentInteractionForSession', compiled)(
+ h.coordinator, () => pendingInteraction,
+ );
+ expect(await gate.ensureGoalInputReady('goal-task')).toBe(true);
+ h.coordinator.setInteractionLock('goal-task', 'approval', true);
+ h.coordinator.enqueue('goal-task', makeItem('user-input', 'supplement'));
+ expect(await gate.ensureGoalInputReady('goal-task')).toBe(false);
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+ h.coordinator.setInteractionLock('goal-task', 'approval', false);
+ await vi.waitFor(() => expect(h.sendToAgent).toHaveBeenCalledOnce());
+ expect(gate.isGoalInputBlocked('goal-task')).toBe(true);
+ h.coordinator.stop('goal-task');
+ expect(await gate.ensureGoalInputReady('goal-task')).toBe(false);
+ h.setRunning(false);
+ h.coordinator.resume('goal-task');
+ await vi.waitFor(async () => expect(await gate.ensureGoalInputReady('goal-task')).toBe(true));
+ pendingInteraction = true;
+ expect(await gate.ensureGoalInputReady('goal-task')).toBe(false);
+ pendingInteraction = false;
+ expect(await gate.ensureGoalInputReady('goal-task')).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 64af7fd571..9f20f195fc 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4088,6 +4088,22 @@ export function createAutomationUserTurnGitBaselineHooks(): AutomationUserTurnGi
};
}
+/** Goal direct dispatch must yield to the same input boundary as ordinary messages. */
+export function isGoalInputBlocked(sessionId: string): boolean {
+ return !agentInputCoordinatorHolder
+ || agentInputCoordinatorHolder.shouldQueueNewTurn(sessionId)
+ || hasPendingAgentInteractionForSession(sessionId);
+}
+
+export async function ensureGoalInputReady(sessionId: string): Promise<boolean> {
+ const coordinator = agentInputCoordinatorHolder;
+ if (!coordinator) return false;
+ await coordinator.ensureQueueRestored(sessionId);
+ return coordinator === agentInputCoordinatorHolder
+ && coordinator.isQueueRestored(sessionId)
+ && !isGoalInputBlocked(sessionId);
+}
+
export function isSessionInTurn(sessionId: string): boolean {
return sessionTurnActivityTracker.isSessionInTurn(sessionId);
}
@@ -17606,6 +17622,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}),
emitProjection: (projection) => {
broadcastToAllWindows(MAKER_PUSH.INPUT_PROJECTION, projection);
+ if (!isGoalInputBlocked(projection.sessionId)) notifyGoalIdleAfterTurnSettled(projection.sessionId);
},
// 意识拦截钩(订阅槽①):派发/落库前问已装钩子意识;fail-open 由
// screenGhostUserMessage 内部收敛,快路径(无钩子意识)零开销。
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index e61f87fbe4..a175652978 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -697,6 +697,8 @@ import {
import {
buildLearnCardData,
buildLearnStartRequest,
+ executeMobileGoalCommand,
+ mergeMobileGoalCommand,
filterMobileDesktopCommands,
parseMobileDesktopCommand,
} from '@/session/desktopSlashCommands';
@@ -6287,15 +6289,58 @@ export default function SessionScreen() {
const willHaveAttachments = attachmentsRef.current.length > 0 || uploadsInFlight > 0;
const earlyLocalCommand = willHaveAttachments ? null : parseMobileLocalSystemCommand(body);
const pendingSkillAtSend = pendingSkillSelectionRef.current;
- const parsedDesktopCommandAtSend = willHaveAttachments
- ? null
- : parseMobileDesktopCommand(body, commandsAtSend);
+ const parsedDesktopCommandAtSend = parseMobileDesktopCommand(body, commandsAtSend);
+ const eligibleDesktopCommand = willHaveAttachments && parsedDesktopCommandAtSend?.name !== 'goal'
+ ? null : parsedDesktopCommandAtSend;
const earlyDesktopCommand =
- parsedDesktopCommandAtSend
+ eligibleDesktopCommand
&& pendingSkillAtSend?.sid === sessionId
- && pendingSkillAtSend.name === parsedDesktopCommandAtSend.name
+ && pendingSkillAtSend.name === eligibleDesktopCommand.name
? null
- : parsedDesktopCommandAtSend;
+ : eligibleDesktopCommand;
+ if (outboxEligible && earlyDesktopCommand?.name === 'goal') {
+ if (willHaveAttachments) {
+ setError(t('session.screen.goalCommandAttachments'));
+ return;
+ }
+ if (isRemoteSessionMissing(readSessionRowNow())) {
+ setError(t('session.screen.commandWaitsForSession'));
+ return;
+ }
+ if (goalBusy) return;
+ const commandOwner = getMobileAuthOwner();
+ const commandScopeAlive = () => isMobileAuthOwnerCurrent(commandOwner)
+ && outboxSessionAliveRef.current === sessionId && deviceIdRef.current === deviceId;
+ setGoalBusy(true);
+ setGoalError(null);
+ try {
+ const result = await executeMobileGoalCommand(earlyDesktopCommand.args, sessionId, maker.goal);
+ if (!commandScopeAlive()) return;
+ if (result.status !== undefined) remoteSessionStore.setGoalStatus(sessionId, result.status);
+ if (result.command.action === 'set') {
+ setGoalRestore(null);
+ router.setParams({ goalObjective: undefined, goalLimits: undefined, goalError: undefined });
+ }
+ if (result.command.action === 'open-dialog') {
+ setContextSheetView('goal');
+ setContextSheetOpen(true);
+ }
+ // Consume only the submitted command; keep quotes and any newer input.
+ if (composerDocumentsEqual(composerDocumentRef.current, documentAtSend)) {
+ applyComposerDocument(normalizeComposerDocument({
+ version: 1, nodes: documentAtSend.nodes.filter((node) => node.type === 'quote'),
+ }));
+ }
+ } catch (err) {
+ if (!commandScopeAlive()) return;
+ const message = humanizeRemoteError(err);
+ setGoalError(message);
+ setError(message);
+ } finally {
+ if (commandScopeAlive()) setGoalBusy(false);
+ }
+ return;
+ }
// A known hidden model requires an explicit choice before consuming the draft or enqueueing.
const sessionAtSend = readSessionRowNow() ?? currentSession;
const intentAtSend = sessionAtSend.agentSwitchIntent;
@@ -6953,11 +6998,10 @@ export default function SessionScreen() {
}
} catch (err) {
setError(formatRemoteError(err));
+ }
} finally {
sendInFlightRef.current = false;
setSending(false);
- }
- } finally {
messageWorkLease.release();
}
}
@@ -8140,14 +8184,17 @@ export default function SessionScreen() {
try {
const status = await maker.goal.getStatus(sessionId);
if (!cancelled) remoteSessionStore.setGoalStatus(sessionId, status ?? null);
- } catch {
- // 老被控端没有 goal 通道(CHANNEL_NOT_ALLOWED):保持未知,提交时再显式报错。
+ } catch (err) {
+ // Ordinary status refresh stays quiet; an explicitly opened Goal panel reports capability/connection errors.
+ if (!cancelled && contextSheetOpen && contextSheetView === 'goal') {
+ setGoalError(humanizeRemoteError(err));
+ }
}
})();
return () => {
cancelled = true;
};
- }, [appStateActive, connectionEpoch, contextSheetOpen, deviceId, maker, remoteHistoryAvailable, sessionId]));
+ }, [appStateActive, connectionEpoch, contextSheetOpen, contextSheetView, deviceId, maker, remoteHistoryAvailable, sessionId]));
// 暂停 / 继续 / 结束目标:先乐观切本地状态镜像(面板当帧反馈,不等往返),
// RPC 后台;成功回读权威收敛(既有语义)。失败时报错并还原:优先回读权威状态,
// 回读也失败(离线 / 超时,与 action 同因高概率连败)则还原到乐观前的快照——
@@ -8167,7 +8214,7 @@ export default function SessionScreen() {
const status = await maker.goal.getStatus(sessionId).catch(() => null);
remoteSessionStore.setGoalStatus(sessionId, status ?? null);
} catch (err) {
- setGoalError(formatRemoteError(err));
+ setGoalError(humanizeRemoteError(err));
if (optimistic !== undefined) {
const status = await maker.goal.getStatus(sessionId).catch(() => undefined);
if (status !== undefined) {
@@ -8218,7 +8265,7 @@ export default function SessionScreen() {
goalError: undefined,
});
} catch (err) {
- setGoalError(formatRemoteError(err));
+ setGoalError(humanizeRemoteError(err));
} finally {
setGoalBusy(false);
}
@@ -11000,9 +11047,9 @@ function SessionComposerPalette({
const pluginPaletteVisible = useMemo(() => detectComposerPluginTrigger(draft) !== null, [draft]);
const visibleSlashCommands = useMemo(
() => canUseComposer && composerTrigger.kind === 'slash'
- ? filterSlashCommands(mergeMobileLocalSlashCommands(slashCommands), composerTrigger.query, 5)
+ ? filterSlashCommands(mergeMobileLocalSlashCommands(mergeMobileGoalCommand(slashCommands, t('session.common.goalMode'))), composerTrigger.query, 5)
: [],
- [canUseComposer, composerTrigger, slashCommands],
+ [canUseComposer, composerTrigger, slashCommands, t],
);
const visibleAtResources = useMemo(
() => canUseComposer && composerTrigger.kind === 'at'
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 53c1eba23b..8175d1b423 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -1,3 +1,5 @@
+import { parseGoalCommand } from '@cindy/maker-shared/goal-command';
+import { mergeMobileGoalCommand, parseMobileDesktopCommand } from '@/session/desktopSlashCommands';
import { modelNeedsReselection } from '@/session/modelReselection';
import { completePrecreatedWorktreeRecovery } from '@/session/completePrecreatedWorktreeRecovery';
import { outboxCreationRetryIdentity } from '@/session/cancelledCreationDraft';
@@ -993,6 +995,10 @@ export default function NewRemoteSessionScreen() {
incomingShareBatch,
isShareTargetFocused,
]);
+ const pendingGoalSkillRef = useRef<string | null>(null);
+ useEffect(() => {
+ pendingGoalSkillRef.current = null;
+ }, [selectedDeviceId, draft.agentKind, draft.workspaceKind, draft.workingDir]);
const [slashCommands, setSlashCommands] = useState<MobileSlashCommand[]>([]);
const [slashPaletteLoading, setSlashPaletteLoading] = useState(false);
const [slashPaletteError, setSlashPaletteError] = useState<string | null>(null);
@@ -2143,9 +2149,9 @@ export default function NewRemoteSessionScreen() {
const composerAtQuery = composerTrigger.kind === 'at' ? composerTrigger.query : '';
const visibleSlashCommands = useMemo(
() => composerTrigger.kind === 'slash'
- ? filterSlashCommands(slashCommands, composerTrigger.query, 5)
+ ? filterSlashCommands(mergeMobileGoalCommand(slashCommands, t('session.common.goalMode')), composerTrigger.query, 5)
: [],
- [composerTrigger, slashCommands],
+ [composerTrigger, slashCommands, t],
);
const visibleAtResources = useMemo(
() => composerTrigger.kind === 'at'
@@ -2571,6 +2577,7 @@ export default function NewRemoteSessionScreen() {
return;
}
const seq = ++slashLoadSeqRef.current;
+ pendingGoalSkillRef.current = null;
const agentKind = draft.agentKind;
const workingDir = draft.workspaceKind === 'project' ? draft.workingDir.trim() : '';
const paletteCacheKey = buildComposerPaletteCacheKey(selectedDeviceId, agentKind, workingDir);
@@ -4459,6 +4466,7 @@ export default function NewRemoteSessionScreen() {
const selectSlashCommand = useCallback((command: MobileSlashCommand) => {
const current = firstMessageRef.current;
+ pendingGoalSkillRef.current = command.kind === 'agent-skill' ? command.name : null;
const next = insertSlashCommand(current, detectComposerTrigger(current), command);
if (next === current) return;
setFirstMessageDraft(next);
@@ -4694,7 +4702,7 @@ export default function NewRemoteSessionScreen() {
patchDraft({ permissionMode: remembered && remembered !== 'plan' ? remembered : fallback });
}, [draft.permissionMode, patchDraft, planModeCapability, runtimeOptions.permissionOptions]);
- const create = useCallback(async () => {
+ const createMessageSession = useCallback(async () => {
if (leaveForeignOutboxRecovery()) return;
if (
creatingRef.current
@@ -5386,8 +5394,8 @@ export default function NewRemoteSessionScreen() {
// 目标模式建会话(对齐桌面 handleCreateGoal):createSession → goal.set(被控端落
// 目标消息 + 自动开跑第一轮)→ 跳转会话页。不走普通首条消息发送,目标文案即对话起点;
- // composer 附件不随目标带入(与桌面一致)。goal.set 失败时报错留在面板,会话已创建,
- // 用户可进会话重设目标,重试本表单会新建会话。
+ // composer 附件不随目标带入(与桌面一致)。goal.set 失败后进入同一任务恢复目标表单,
+ // 不重放写入、不重复创建;成功交接后保留创建锁直到页面卸载。
const createGoalSession = useCallback(async (input: { objective: string; limits?: MobileGoalLimitsInput }) => {
if (leaveForeignOutboxRecovery()) return;
if (creatingRef.current || goalBusy) return;
@@ -5426,6 +5434,7 @@ export default function NewRemoteSessionScreen() {
setCreating(true);
setGoalBusy(true);
setGoalError(null);
+ let handedOff = false;
let releasePrecreatedRegistration: (() => void) | null = null;
let precreatedWorktree: {
sessionId: string;
@@ -5991,7 +6000,7 @@ export default function NewRemoteSessionScreen() {
try {
await maker.goal.set({ sessionId: result.sessionId, objective: input.objective, ...(input.limits ? { limits: input.limits } : {}) });
} catch (goalErr) {
- goalSetError = formatRemoteError(goalErr);
+ goalSetError = humanizeRemoteError(goalErr);
}
// ── settle 段(可降级):本地同步/UI,owner + 设备检查恢复正常语义 ──
// 设备复核(greptile P1):goal.set 等待期间同账号可能切换设备——owner 检查
@@ -6060,6 +6069,7 @@ export default function NewRemoteSessionScreen() {
} : {}),
},
});
+ handedOff = true;
} catch (err) {
if (!isCurrentOwner()) return;
// 只有 session 尚未认领 worktree 时才补偿回收;Goal 已建成后 goal.set
@@ -6081,7 +6091,7 @@ export default function NewRemoteSessionScreen() {
sessionClaimed = true;
}
if (sessionClaimed) {
- setGoalError(formatRemoteError(err));
+ setGoalError(humanizeRemoteError(err));
return;
}
if (sessionCreateStarted) {
@@ -6117,7 +6127,7 @@ export default function NewRemoteSessionScreen() {
return;
}
}
- setGoalError(formatRemoteError(err));
+ setGoalError(humanizeRemoteError(err));
} finally {
if (
isCurrentOwner()
@@ -6136,9 +6146,11 @@ export default function NewRemoteSessionScreen() {
}).catch(() => undefined);
}
releasePrecreatedRegistration?.();
- creatingRef.current = false;
- setCreating(false);
- setGoalBusy(false);
+ if (!handedOff) {
+ creatingRef.current = false;
+ setCreating(false);
+ setGoalBusy(false);
+ }
}
}, [
agentAuthVerdict,
@@ -6175,6 +6187,33 @@ export default function NewRemoteSessionScreen() {
resolveWorktreeCreateErrorKey,
]);
+ const create = useCallback(async () => {
+ const parsed = parseMobileDesktopCommand(firstMessageRef.current, slashCommands);
+ if (parsed?.name !== 'goal' || pendingGoalSkillRef.current === 'goal') {
+ await createMessageSession();
+ return;
+ }
+ if (creatingRef.current || voiceIsBusy) return;
+ if (attachmentsRef.current.length > 0 || pendingUploads.length > 0) {
+ setError(t('session.screen.goalCommandAttachments'));
+ return;
+ }
+ const command = parseGoalCommand(parsed.args);
+ if (command.action === 'clear') {
+ setError(t('session.new.goalCommandNeedsSession'));
+ return;
+ }
+ setGoalError(null);
+ setContextSheetView('goal');
+ setContextSheetOpen(true);
+ if (command.action === 'set') await createGoalSession({ objective: command.objective });
+ }, [attachmentsRef, createGoalSession, createMessageSession, pendingUploads.length, slashCommands, t, voiceIsBusy]);
+
+ const goalDraftCommand = parseMobileDesktopCommand(draft.firstMessage, slashCommands);
+ const goalDraftObjective = goalDraftCommand?.name === 'goal' && pendingGoalSkillRef.current !== 'goal'
+ ? goalDraftCommand.args
+ : draft.firstMessage.trim();
+
return (
<SafeAreaView edges={composerDock.enabled ? ['left', 'right'] : simpleScreenSafeAreaEdges()} style={styles.safeArea} testID="newSession.screen">
{Platform.OS === 'ios' ? (
@@ -7004,7 +7043,7 @@ export default function NewRemoteSessionScreen() {
? t(worktreeControlCaptionKey)
: undefined}
error={goalError}
- initial={draft.firstMessage.trim() ? { objective: draft.firstMessage.trim() } : undefined}
+ initial={goalDraftObjective ? { objective: goalDraftObjective } : undefined}
onSetGoal={(input) => void createGoalSession(input)}
testID="newSession.contextSheetGoalView"
/>
diff --git a/apps/mobile/src/__tests__/desktopSlashCommands.test.ts b/apps/mobile/src/__tests__/desktopSlashCommands.test.ts
index d9381f9b21..28f8fbfb28 100644
--- a/apps/mobile/src/__tests__/desktopSlashCommands.test.ts
+++ b/apps/mobile/src/__tests__/desktopSlashCommands.test.ts
@@ -1,8 +1,10 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
MOBILE_SUPPORTED_DESKTOP_COMMANDS,
buildLearnCardData,
buildLearnStartRequest,
+ executeMobileGoalCommand,
+ mergeMobileGoalCommand,
filterMobileDesktopCommands,
parseMobileDesktopCommand,
} from '@/session/desktopSlashCommands';
@@ -53,8 +55,8 @@ describe('parseMobileDesktopCommand', () => {
expect(parseMobileDesktopCommand('文本里提到 /learn 不算')).toBeNull();
});
- it('白名单集合当前只含 learn(新增命令需同步实现分流)', () => {
- expect([...MOBILE_SUPPORTED_DESKTOP_COMMANDS]).toEqual(['learn']);
+ it('白名单集合包含已实现的 learn 和 goal', () => {
+ expect([...MOBILE_SUPPORTED_DESKTOP_COMMANDS]).toEqual(['learn', 'goal']);
});
});
@@ -115,3 +117,57 @@ describe('buildLearnCardData', () => {
.toEqual({ error: 'learn-failed', detail: '[NOT_CONNECTED] not online' });
});
});
+
+
+describe('mobile /goal business routing', () => {
+ const goalApi = () => ({ set: vi.fn().mockResolvedValue(undefined), clear: vi.fn().mockResolvedValue(undefined),
+ getStatus: vi.fn().mockResolvedValue({ objective: '目标', status: 'active' }),
+ pause: vi.fn(), resume: vi.fn(), update: vi.fn() });
+
+ it('shows Goal without loading the roster, and preserves a same-name Skill', () => {
+ expect(mergeMobileGoalCommand([], 'Goal Mode')).toEqual([{ kind: 'desktop', name: 'goal', description: 'Goal Mode' }]);
+ const skill = { kind: 'agent-skill', name: 'goal', description: 'skill' } as MobileSlashCommand;
+ expect(mergeMobileGoalCommand([skill], 'Goal Mode')).toEqual([skill]);
+ expect(parseMobileDesktopCommand('/goal target', [skill])).toBeNull();
+ expect(parseMobileDesktopCommand('/goal target')).toEqual({ name: 'goal', args: 'target' });
+ expect(filterMobileDesktopCommands([{ kind: 'desktop', name: 'goal', description: 'Goal Mode' }])).toHaveLength(1);
+ });
+
+ it('bare /goal opens the existing panel without setting a goal', async () => {
+ const api = goalApi();
+ expect(await executeMobileGoalCommand('', 's1', api)).toMatchObject({ command: { action: 'open-dialog' } });
+ expect(api.getStatus).toHaveBeenCalledExactlyOnceWith('s1');
+ expect(api.set).not.toHaveBeenCalled();
+ expect(api.clear).not.toHaveBeenCalled();
+ });
+
+ it('sets the actual task goal once and reads authoritative status', async () => {
+ const api = goalApi();
+ const result = await executeMobileGoalCommand(' 目标 ', 'existing-task', api);
+ expect(api.set).toHaveBeenCalledExactlyOnceWith({ sessionId: 'existing-task', objective: '目标' });
+ expect(api.getStatus).toHaveBeenCalledWith('existing-task');
+ expect(result.status).toMatchObject({ objective: '目标', status: 'active' });
+ });
+
+ it.each(['clear', 'STOP', 'off', 'cancel', 'reset', 'none'])('clears for desktop alias %s', async args => {
+ const api = goalApi();
+ await executeMobileGoalCommand(args, 's1', api);
+ expect(api.clear).toHaveBeenCalledExactlyOnceWith('s1');
+ expect(api.set).not.toHaveBeenCalled();
+ });
+
+ it('propagates unsupported/connection errors, never falls through to a message', async () => {
+ const api = goalApi();
+ api.set.mockRejectedValue(new Error('[CHANNEL_NOT_ALLOWED] old host'));
+ await expect(executeMobileGoalCommand('目标', 's1', api)).rejects.toThrow('CHANNEL_NOT_ALLOWED');
+ expect(api.set).toHaveBeenCalledOnce();
+ expect(api.getStatus).not.toHaveBeenCalled();
+ });
+
+ it('does not replay goal.set when only status refresh fails', async () => {
+ const api = goalApi();
+ api.getStatus.mockRejectedValue(new Error('offline'));
+ expect((await executeMobileGoalCommand('目标', 's1', api)).status).toBeUndefined();
+ expect(api.set).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/mobile/src/__tests__/mobileGoalCommands.test.ts b/apps/mobile/src/__tests__/mobileGoalCommands.test.ts
new file mode 100644
index 0000000000..fc7d3df4c7
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileGoalCommands.test.ts
@@ -0,0 +1,223 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+import { parseGoalCommand } from '@cindy/maker-shared/goal-command';
+import { executeMobileGoalCommand, parseMobileDesktopCommand } from '@/session/desktopSlashCommands';
+import { humanizeRemoteError } from '@/device-link/remoteStatus';
+import { composerDocumentProjectedText, emptyComposerDocument, normalizeComposerDocument, reconcileComposerProjectedText, serializeComposerDocument, textComposerDocument } from '@/session/composerDocument';
+
+// Execute the actual page callbacks, excluding unrelated native/network UI.
+function callback(path: string, name: string) {
+ const source = ts.createSourceFile(path, readFileSync(resolve(process.cwd(), path), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ let body = '';
+ function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === name && node.initializer && ts.isCallExpression(node.initializer)) {
+ body = node.initializer.arguments[0].getText(source);
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ if (!body) throw new Error(`Missing page callback ${name}`);
+ return (bindings: Record<string, unknown>) => new Function(...Object.keys(bindings), ts.transpileModule(`return (${body});`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText)(...Object.values(bindings));
+}
+const newCreate = callback('app/sessions/new.tsx', 'create');
+const goalCreate = callback('app/sessions/new.tsx', 'createGoalSession');
+const sessionSource = ts.createSourceFile('session.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+let sendSource = '';
+function findSend(node: ts.Node) {
+ if (ts.isFunctionDeclaration(node) && node.name?.text === 'send') sendSource = node.getText(sessionSource);
+ ts.forEachChild(node, findSend);
+}
+findSend(sessionSource);
+if (!sendSource) throw new Error('Missing complete SessionScreen.send entry');
+const compiledExisting = ts.transpileModule(`${sendSource}\nreturn send;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+
+function newHarness(text = '/goal target') {
+ const noop = vi.fn();
+ const draft = { agentKind: 'pi', model: 'test-model', providerId: 'test-provider', workspaceKind: 'dialogue', workingDir: '', firstMessage: text, agentDeviceId: 'agent-device' };
+ const bindings = {
+ parseGoalCommand, parseMobileDesktopCommand,
+ firstMessageRef: { current: text }, slashCommands: [], pendingGoalSkillRef: { current: null as string | null },
+ creatingRef: { current: false }, voiceIsBusy: false, attachmentsRef: { current: [] as unknown[] }, pendingUploads: [] as unknown[],
+ createMessageSession: vi.fn(), createGoalSession: vi.fn(),
+ setError: vi.fn(), setGoalError: vi.fn(), setContextSheetView: vi.fn(), setContextSheetOpen: vi.fn(), t: (key: string) => key,
+ leaveForeignOutboxRecovery: () => false, goalBusy: false, runtimePendingRef: { current: false },
+ selectedDeviceId: 'host', selectedDeviceName: 'Host', selectedDeviceRef: { current: 'host' },
+ draft, remoteAgentPick: {}, deviceProvidersRef: { current: { ready: false } },
+ captureWorktreeCreateIntent: () => ({ applicable: false, enabled: false }), isWorktreeCreateIntentCurrent: () => true,
+ setCreating: noop, setGoalBusy: noop, auth: { user: { id: 'test-user' } },
+ getMobileAuthOwner: () => ({ accountId: 'test-user' }), isMobileAuthOwnerCurrent: () => true,
+ agentAuthVerdict: 'ready', applyRemoteAgentPick: (value: unknown) => value,
+ createNewSessionId: () => 'new-goal-task', saveNewSessionPreferences: noop,
+ getDeviceProvidersGen: () => 1, resolveRecentModelAndProvider: (_rows: unknown, selected: unknown) => selected,
+ assertSubmitModelResolved: noop, withTransientRemoteRetry: (fn: () => Promise<unknown>) => fn(), openLink: noop, subscribe: vi.fn(async () => {}),
+ buildRemoteCreateSessionOptions: (value: unknown) => value, normalizeCreateSessionResult: (value: unknown) => value,
+ maker: { createSession: vi.fn(async () => ({ sessionId: 'new-goal-task' })),
+ goal: { set: vi.fn(async () => {}) }, getSession: vi.fn(async () => ({ id: 'new-goal-task', title: 'Goal task' })) },
+ collabDraft: null, remoteSessionStore: { upsertDeviceSession: noop, setPendingTitlePreview: noop },
+ isDefaultDraftSessionTitle: () => false, waitForPendingUploads: noop,
+ setAttachments: noop, setMediaAssetAttachments: noop, setAttachmentPreviews: noop, composerAnnotationsRef: { current: null },
+ patchDraft: vi.fn(), router: { replace: vi.fn() }, humanizeRemoteError,
+ };
+ bindings.createGoalSession = vi.fn(goalCreate(bindings));
+ return { bindings, run: newCreate(bindings) as () => Promise<void> };
+}
+
+function existingHarness(args = 'target') {
+ const initial = textComposerDocument(`/goal ${args}`);
+ const release = vi.fn();
+ const noop = vi.fn();
+ const session = { id: 'existing-task', agentKind: 'pi', model: 'test-model', permissionMode: 'ask', workingDir: '/test-workdir' };
+ const bindings = {
+ setError: vi.fn(), setGoalError: vi.fn(), t: (key: string) => key,
+ isRemoteSessionMissing: () => false, readSessionRowNow: () => session, goalBusy: false, setGoalBusy: vi.fn(),
+ executeMobileGoalCommand, sessionId: 'existing-task', deviceId: 'host', deviceIdRef: { current: 'host' },
+ outboxSessionAliveRef: { current: 'existing-task' }, getMobileAuthOwner: () => ({}), isMobileAuthOwnerCurrent: () => true,
+ maker: { goal: { set: vi.fn(async () => {}), clear: vi.fn(async () => {}), getStatus: vi.fn(async () => ({ status: 'active', objective: 'target' })) } },
+ remoteSessionStore: { setGoalStatus: vi.fn(), acquireSessionMessageWork: vi.fn(() => ({ release })), getSessionDeviceId: () => 'host' }, setContextSheetView: vi.fn(), setContextSheetOpen: vi.fn(),
+ setGoalRestore: vi.fn(), router: { setParams: vi.fn() }, composerDocumentRef: { current: initial },
+ composerDocumentsEqual: (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b),
+ applyComposerDocument: vi.fn(), normalizeComposerDocument, humanizeRemoteError,
+ composerDraftHydrated: true, voiceState: 'idle', slashCommandsRef: { current: [] }, queueEditingRef: { current: null },
+ composerDocumentProjectedText, serializeComposerDocument, reconcileComposerProjectedText, emptyComposerDocument,
+ canUseComposer: true, attachments: [] as unknown[], attachmentsRef: { current: [] as unknown[] }, pendingUploads: [],
+ sendInFlightRef: { current: false }, sending: false, setSending: vi.fn((_sending: boolean) => {}), currentSession: session,
+ outboxConnectionBlockedNow: () => false, getPendingUploadCount: () => 0,
+ parseMobileLocalSystemCommand: () => null, parseMobileDesktopCommand, pendingSkillSelectionRef: { current: null },
+ resolveSessionAgentKind: () => 'pi', modelNeedsReselection: () => false, getCachedDeviceProviders: () => undefined,
+ commandNeedsRemoteSession: () => false, extractMobileSessionReferences: () => [], outboxDispatchBlockedNow: () => false,
+ runtimeOptions: { planModeSupported: true }, permissionModeOrAsk: (mode: string) => mode,
+ dismissPromptRecommendation: noop, hydrateComposerMessageReferenceBodies: async (doc: unknown) => doc,
+ resolvePastedSessionLinkLabel: noop, requestMessageListFollowLatest: noop, hasPastePlaceholders: () => false,
+ beginOutboxAttachmentHandoff: async () => ({ prepare: async () => [], release: noop }),
+ attachmentPreviews: {}, buildOutboxItem: (input: unknown) => input, createOutboxClientId: () => 'ordinary-message',
+ mobileDurableOutbox: { add: vi.fn(async (_record: unknown) => {}) }, rememberSentAttachmentPreviews: noop,
+ releaseUploadedSources: noop, setMediaAssetAttachments: noop, setAttachmentPreviews: noop,
+ composerAnnotationsRef: { current: null }, setAttachments: noop, setAttachmentError: noop,
+ voiceDictionaryLearningTrackerRef: { current: null }, formatRemoteError: String,
+ };
+ bindings.setSending = vi.fn((value: boolean) => { bindings.sending = value; });
+ bindings.applyComposerDocument = vi.fn((doc: typeof initial) => { bindings.composerDocumentRef.current = doc; });
+ return { bindings, release, run: () => new Function(...Object.keys(bindings), compiledExisting)(...Object.values(bindings))() as Promise<void> };
+}
+
+describe('new task /goal page callback', () => {
+ it('creates one actual task and sets its Goal exactly once, preserving the handoff lock', async () => {
+ const h = newHarness();
+ await h.run();
+ await h.run();
+ expect(h.bindings.setGoalError).toHaveBeenLastCalledWith(null);
+ expect(h.bindings.maker.createSession).toHaveBeenCalledOnce();
+ expect(h.bindings.maker.goal.set).toHaveBeenCalledExactlyOnceWith({ sessionId: 'new-goal-task', objective: 'target' });
+ expect(h.bindings.router.replace).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ sessionId: 'new-goal-task' }) }));
+ expect(h.bindings.createMessageSession).not.toHaveBeenCalled();
+ });
+ it('opens the existing panel for bare /goal without creating a task', async () => {
+ const h = newHarness('/goal'); await h.run();
+ expect(h.bindings.setContextSheetView).toHaveBeenCalledWith('goal');
+ expect(h.bindings.maker.createSession).not.toHaveBeenCalled();
+ });
+ it.each(['clear', 'stop', 'off', 'cancel', 'reset', 'none'])('rejects %s without an existing task', async alias => {
+ const h = newHarness(`/goal ${alias}`); await h.run();
+ expect(h.bindings.setError).toHaveBeenCalledWith('session.new.goalCommandNeedsSession');
+ expect(h.bindings.maker.createSession).not.toHaveBeenCalled();
+ });
+ it('hands a failed Goal set back to the created task with its objective, without replay', async () => {
+ const h = newHarness(); h.bindings.maker.goal.set.mockRejectedValueOnce(new Error('[CHANNEL_NOT_ALLOWED] old host'));
+ await h.run(); await h.run();
+ expect(h.bindings.maker.createSession).toHaveBeenCalledOnce();
+ expect(h.bindings.maker.goal.set).toHaveBeenCalledOnce();
+ expect(h.bindings.router.replace).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ sessionId: 'new-goal-task', goalObjective: 'target', goalError: expect.any(String) }) }));
+ });
+ it('keeps attachments and the command draft instead of creating a task', async () => {
+ const h = newHarness(); h.bindings.attachmentsRef.current = [{}]; await h.run();
+ expect(h.bindings.firstMessageRef.current).toBe('/goal target');
+ expect(h.bindings.setError).toHaveBeenCalledWith('session.screen.goalCommandAttachments');
+ expect(h.bindings.maker.createSession).not.toHaveBeenCalled();
+ });
+ it('preserves an explicit same-name Skill selection', async () => {
+ const h = newHarness(); h.bindings.pendingGoalSkillRef.current = 'goal'; await h.run();
+ expect(h.bindings.createMessageSession).toHaveBeenCalledOnce();
+ expect(h.bindings.maker.goal.set).not.toHaveBeenCalled();
+ });
+});
+
+describe('existing task /goal send boundary', () => {
+ it('sets the associated task Goal and projects its real status', async () => {
+ const h = existingHarness(); await h.run();
+ expect(h.bindings.maker.goal.set).toHaveBeenCalledExactlyOnceWith({ sessionId: 'existing-task', objective: 'target' });
+ expect(h.bindings.remoteSessionStore.setGoalStatus).toHaveBeenCalledWith('existing-task', { status: 'active', objective: 'target' });
+ expect(h.bindings.applyComposerDocument).toHaveBeenCalledWith(emptyComposerDocument());
+ });
+ it('bare /goal opens the existing panel', async () => {
+ const h = existingHarness(''); await h.run();
+ expect(h.bindings.setContextSheetOpen).toHaveBeenCalledWith(true);
+ expect(h.bindings.maker.goal.set).not.toHaveBeenCalled();
+ });
+ it('keeps bare /goal when the host cannot read Goal status', async () => {
+ const h = existingHarness('');
+ h.bindings.maker.goal.getStatus.mockRejectedValueOnce(new Error('[CHANNEL_NOT_ALLOWED] old host'));
+ await h.run();
+ expect(h.bindings.applyComposerDocument).not.toHaveBeenCalled();
+ expect(h.bindings.setContextSheetOpen).not.toHaveBeenCalled();
+ expect(h.bindings.setError).toHaveBeenCalledWith(humanizeRemoteError(new Error('[CHANNEL_NOT_ALLOWED] old host')));
+ });
+ it.each(['[CHANNEL_NOT_ALLOWED] old host', '[NOT_CONNECTED] offline'])('retains the draft on %s', async error => {
+ const h = existingHarness(); h.bindings.maker.goal.set.mockRejectedValueOnce(new Error(error)); await h.run();
+ expect(h.bindings.applyComposerDocument).not.toHaveBeenCalled();
+ expect(h.bindings.setError).toHaveBeenCalledWith(humanizeRemoteError(new Error(error)));
+ });
+ it('does not consume newer input while Goal is being set', async () => {
+ const h = existingHarness(); h.bindings.maker.goal.set.mockImplementationOnce(async () => { h.bindings.composerDocumentRef.current = textComposerDocument('new input'); }); await h.run();
+ expect(h.bindings.applyComposerDocument).not.toHaveBeenCalled();
+ });
+ it('rejects attachments and retains the command', async () => {
+ const h = existingHarness(); h.bindings.attachmentsRef.current = [{}]; await h.run();
+ expect(h.bindings.setError).toHaveBeenCalledWith('session.screen.goalCommandAttachments');
+ expect(h.bindings.maker.goal.set).not.toHaveBeenCalled();
+ expect(h.bindings.applyComposerDocument).not.toHaveBeenCalled();
+ });
+ it('ignores a late result after switching tasks', async () => {
+ const h = existingHarness(); h.bindings.maker.goal.set.mockImplementationOnce(async () => { h.bindings.outboxSessionAliveRef.current = 'other-task'; }); await h.run();
+ expect(h.bindings.remoteSessionStore.setGoalStatus).not.toHaveBeenCalled();
+ expect(h.bindings.applyComposerDocument).not.toHaveBeenCalled();
+ expect(h.bindings.sendInFlightRef.current).toBe(false);
+ expect(h.release).toHaveBeenCalledOnce();
+ });
+ it('keeps the send lock while Goal is in flight and rejects a duplicate submission', async () => {
+ const h = existingHarness();
+ let finish!: () => void;
+ h.bindings.maker.goal.set.mockImplementationOnce(() => new Promise<void>(resolve => { finish = resolve; }));
+ const first = h.run();
+ expect(h.bindings.sendInFlightRef.current).toBe(true);
+ await h.run();
+ expect(h.bindings.maker.goal.set).toHaveBeenCalledOnce();
+ expect(h.release).not.toHaveBeenCalled();
+ finish();
+ await first;
+ expect(h.bindings.sendInFlightRef.current).toBe(false);
+ expect(h.bindings.sending).toBe(false);
+ expect(h.release).toHaveBeenCalledOnce();
+ });
+ it.each(['set', 'clear', 'bare', 'failure', 'attachments', 'busy'] as const)('releases the complete send boundary after Goal %s so an ordinary message can follow', async scenario => {
+ const h = existingHarness(scenario === 'clear' ? 'clear' : scenario === 'bare' ? '' : 'target');
+ if (scenario === 'failure') h.bindings.maker.goal.set.mockRejectedValueOnce(new Error('[NOT_CONNECTED] offline'));
+ if (scenario === 'attachments') h.bindings.attachmentsRef.current = [{}];
+ if (scenario === 'busy') h.bindings.goalBusy = true;
+ await h.run();
+ expect(h.bindings.sendInFlightRef.current).toBe(false);
+ expect(h.bindings.sending).toBe(false);
+ expect(h.release).toHaveBeenCalledOnce();
+ h.bindings.goalBusy = false;
+ h.bindings.attachmentsRef.current = [];
+ h.bindings.composerDocumentRef.current = textComposerDocument('ordinary follow-up');
+ await h.run();
+ expect(h.bindings.mobileDurableOutbox.add).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
+ item: expect.objectContaining({ sessionId: 'existing-task', text: 'ordinary follow-up' }),
+ }));
+ expect(h.bindings.sendInFlightRef.current).toBe(false);
+ expect(h.bindings.sending).toBe(false);
+ expect(h.release).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index 5842711f2a..b1cbbde4f5 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -2053,9 +2053,18 @@ describe('new session composer surface', () => {
const browseHiddenToggleStyleStart = newSource.indexOf('browseHiddenToggle: {');
const browseHiddenToggleStyleEnd = newSource.indexOf('browseCheckbox: {', browseHiddenToggleStyleStart);
const browseHiddenToggleStyle = newSource.slice(browseHiddenToggleStyleStart, browseHiddenToggleStyleEnd);
- const createStart = newSource.indexOf('const create = useCallback(async () => {');
- const createEnd = newSource.indexOf('return (', createStart);
+ const createStart = newSource.indexOf('const createMessageSession = useCallback(async () => {');
+ const createEnd = newSource.indexOf('const createGoalSession = useCallback', createStart);
+ expect(createStart).toBeGreaterThan(-1);
+ expect(createEnd).toBeGreaterThan(createStart);
const createSource = newSource.slice(createStart, createEnd);
+ const dispatchStart = newSource.indexOf('const create = useCallback(async () => {', createEnd);
+ expect(dispatchStart).toBeGreaterThan(createEnd);
+ const dispatchEnd = newSource.indexOf('const goalDraftCommand', dispatchStart);
+ expect(dispatchEnd).toBeGreaterThan(dispatchStart);
+ const dispatchSource = newSource.slice(dispatchStart, dispatchEnd);
+ expect(dispatchSource).toContain("if (parsed?.name !== 'goal' || pendingGoalSkillRef.current === 'goal')");
+ expect(dispatchSource).toContain('await createMessageSession();');
expect(newSource).toContain("MobileComposerInputRow,");
expect(sessionSource).toContain("MobileComposerInputRow,");
@@ -2574,10 +2583,11 @@ describe('submit guard catalog wiring (source locks)', () => {
expect(newSource.match(/parseAck: parseDiscardPrecreatedAck,/g) ?? []).toHaveLength(2);
// 真局部 slice(独立 review round-22 Standards P1:全文件 indexOf 命中 create 首个
// 检查,Goal 检查删掉也照样绿)
- const createSlice = newSource.slice(
- newSource.indexOf('const create = useCallback'),
- newSource.indexOf('const createGoalSession = useCallback'),
- );
+ const createStart = newSource.indexOf('const createMessageSession = useCallback');
+ const goalStart = newSource.indexOf('const createGoalSession = useCallback');
+ expect(createStart).toBeGreaterThan(-1);
+ expect(goalStart).toBeGreaterThan(createStart);
+ const createSlice = newSource.slice(createStart, goalStart);
const goalSlice = newSource.slice(newSource.indexOf('const createGoalSession = useCallback'));
// 入口设备检查先于加锁(round-20 Standards P1 busy 泄漏):goal 的 setGoalBusy(true)
// 前必须有该 return(create() 的检查在 try 内,finally 兜底,不要求此序)。
diff --git a/apps/mobile/src/__tests__/newSessionWorktreeSync.test.tsx b/apps/mobile/src/__tests__/newSessionWorktreeSync.test.tsx
index b87e869412..5c32182b5f 100644
--- a/apps/mobile/src/__tests__/newSessionWorktreeSync.test.tsx
+++ b/apps/mobile/src/__tests__/newSessionWorktreeSync.test.tsx
@@ -94,11 +94,11 @@ const bindingsNames = [
const compiled = ts.transpileModule(`function usePageWorktree(bindings) {
const { ${bindingsNames.join(', ')} } = bindings;
${hooks.map((node) => node.getText(source)).join('\n')}
- ${entryGuards('create')}
+ ${entryGuards('createMessageSession')}
${entryGuards('createGoalSession')}
return { worktreeEnabled, worktreeCreateBlocked, worktreeToggleDisabled,
worktreePreferenceSaving, worktreePreferenceAuthorityUnknown,
- toggleWorktree, create, createGoalSession, isWorktreeCreateIntentCurrent };
+ toggleWorktree, create: createMessageSession, createGoalSession, isWorktreeCreateIntentCurrent };
}`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
interface Intent { enabled: boolean; sourceBranch: string; target: { deviceId: string } }
interface State {
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 3da0ca4756..d60bd5ae47 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -227,6 +227,7 @@
"sessionNotSyncedRetry": "The session hasn't finished syncing; try again shortly.",
"savingPreviousQueueEdit": "Saving the previous queued message edit; edit again once it finishes.",
"attachmentsUploadingBeforeEdit": "Attachments are still uploading; edit the queued message after they finish.",
+ "goalCommandAttachments": "Send /goal without attachments. Your draft and attachments are kept.",
"goalAlreadyActive": "This session already has an active goal; handle it here first.",
"resetReconfirmTitle": "Confirm Again",
"resetOfferExpired": "The reset credential has expired; review the refreshed quota info.",
@@ -287,6 +288,7 @@
"shareMessage": "Share this message"
},
"new": {
+ "goalCommandNeedsSession": "Open an existing session to clear its goal.",
"selectDevice": "Select a device",
"workspaceDialogue": "Chat",
"workspaceProject": "Project",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 1e87be3353..5a358a982f 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -227,6 +227,7 @@
"sessionNotSyncedRetry": "セッションの同期がまだ完了していません。しばらくしてから再試行してください。",
"savingPreviousQueueEdit": "直前のキュー内メッセージの変更を保存中です。完了してから編集してください。",
"attachmentsUploadingBeforeEdit": "添付ファイルをアップロード中です。完了してからキュー内メッセージを編集してください。",
+ "goalCommandAttachments": "添付ファイルなしで /goal を送信してください。下書きと添付ファイルは保持されています。",
"goalAlreadyActive": "このセッションには進行中のゴールがあります。先にこちらで対応してください。",
"resetReconfirmTitle": "再確認してください",
"resetOfferExpired": "リセット用の認証が期限切れです。更新後のクォータ情報を確認してください。",
@@ -287,6 +288,7 @@
"shareMessage": "このメッセージを共有"
},
"new": {
+ "goalCommandNeedsSession": "目標を解除するには既存のセッションを開いてください。",
"selectDevice": "デバイスを選択",
"workspaceDialogue": "会話",
"workspaceProject": "プロジェクト",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 9440777c09..639b4af45f 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -223,6 +223,7 @@
"sessionNotSyncedRetry": "세션 동기화가 아직 완료되지 않았습니다. 잠시 후 다시 시도하세요.",
"savingPreviousQueueEdit": "이전 대기열 메시지의 변경을 저장 중입니다. 완료된 후 편집하세요.",
"attachmentsUploadingBeforeEdit": "첨부 파일을 업로드 중입니다. 완료된 후 대기열 메시지를 편집하세요.",
+ "goalCommandAttachments": "첨부 파일 없이 /goal을 보내세요. 초안과 첨부 파일은 유지됩니다.",
"goalAlreadyActive": "이 세션에는 진행 중인 목표가 있습니다. 먼저 여기에서 처리하세요.",
"resetReconfirmTitle": "다시 확인해 주세요",
"resetOfferExpired": "재설정 자격 증명이 만료되었습니다. 새로 고친 사용량 정보를 확인하세요.",
@@ -283,6 +284,7 @@
"shareMessage": "이 메시지 공유"
},
"new": {
+ "goalCommandNeedsSession": "목표를 해제하려면 기존 세션을 여세요.",
"selectDevice": "기기 선택",
"workspaceDialogue": "대화",
"workspaceProject": "프로젝트",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 1b867bb352..7808e914d4 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -223,6 +223,7 @@
"sessionNotSyncedRetry": "任务尚未同步完成,请稍后再试。",
"savingPreviousQueueEdit": "正在保存上一条排队消息的修改,完成后再编辑。",
"attachmentsUploadingBeforeEdit": "还有附件正在上传,等上传完成后再编辑排队消息。",
+ "goalCommandAttachments": "请单独发送 /goal。草稿和附件已保留。",
"goalAlreadyActive": "该任务已有进行中的目标,请先在此处理它。",
"resetReconfirmTitle": "请重新确认",
"resetOfferExpired": "重置凭证已过期,请确认刷新后的配额信息。",
@@ -283,6 +284,7 @@
"shareMessage": "分享这条消息"
},
"new": {
+ "goalCommandNeedsSession": "请进入已有任务清除目标。",
"selectDevice": "选择设备",
"workspaceDialogue": "对话",
"workspaceProject": "项目",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index 678a3b5a5e..0c2f6ef877 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -227,6 +227,7 @@
"sessionNotSyncedRetry": "任務尚未同步完成,請稍後再試。",
"savingPreviousQueueEdit": "正在儲存上一條排隊訊息的修改,完成後再編輯。",
"attachmentsUploadingBeforeEdit": "還有附件正在上傳,等上傳完成後再編輯排隊訊息。",
+ "goalCommandAttachments": "請單獨傳送 /goal。草稿和附件已保留。",
"goalAlreadyActive": "該任務已有進行中的目標,請先在此處理它。",
"resetReconfirmTitle": "請重新確認",
"resetOfferExpired": "重置憑證已過期,請確認重新整理後的配額資訊。",
@@ -287,6 +288,7 @@
"shareMessage": "分享這條訊息"
},
"new": {
+ "goalCommandNeedsSession": "請進入既有任務清除目標。",
"selectDevice": "選擇裝置",
"workspaceDialogue": "對話",
"workspaceProject": "專案",
diff --git a/apps/mobile/src/session/desktopSlashCommands.ts b/apps/mobile/src/session/desktopSlashCommands.ts
index 9f421010f6..a8256d0091 100644
--- a/apps/mobile/src/session/desktopSlashCommands.ts
+++ b/apps/mobile/src/session/desktopSlashCommands.ts
@@ -14,15 +14,18 @@
*
* 纯函数、无 RN 依赖,node 可单测。
*/
-import type { MobileLearnStartRequest, MobileSlashCommand } from '@/device-link/mobileMakerTransport';
+import { parseGoalCommand } from '@cindy/maker-shared/goal-command';
+import { mergeSlashCommands } from '@cindy/maker-shared/composer-palette';
+import type { MobileLearnStartRequest, MobileSlashCommand, MobileMakerTransport } from '@/device-link/mobileMakerTransport';
/**
* 移动端可执行的 desktop 命令白名单。只放行已实现分流的命令:
+ * - goal:现有目标面板与 maker:goal:* 业务。
* - learn:直调被控端 `learn:start`(评审 UI 暂在桌面端,移动端出系统卡提示)。
* 其余 desktop 命令(/help /clear /issue /workflows /jump-session 等)是控制端
* UI 动作,移动端没有对应实现,展示了也执行不了 → 不放行。
*/
-export const MOBILE_SUPPORTED_DESKTOP_COMMANDS: ReadonlySet<string> = new Set(['learn']);
+export const MOBILE_SUPPORTED_DESKTOP_COMMANDS: ReadonlySet<string> = new Set(['learn', 'goal']);
/** palette 展示用:被控端 desktop 命令清单 → 只保留移动端可执行子集。 */
export function filterMobileDesktopCommands(
@@ -103,3 +106,23 @@ export function buildLearnCardData(
detail: outcome.errorMessage,
};
}
+
+/** Goal stays discoverable even before the remote command roster has loaded. */
+export function mergeMobileGoalCommand(commands: readonly MobileSlashCommand[], description: string): MobileSlashCommand[] {
+ return mergeSlashCommands(
+ commands.filter(command => command.kind === 'agent-builtin'),
+ commands.filter(command => command.kind === 'agent-skill'),
+ [{ kind: 'desktop', name: 'goal', description }, ...commands.filter(command => command.kind === 'desktop' && command.name !== 'goal')],
+ );
+}
+
+/** No text is enqueued; writes are attempted exactly once, then status is read. */
+export async function executeMobileGoalCommand(args: string, sessionId: string, goal: MobileMakerTransport['goal']) {
+ const command = parseGoalCommand(args);
+ if (command.action === 'open-dialog') return { command, status: await goal.getStatus(sessionId) };
+ if (command.action === 'clear') await goal.clear(sessionId);
+ else await goal.set({ sessionId, objective: command.objective });
+ // A failed status refresh must never cause replay of an already accepted write.
+ const status = await goal.getStatus(sessionId).catch(() => undefined);
+ return { command, status };
+}
diff --git a/docs/product-rules/core-product-principles.md b/docs/product-rules/core-product-principles.md
index 99ac5c2bb7..a445121c3b 100644
--- a/docs/product-rules/core-product-principles.md
+++ b/docs/product-rules/core-product-principles.md
@@ -116,6 +116,23 @@ Cindy 应让用户方便地接入、选择和使用不同 Agent 与模型,同
- 切换设备或断线重连后,用户不需要重新解释已经存在的上下文。
- 多端状态冲突、权限与操作归属必须有确定规则,不能依赖用户猜测。
+#### 目标模式与补充消息
+
+目标运行期间,普通补充、问进度、排队消息与同轮插话优先处理,结束后继续原目标。
+普通消息保留真实来源,不计入 Goal 轮数和预算,也不采用其正文作为 Goal 完成裁决。
+显式暂停、Stop、清除仍优先于自动恢复与迟到事件;错误、限额和既有预算守卫不变。
+待处理输入、审批、恢复暂停与队列锁未释放时,Goal 不抢跑;后台事件不视为新的目标轮次。
+不通过关键词或额外模型调用推断自然语言暂停,现有明确控制入口才提供确定的暂停保证。
+
+手机新建和已有任务中的 `/goal` 复用既有目标面板和 `maker:goal:*` 接口:无参数打开面板,
+目标参数设置目标,`clear / stop / off / cancel / reset / none` 与桌面一样清除。
+同名 Skill 优先;命令与附件组合明确拒绝并保留草稿。能力不支持或连接失败不降为模型消息,
+已创建任务的 Goal 设置失败转到该任务恢复目标,不重复建任务或自动重放设置请求。
+
+实现与回归:Desktop `goal-host/controller.ts`、`goal-host/__tests__/controller.test.ts`,
+Mobile `session/desktopSlashCommands.ts`、`__tests__/mobileGoalCommands.test.ts`。
+后台工作与目标的全面联动沿现有执行边界,不在此规则中引入额外生命周期或完成复核。
+
### 4.4 插件系统
插件是运行在 Cindy 中的沙箱小程序,是人类与 Cindy Agent 双向协作的应用界面。
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index 488f8486c4..080b08febb 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -30,6 +30,7 @@
"./file-preview": "./src/filePreview.ts",
"./fixtures": "./src/fixtures.ts",
"./ghost-command": "./src/ghostCommand.ts",
+ "./goal-command": "./src/goalCommand.ts",
"./goal-verdict": "./src/goalVerdict.ts",
"./history-gap": "./src/historyGap.ts",
"./image-annotation": "./src/imageAnnotation.ts",
diff --git a/packages/maker-shared/src/goalCommand.ts b/packages/maker-shared/src/goalCommand.ts
new file mode 100644
index 0000000000..d3a4a72583
--- /dev/null
+++ b/packages/maker-shared/src/goalCommand.ts
@@ -0,0 +1,14 @@
+/** Host-owned /goal semantics shared by Desktop and Mobile. */
+export type GoalCommand =
+ | { action: 'open-dialog' }
+ | { action: 'clear' }
+ | { action: 'set'; objective: string };
+
+const CLEAR_ALIASES = new Set(['clear', 'stop', 'off', 'cancel', 'reset', 'none']);
+
+export function parseGoalCommand(args: string): GoalCommand {
+ const objective = args.trim();
+ if (!objective) return { action: 'open-dialog' };
+ if (CLEAR_ALIASES.has(objective.toLowerCase())) return { action: 'clear' };
+ return { action: 'set', objective };
+}