Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): gate recommendations on voice input and observed turns
DavidShen4d6e0b4df217
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex cb90ecca33..99832d9ec0 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -1355,14 +1355,6 @@ export default function SessionScreen() {requestAnimationFrame(() => composerInputRef.current?.focus());},});- const { prompt: promptRecommendation, dismiss: dismissPromptRecommendation } = usePromptRecommendation({- ownerId: auth.user?.id, deviceId, sessionId, maker,- agentKind: recommendationSession ? agentKindForSession(recommendationSession) : null,- revision: recommendationSession?.lastTurnEndedAt, running: remoteSessionRunning,- composerSource: composerDraftSource,- hasAttachments: attachments.length > 0 || pendingUploads.length > 0 || pastePlaceholderCount > 0,- hasTerminalError: remoteSessionRunStatus.hasTerminalError === true,- });// 换会话与退屏的 outbox 回收:未派发条目的文字合并回草稿库(用户已「发出」的文字// 不能静默蒸发,回来时出现在输入框里),在途上传任务丢弃(与托盘退出语义一致,// controller 会中止传输并回收已完成的 OSS 对象),已就绪附件回收中转对象。@@ -1396,6 +1388,16 @@ export default function SessionScreen() {const voiceStartPendingSeqRef = useRef(0);const voiceStartedOnPressInRef = useRef(false);const [voiceState, setVoiceStateInternal] = useState<MobileVoiceState>('idle');+ const { prompt: promptRecommendation, dismiss: dismissPromptRecommendation } = usePromptRecommendation({+ ownerId: auth.user?.id, deviceId, sessionId, maker,+ agentKind: recommendationSession ? agentKindForSession(recommendationSession) : null,+ revision: recommendationSession?.lastTurnEndedAt, running: remoteSessionRunning,+ composerSource: composerDraftSource,+ hasAttachments: attachments.length > 0 || pendingUploads.length > 0 || pastePlaceholderCount > 0,+ hasTerminalError: remoteSessionRunStatus.hasTerminalError === true,+ voiceIsBusy: voiceStartPending || voiceState === 'listening'+ || voiceState === 'submitting' || voiceState === 'refining',+ });const [voiceError, setVoiceError] = useState<string | null>(null);const [voiceReleaseToSendActive, setVoiceReleaseToSendActive] = useState(false);// 「语音结束保持展开」hold:语音真实收尾(busy → done/error)时布防,草稿仍有diff --git a/apps/mobile/src/__tests__/usePromptRecommendation.test.tsx b/apps/mobile/src/__tests__/usePromptRecommendation.test.tsxindex 704c3ac925..70ee32da6c 100644--- a/apps/mobile/src/__tests__/usePromptRecommendation.test.tsx+++ b/apps/mobile/src/__tests__/usePromptRecommendation.test.tsx@@ -42,6 +42,53 @@ it('waits for the new completion revision even when stopped arrives first', asynexpect(request).toHaveBeenLastCalledWith(expect.objectContaining({ cacheOnly: false, completionRevision: 20 }));});+it('metadata refresh after opening cached history stays cache-only, including retries', async () => {+ request.mockResolvedValue({ prompt: null });+ await render(); await advance();+ await render({ revision: 20 }); await advance();+ await act(async () => vi.advanceTimersByTimeAsync(10_000));+ expect(request).toHaveBeenCalledTimes(5);+ expect(request.mock.calls.every(([args]) => args.cacheOnly === true)).toBe(true);+});++it('an observed run authorizes only its completion, and a later run can predict again', async () => {+ await render({ running: true });+ await render({ running: false, revision: 20 }); await advance();+ expect(request).toHaveBeenLastCalledWith(expect.objectContaining({ cacheOnly: false, completionRevision: 20 }));+ await render({ revision: 30 }); await advance();+ expect(request).toHaveBeenLastCalledWith(expect.objectContaining({ cacheOnly: true, completionRevision: 30 }));+ await render({ running: true });+ await render({ running: false, revision: 40 }); await advance();+ expect(request).toHaveBeenLastCalledWith(expect.objectContaining({ cacheOnly: false, completionRevision: 40 }));+});++it('voice input consumes a completion before transcription, without reviving it when voice ends', async () => {+ await render({ running: true, voiceIsBusy: true });+ await render({ running: false, revision: 20 }); await advance();+ expect(request).not.toHaveBeenCalled();+ await render({ voiceIsBusy: false }); await advance();+ expect(request).not.toHaveBeenCalled();+ await render({ running: true });+ await render({ running: false, revision: 30 }); await advance();+ expect(value.prompt).toBe('Suggested next step');+});++it('starting voice cancels a scheduled request and rejects an already pending result', async () => {+ await render({ running: true });+ await render({ running: false, revision: 20 });+ await render({ voiceIsBusy: true }); await advance();+ expect(request).not.toHaveBeenCalled();+ await render({ running: true, voiceIsBusy: false });+ let resolve!: (result: { prompt: string }) => void;+ request.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));+ await render({ running: false, revision: 30 }); await advance();+ await render({ voiceIsBusy: true });+ await act(async () => resolve({ prompt: 'Stale suggestion' }));+ await render({ voiceIsBusy: false }); await advance();+ expect(value.prompt).toBeNull();+ expect(request).toHaveBeenCalledTimes(1);+});+it('dismissal or sending rejects late results and survives a page remount', async () => {let resolve!: (result: { prompt: string }) => void;request.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));diff --git a/apps/mobile/src/session/usePromptRecommendation.ts b/apps/mobile/src/session/usePromptRecommendation.tsindex 1f84c09a21..bb5488a865 100644--- a/apps/mobile/src/session/usePromptRecommendation.ts+++ b/apps/mobile/src/session/usePromptRecommendation.ts@@ -9,7 +9,7 @@ const subscribeEmptyComposer = () => () => {};const CACHE_RETRY_DELAYS_MS = [1_000, 3_000, 5_000];export function usePromptRecommendation({ ownerId, deviceId, sessionId, agentKind, revision, running, maker,- composerSource, hasAttachments = false, hasTerminalError = false }: {+ composerSource, hasAttachments = false, hasTerminalError = false, voiceIsBusy = false }: {ownerId?: string;deviceId: string;sessionId: string;@@ -19,6 +19,7 @@ export function usePromptRecommendation({ ownerId, deviceId, sessionId, agentKincomposerSource?: ComposerDraftSource;hasAttachments?: boolean;hasTerminalError?: boolean;+ voiceIsBusy?: boolean;maker: Pick<MobileMakerTransport, 'predictNextPrompt'>;}) {const scope = JSON.stringify([ownerId, deviceId, sessionId]);@@ -27,7 +28,7 @@ export function usePromptRecommendation({ ownerId, deviceId, sessionId, agentKinconst snapshot = composerSource?.getSnapshot();return !!snapshot && (!!snapshot.draft.trim() || composerDocumentQuotes(snapshot.document).length > 0);});- const blocked = hasComposerContent || hasAttachments || hasTerminalError;+ const blocked = hasComposerContent || hasAttachments || hasTerminalError || voiceIsBusy;const [result, setResult] = useState<{ scope: string; revision: number; prompt: string } | null>(null);// The transport is recreated when the device-link context refreshes. Keep the// latest callable without treating that refresh as a new recommendation run.@@ -39,7 +40,6 @@ export function usePromptRecommendation({ ownerId, deviceId, sessionId, agentKinrunning: false,sawRunning: false,revisionAtStart: 0,- lastRevision: null as number | null,liveRevision: null as number | null,});const current = useRef({ scope, revision, running, blocked });@@ -56,22 +56,12 @@ export function usePromptRecommendation({ ownerId, deviceId, sessionId, agentKinrunning: false,sawRunning: false,revisionAtStart: 0,- lastRevision: null,liveRevision: null,};request.current = null;setResult(null);}const run = observed.current;- // A sessions patch can deliver the new completion revision without a- // visible running edge (for example while the phone is reconnecting).- // Remember the latest revision so that a strictly newer completion still- // starts a live prediction instead of being treated as history.- const revisionAdvanced = revision != null- && run.lastRevision != null- && revision > run.lastRevision;- if (revision != null) run.lastRevision = revision;- if (revisionAdvanced) run.liveRevision = revision;if (running) {if (!run.running) {// A fresh running edge starts a new completion generation. A dismissal@@ -79,6 +69,7 @@ export function usePromptRecommendation({ ownerId, deviceId, sessionId, agentKinconsumedRevisions.delete(scope);run.sawRunning = true;run.revisionAtStart = revision ?? 0;+ run.liveRevision = null;request.current = null;setResult(null);}@@ -86,6 +77,13 @@ export function usePromptRecommendation({ ownerId, deviceId, sessionId, agentKinreturn;}run.running = false;+ // Only an observed run can authorize a paid prediction. Keep waiting if+ // stopped arrives before its revision, then bind that run to one completion.+ // Later metadata refreshes must not inherit permission from an older run.+ if (run.sawRunning && revision != null && revision > run.revisionAtStart) {+ run.liveRevision = revision;+ run.sawRunning = false;+ }if (!deviceId || !sessionId || !agentKind || !revision || consumedRevisions.get(scope) === revision) return;if (blocked) {// Consume this completion even if the draft/attachment is later removed.@@ -94,9 +92,7 @@ export function usePromptRecommendation({ ownerId, deviceId, sessionId, agentKinreturn;}// Historical navigation only reuses a host result; it never starts a paid prediction.- // An ended patch may arrive after stopped, so keep the observed run until then.- const cacheOnly = (!run.sawRunning && run.liveRevision !== revision)- || (run.sawRunning && revision <= run.revisionAtStart);+ const cacheOnly = run.liveRevision !== revision;if (request.current?.scope === scope && request.current.revision === revision&& request.current.cacheOnly === cacheOnly) return;const attempt = { scope, revision, cacheOnly };