The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): queue goal-resume continuation when busy; wipe session controls on gateway switch
Tekniumefc30169c328
diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsxindex 7308cdcec31..59d55dbd4a0 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx@@ -1,5 +1,6 @@import { memo, useCallback, useState } from 'react'+import { queueKickoffIfSessionBusy } from '@/app/session/hooks/use-prompt-actions/queue-if-busy'import type { SubmitTextOptions } from '@/app/session/hooks/use-prompt-actions/utils'import { StatusSection } from '@/components/chat/status-section'import { Button } from '@/components/ui/button'@@ -85,6 +86,22 @@ export const SessionControlGoalSection = memo(function SessionControlGoalSectionreturn false}+ // The backend has already resumed the goal; if a turn is running the+ // kickoff must queue (same as a typed `/goal resume`, slash.ts), not+ // read as a failure.+ const queued = queueKickoffIfSessionBusy({+ displayText: dispatch.display ?? undefined,+ sessionId,+ text: dispatch.message+ })++ if (queued !== 'idle') {+ const copy = queued === 'queued' ? ctrl.continuationQueued : ctrl.continuationBusy+ onFeedback(queued === 'queued' ? null : copy, queued === 'queued' ? copy : null)++ return queued === 'queued'+ }+const submitted = await onSubmit(dispatch.message, {displayKind: 'hidden',sessionId@@ -146,12 +163,12 @@ export const SessionControlGoalSection = memo(function SessionControlGoalSectiongoal.last_verdict === 'blocked'? s.goalBlocked: visibleState === 'waiting'- ? s.goalWaiting- : visibleState === 'paused'- ? s.goalPaused- : visibleState === 'done'- ? s.goalDone- : s.goalActive+ ? s.goalWaiting+ : visibleState === 'paused'+ ? s.goalPaused+ : visibleState === 'done'+ ? s.goalDone+ : s.goalActiveconst headerLabel =visibleState === 'done'diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control.tsxindex 6a498c85302..11d0eb5dc7e 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control.tsx@@ -33,7 +33,9 @@ export const SessionControlSections = memo(function SessionControlSections({setFeedbackSuccess(success)}, [])- const storeError = entry.error ? ctrl.actionFailed(entry.error) : null+ // Action failures arrive through onFeedback (which wins below); a store+ // error with no feedback is a read/hydration failure, not a failed action.+ const storeError = entry.error ? ctrl.controlUnavailable(entry.error) : nullconst displayError = feedbackError ?? (entry.error === dismissedStoreError ? null : storeError)const handleDismissError = useCallback(() => {diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.test.tsindex 6211e57b713..fb2d19bfc35 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.test.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-control.test.ts@@ -1,10 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import {- $sessionControlBySession,- resetSessionControlForTests,- type SessionControlSnapshot-} from '@/store/session-control'+import { $sessionControlBySession, clearAllSessionControl, type SessionControlSnapshot } from '@/store/session-control'import { handleControlEvent } from './session-control'import type { GatewayEventContext } from './types'@@ -34,7 +30,7 @@ function context(overrides: Partial<GatewayEventContext> = {}): GatewayEventContdescribe('handleControlEvent', () => {afterEach(() => {- resetSessionControlForTests()+ clearAllSessionControl()})it('does not claim non-control events', () => {diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.tsnew file mode 100644index 00000000000..e0f8edebe05--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/queue-if-busy.ts@@ -0,0 +1,45 @@+import { enqueueQueuedPrompt } from '@/store/composer-queue'+import { $sessions, resolveComposerSessionKey } from '@/store/session'+import { $sessionStates } from '@/store/session-states'++import { isTargetSessionBusy } from './utils'++export interface QueueIfBusyInput {+ /** Runtime session the command was resolved against. */+ sessionId: string+ /** Stored session the composer queue is keyed by; defaults to the runtime id+ * (or its published storedSessionId when known). */+ storedSessionId?: string | null+ /** Foreground busy flag — only consulted when there is no session id. */+ foregroundBusy?: boolean+ text: string+ displayText?: string+}++/**+ * When the target session is mid-turn, park a backend-produced kickoff on the+ * composer queue instead of dropping it. The backend has ALREADY executed the+ * command (a `/goal` is set, a goal is resumed) and `text` is the prompt that+ * tells the agent about it — losing it leaves the goal silently unheard+ * (#63352). Returns `'idle'` when the caller should submit normally, `'queued'`+ * when the prompt now waits on the queue, and `'busy'` when the session is+ * busy but nothing could be queued.+ */+export function queueKickoffIfSessionBusy({+ displayText,+ foregroundBusy = false,+ sessionId,+ storedSessionId,+ text+}: QueueIfBusyInput): 'busy' | 'idle' | 'queued' {+ const states = $sessionStates.get()++ if (!isTargetSessionBusy(states, sessionId, foregroundBusy)) {+ return 'idle'+ }++ const stored = storedSessionId ?? states[sessionId]?.storedSessionId ?? null+ const queueKey = resolveComposerSessionKey(stored, $sessions.get()) || stored || sessionId++ return enqueueQueuedPrompt(queueKey, { attachments: [], displayText, text }) ? 'queued' : 'busy'+}diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex a06b6b16430..a54a7bdfb6c 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@ -18,7 +18,6 @@ import { isMissingRpcMethod } from '@/lib/gateway-rpc'import { setSessionYolo } from '@/lib/yolo-session'import { openCommandPalettePage } from '@/store/command-palette'import { setComposerDraft } from '@/store/composer'-import { enqueueQueuedPrompt } from '@/store/composer-queue'import { applyGoalStatusText } from '@/store/goals'import { dismissNotification, notify, notifyError } from '@/store/notifications'import { setPetScale } from '@/store/pet-gallery'@@ -34,7 +33,6 @@ import {$connection,$sessions,$yoloActive,- resolveComposerSessionKey,setActiveSessionId,setCurrentUsage,setModelPickerOpen,@@ -61,11 +59,11 @@ import type {SlashExecResponse} from '../../../types'+import { queueKickoffIfSessionBusy } from './queue-if-busy'import { resolveTargetSessionId } from './resolve-target-session'import {type GatewayRequest,isSessionIdCandidate,- isTargetSessionBusy,renderCommandsCatalog,renderRpcResult,slashStatusText,@@ -345,25 +343,25 @@ export function useSlashCommand(deps: SlashCommandDeps) {// view's — see isTargetSessionBusy. `busyRef` mirrors whatever chat// is on screen, while this command runs against the session// resolveTargetSessionId picked, routinely a different one.- if (isTargetSessionBusy($sessionStates.get(), sessionId, busyRef.current)) {- // The backend already executed the command — for `/goal <text>`- // the goal is set and `message` is its kickoff prompt. Dropping- // it here loses the kickoff silently (the goal exists but the- // agent never hears about it, #63352). Queue it on the composer- // queue instead: it fires when the running turn settles, and the- // queue panel above the composer shows it in the meantime.- //- // Park it on the same stored session the output writer is bound to- // rather than re-reading the globals here — a session switch between- // dispatch and this branch would otherwise queue the kickoff on- // whichever chat is now in front.- const queueKey = resolveComposerSessionKey(storedSessionId, $sessions.get()) || storedSessionId || sessionId-- if (enqueueQueuedPrompt(queueKey, { attachments: [], text: message, displayText })) {- renderSlashOutput('session busy — message queued to send when the current turn finishes')- } else {- renderSlashOutput('session busy — /interrupt the current turn before sending this command')- }+ //+ // Parked on the same stored session the output writer is bound to+ // rather than re-reading the globals — a session switch between+ // dispatch and this branch would otherwise queue the kickoff on+ // whichever chat is now in front (#63352).+ const queued = queueKickoffIfSessionBusy({+ displayText,+ foregroundBusy: busyRef.current,+ sessionId,+ storedSessionId,+ text: message+ })++ if (queued !== 'idle') {+ renderSlashOutput(+ queued === 'queued'+ ? 'session busy — message queued to send when the current turn finishes'+ : 'session busy — /interrupt the current turn before sending this command'+ )return}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 6a24a791c98..1766b1765bd 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -91,6 +91,7 @@ import {setWorkspaceCwdOwner,setYoloActive} from '@/store/session'+import { clearSessionControl } from '@/store/session-control'import { isSessionOwnerResolutionError } from '@/store/session-owner-resolution'import {beginSessionMutation,@@ -2480,6 +2481,7 @@ export function useSessionActions({if (closingRuntimeId) {clearQueuedPrompts(closingRuntimeId)+ clearSessionControl(closingRuntimeId)}// A tiled copy of this session must not outlive it: collapse the panediff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 75d26ebcb30..c0f108b2dc6 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2078,6 +2078,9 @@ export const ar = defineLocale({copySuccess: 'تم نسخ المعيار إلى الحافظة',copyFailure: 'فشل نسخ المعيار إلى الحافظة',continuationFailed: 'فشل إرسال متابعة الهدف',+ continuationQueued: 'تم استئناف الهدف — المتابعة في قائمة الانتظار حتى انتهاء الدور الحالي',+ continuationBusy: 'تم استئناف الهدف — الجلسة مشغولة، نفّذ /interrupt للدور الحالي للمتابعة',+ controlUnavailable: msg => `عناصر تحكم الجلسة غير متاحة: ${msg}`,dismissError: 'تجاهل الخطأ',add: 'إضافة'},diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex a3c529d60cc..fb22b4ed983 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -2793,6 +2793,9 @@ export const en: Translations = {copySuccess: 'Criterion copied to clipboard',copyFailure: 'Failed to copy criterion to clipboard',continuationFailed: 'Failed to submit goal continuation',+ continuationQueued: 'Goal resumed — continuation queued until the current turn finishes',+ continuationBusy: 'Goal resumed — session busy, /interrupt the current turn to continue',+ controlUnavailable: msg => `Session controls unavailable: ${msg}`,dismissError: 'Dismiss error',add: 'Add'},diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 65767047a1a..024d272414e 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2405,6 +2405,7 @@ export const ja = defineLocale({heartbeatEveryHours: hours => `${hours}時間ごと`,heartbeatEverySeconds: seconds => `${seconds}秒ごと`,heartbeatNext: time => `次回 ${time}`,+ heartbeatDueWaitingForIdle: '期限到来 — アイドル待ち',heartbeatActions: 'ハートビートのアクション',pauseHeartbeat: 'ハートビートを一時停止',resumeHeartbeat: 'ハートビートを再開',@@ -2417,6 +2418,9 @@ export const ja = defineLocale({copySuccess: '基準をクリップボードにコピーしました',copyFailure: '基準のコピーに失敗しました',continuationFailed: 'ゴールの継続送信に失敗しました',+ continuationQueued: 'ゴールを再開しました — 継続は現在のターン終了後に送信されます',+ continuationBusy: 'ゴールを再開しました — セッションが実行中です。続行するには /interrupt してください',+ controlUnavailable: msg => `セッション制御を利用できません: ${msg}`,dismissError: 'エラーを閉じる',add: '追加'},diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex c43bee54593..f03597ba319 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -2816,6 +2816,7 @@ export const ru = defineLocale({heartbeatEveryHours: hours => `каждые ${hours}ч`,heartbeatEverySeconds: seconds => `каждые ${seconds}с`,heartbeatNext: time => `следующий ${time}`,+ heartbeatDueWaitingForIdle: 'пора — ожидание простоя',heartbeatActions: 'Действия пульса',pauseHeartbeat: 'Приостановить пульс',resumeHeartbeat: 'Возобновить пульс',@@ -2828,6 +2829,9 @@ export const ru = defineLocale({copySuccess: 'Критерий скопирован в буфер обмена',copyFailure: 'Не удалось скопировать критерий в буфер обмена',continuationFailed: 'Не удалось отправить продолжение цели',+ continuationQueued: 'Цель возобновлена — продолжение поставлено в очередь до конца текущего хода',+ continuationBusy: 'Цель возобновлена — сессия занята, выполните /interrupt, чтобы продолжить',+ controlUnavailable: msg => `Управление сессией недоступно: ${msg}`,dismissError: 'Скрыть ошибку',add: 'Добавить'},diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex c823289fd0b..08ab95ffbad 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2387,6 +2387,9 @@ export interface Translations {copySuccess: stringcopyFailure: stringcontinuationFailed: string+ continuationQueued: string+ continuationBusy: string+ controlUnavailable: (msg: string) => stringdismissError: stringadd: string}diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex f0fd9a28744..7d68fda36ad 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -2325,6 +2325,7 @@ export const zhHant = defineLocale({heartbeatEveryHours: hours => `每 ${hours} 小時`,heartbeatEverySeconds: seconds => `每 ${seconds} 秒`,heartbeatNext: time => `下次 ${time}`,+ heartbeatDueWaitingForIdle: '已到期 — 等待會話閒置',heartbeatActions: '活動訊號操作',pauseHeartbeat: '暫停活動訊號',resumeHeartbeat: '繼續活動訊號',@@ -2337,6 +2338,9 @@ export const zhHant = defineLocale({copySuccess: '已將條件複製到剪貼板',copyFailure: '複製條件到剪貼板失敗',continuationFailed: '提交目標延續內容失敗',+ continuationQueued: '目標已恢復 — 延續內容已排隊,將在目前回合結束後送出',+ continuationBusy: '目標已恢復 — 會話忙碌中,請 /interrupt 目前回合以繼續',+ controlUnavailable: msg => `會話控制無法使用: ${msg}`,dismissError: '關閉錯誤',add: '新增'},diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex e6c7d6d3ab1..db3473c0cb2 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -2957,6 +2957,9 @@ export const zh: Translations = {copySuccess: '已将条件复制到剪贴板',copyFailure: '复制条件到剪贴板失败',continuationFailed: '提交目标后续内容失败',+ continuationQueued: '目标已恢复 — 后续内容已排队,将在当前回合结束后发送',+ continuationBusy: '目标已恢复 — 会话正忙,请 /interrupt 当前回合以继续',+ controlUnavailable: msg => `会话控制不可用: ${msg}`,dismissError: '关闭错误',add: '添加'},diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.tsindex c241e00fef4..620b77ecff2 100644--- a/apps/desktop/src/store/gateway-switch.ts+++ b/apps/desktop/src/store/gateway-switch.ts@@ -23,6 +23,7 @@ import {setSessions,setSessionsLoading} from '@/store/session'+import { clearAllSessionControl } from '@/store/session-control'import { resetSessionPinMirror } from '@/store/session-pin-sync'import { clearAllSessionStates } from '@/store/session-states'import { clearTranscriptTails } from '@/store/transcript-tail-cache'@@ -206,6 +207,9 @@ export function wipeSessionListsForGatewaySwitch(): void {// that are still unread once the next gateway's lists load — so a profile// round-trip doesn't swallow green dots.clearAllSessionStates()+ // Structured goal/loop/heartbeat entries are keyed by runtime id, which the+ // next backend re-mints, so a full wipe is exact (and stale-response-safe).+ clearAllSessionControl()resetLiveRuntimeTracking()resetLiveSync()$unreadFinishedSessionIds.set([])diff --git a/apps/desktop/src/store/session-control.ts b/apps/desktop/src/store/session-control.tsindex 044bd2fb1ca..138503da803 100644--- a/apps/desktop/src/store/session-control.ts+++ b/apps/desktop/src/store/session-control.ts@@ -599,6 +599,7 @@ export function applySessionControlUpdate(sessionId: string, rawSnapshot: unknow})}+/** Drops one runtime session's entry when the session record is closed/deleted. */export function clearSessionControl(sessionId: string): void {if (!sessionId) {return@@ -615,34 +616,13 @@ export function clearSessionControl(sessionId: string): void {$sessionControlBySession.set(remaining)}-/** Lets an explicitly rebound gateway probe backends that were unsupported on its predecessor. */-export function resetSessionControlAfterGatewayRebind(): void {- const entries = $sessionControlBySession.get()- let changed = false- const nextEntries: Record<string, SessionControlEntry> = {}-- for (const [sessionId, entry] of Object.entries(entries)) {- advanceVersion(sessionId)-- const nextEntry: SessionControlEntry = {- ...entry,- capability: entry.capability === 'unsupported' ? 'unknown' : entry.capability,- error: null,- loading: false,- pendingAction: null- }-- nextEntries[sessionId] = nextEntry- changed ||= !sameEntry(entry, nextEntry)- }-- if (changed) {- $sessionControlBySession.set(nextEntries)- }-}--/** Narrow reset seam for tests; production reconnect behavior remains explicitly owned by its caller. */-export function resetSessionControlForTests(): void {+/**+ * Wipes every entry — the gateway-switch seam. Entries are keyed by runtime+ * session id and a different backend mints new ids, so nothing here can be+ * reused; in-flight reads/actions from the old backend are invalidated by the+ * version bump so a late response cannot repopulate the map.+ */+export function clearAllSessionControl(): void {for (const sessionId of new Set([...versions.keys(), ...Object.keys($sessionControlBySession.get())])) {advanceVersion(sessionId)}