The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): retain access to past tasks after turns
Xiponge0bc2c1ce940
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-status-presence.ts b/apps/desktop/src/app/chat/composer/hooks/use-status-presence.tsindex b2c059ba353..0cb66db1ce5 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-status-presence.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-status-presence.ts@@ -4,6 +4,7 @@ import { $composerActionsBySession } from '@/store/composer-actions'import { $statusItemsBySession } from '@/store/composer-status'import { $previewStatusBySession } from '@/store/preview-status'import { $sessionControlBySession } from '@/store/session-control'+import { $retainedTodosBySession } from '@/store/todos'/** Structural view of the per-session feeds — they hold different item* types, and all this hook needs from each is "does this key have rows". */@@ -15,7 +16,11 @@ interface PresenceFeed {const FEEDS: PresenceFeed[] = [$statusItemsBySession, $composerActionsBySession, $previewStatusBySession]const subscribe = (onChange: () => void) => {- const offs = [...FEEDS.map(feed => feed.listen(onChange)), $sessionControlBySession.listen(onChange)]+ const offs = [+ ...FEEDS.map(feed => feed.listen(onChange)),+ $sessionControlBySession.listen(onChange),+ $retainedTodosBySession.listen(onChange)+ ]return () => {for (const off of offs) {@@ -35,7 +40,7 @@ const subscribe = (onChange: () => void) => {* OTHER sessions. The boolean snapshot bails out of all of that, re-rendering* only on the actual show/hide transition.*/-export function useSessionStatusPresence(sessionId: string | null): boolean {+export function useSessionStatusPresence(sessionId: string | null, busy = false): boolean {return useSyncExternalStore(subscribe, () => {if (!sessionId) {return false@@ -45,6 +50,10 @@ export function useSessionStatusPresence(sessionId: string | null): boolean {return true}+ if (!busy && ($retainedTodosBySession.get()[sessionId]?.length ?? 0) > 0) {+ return true+ }+const control = $sessionControlBySession.get()[sessionId]return Boolean(diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsxindex 5daa5d647d7..bcc5685ed12 100644--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@ -231,7 +231,7 @@ export function ChatBar({// Coarse edge: re-renders ChatBar only when the stack shows/hides, NOT on// every per-item status mutation or other sessions' churn (see the hook).- const statusPresent = useSessionStatusPresence(statusSessionId)+ const statusPresent = useSessionStatusPresence(statusSessionId, busy)// Publishes contributed micro actions for this session; the status stack// renders them as the pill strip at the top of the overlay lane.diff --git a/apps/desktop/src/app/chat/composer/status-stack/default-collapse.test.tsx b/apps/desktop/src/app/chat/composer/status-stack/default-collapse.test.tsxindex b6487038a59..4f19e568423 100644--- a/apps/desktop/src/app/chat/composer/status-stack/default-collapse.test.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/default-collapse.test.tsx@@ -6,7 +6,7 @@ import { $backgroundStatusBySession } from '@/store/composer-status'import { $goalsBySession } from '@/store/goals'import { $sessionControlBySession } from '@/store/session-control'import { $subagentsBySession, upsertSubagent } from '@/store/subagents'-import { $todosBySession } from '@/store/todos'+import { $todosBySession, clearSessionTodos, restoreSessionTodosFromSnapshot } from '@/store/todos'import { QueuePanel } from '../queue-panel'@@ -40,6 +40,29 @@ afterEach(() => {$sessionControlBySession.set({})$subagentsBySession.set({})$todosBySession.set({})+ clearSessionTodos('owner')+})++it('offers a collapsed read-only checklist from an idle session, without a running spinner', () => {+ restoreSessionTodosFromSnapshot(+ 'owner',+ {+ revision: 3,+ todos: [+ { id: 'one', content: 'Already done', status: 'completed' },+ { id: 'two', content: 'Still open', status: 'in_progress' }+ ]+ },+ false+ )+ render(stack())++ const review = screen.getByRole('button', { name: /Previous tasks 1\/2/ })+ expect(review.getAttribute('aria-expanded')).toBe('false')+ expect(screen.queryByText('Still open')).toBeNull()+ fireEvent.click(review)+ expect(screen.getByText('Still open')).toBeTruthy()+ expect(screen.queryByLabelText('Running')).toBeNull()})it('auto-expands only todos and keeps other groups closed as activity arrives', () => {diff --git a/apps/desktop/src/app/chat/composer/status-stack/index.tsx b/apps/desktop/src/app/chat/composer/status-stack/index.tsxindex 8f9da916d52..05a8dfcb7cc 100644--- a/apps/desktop/src/app/chat/composer/status-stack/index.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/index.tsx@@ -17,6 +17,7 @@ import { Codicon } from '@/components/ui/codicon'import { GlyphSpinner } from '@/components/ui/glyph-spinner'import { Tip, TipKeybindLabel } from '@/components/ui/tooltip'import { type Translations, useI18n } from '@/i18n'+import { todoTree } from '@/lib/todos'import { useSessionSlice, useStoreSelector } from '@/lib/use-session-slice'import { cn } from '@/lib/utils'import { $billingBlock } from '@/store/billing-block'@@ -34,6 +35,7 @@ import { $interfaceMode, shownInMode, type Tiered } from '@/store/interface-modeimport { $previewStatusBySession, dismissPreviewArtifact } from '@/store/preview-status'import { $sessionControlBySession, refreshSessionControl } from '@/store/session-control'import { $threadScrolledUpBySession } from '@/store/thread-scroll'+import { $retainedTodosBySession } from '@/store/todos'import { openSessionInNewWindow } from '@/store/windows'import { PreviewStatusRow } from './preview-row'@@ -121,6 +123,8 @@ export function ComposerStatusStack({ onSubmit, queue, sessionId }: ComposerStat// across unrelated writes, so the slice hook bails out unless OUR session's// items actually changed.const items = useSessionSlice($statusItemsBySession, sessionId)+ const retainedTodos = useSessionSlice($retainedTodosBySession, sessionId)+ const busy = useStore(useSessionView().$busy)const previews = useSessionSlice($previewStatusBySession, sessionId)const controlEntry = useSessionValue($sessionControlBySession, sessionId)@@ -293,6 +297,37 @@ export function ComposerStatusStack({ onSubmit, queue, sessionId }: ComposerStat})}+ // A settled snapshot is reviewable but never re-enters the live progress+ // feed. Only show this disclosure once the live Todo section has retired.+ if (!busy && retainedTodos.length > 0 && !groups.some(group => group.type === 'todo')) {+ const done = retainedTodos.filter(todo => todo.status === 'completed').length+ sections.push({+ key: 'retained-todo',+ node: (+ <StatusSection+ defaultCollapsed+ icon={<Codicon className="text-muted-foreground/70" name="checklist" size="0.8rem" />}+ label={t.statusStack.previousTodos(done, retainedTodos.length)}+ >+ {todoTree(retainedTodos).map(([todo, depth]) => (+ <StatusItemRow+ historical+ item={{+ depth,+ id: `retained-todo:${todo.id}`,+ state: 'done',+ title: todo.content,+ todoStatus: todo.status,+ type: 'todo'+ }}+ key={todo.id}+ />+ ))}+ </StatusSection>+ )+ })+ }+if (queue) {sections.push({ key: 'queue', node: queue })}diff --git a/apps/desktop/src/app/chat/composer/status-stack/status-row.tsx b/apps/desktop/src/app/chat/composer/status-stack/status-row.tsxindex 56ee644f03c..d951d9a0926 100644--- a/apps/desktop/src/app/chat/composer/status-stack/status-row.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/status-row.tsx@@ -23,7 +23,7 @@ const TODO_GLYPHS: Record<Exclude<TodoStatus, 'in_progress' | 'pending'>, { icon// Left slot: braille spinner while running, otherwise a small status dot// (green = done, red = failed) so the slot is always filled and rows align.-function leadingGlyph(item: ComposerStatusItem, s: Translations['statusStack']): ReactNode {+function leadingGlyph(item: ComposerStatusItem, s: Translations['statusStack'], historical = false): ReactNode {if (item.type === 'goal') {if (item.goalStatus === 'paused') {return <Codicon className="text-muted-foreground/60" name="debug-pause" size="0.8rem" />@@ -42,7 +42,7 @@ function leadingGlyph(item: ComposerStatusItem, s: Translations['statusStack']):)}- if (item.todoStatus === 'pending') {+ if (item.todoStatus === 'pending' || (historical && item.todoStatus === 'in_progress')) {return <StatusPendingIcon />}@@ -72,6 +72,8 @@ function leadingGlyph(item: ComposerStatusItem, s: Translations['statusStack']):interface StatusItemRowProps {item: ComposerStatusItem+ /** Render a retained, non-running task snapshot. */+ historical?: boolean/** Clear a finished background task from the stack. */onDismiss?: (id: string) => void/** Open the subagent's own session window, livestreamed by the gateway's@@ -86,7 +88,13 @@ interface StatusItemRowProps {* Memoised + keyed by id so parent re-renders never remount it (the spinner* keeps ticking instead of resetting).*/-export const StatusItemRow = memo(function StatusItemRow({ item, onDismiss, onOpen, onStop }: StatusItemRowProps) {+export const StatusItemRow = memo(function StatusItemRow({+ historical = false,+ item,+ onDismiss,+ onOpen,+ onStop+}: StatusItemRowProps) {const { t } = useI18n()const s = t.statusStackconst failed = item.state === 'failed'@@ -110,7 +118,7 @@ export const StatusItemRow = memo(function StatusItemRow({ item, onDismiss, onOp<StatusRowdepth={Math.min(item.depth ?? 0, 4)}dismiss={action ? { label: action.label, onDismiss: action.onClick } : undefined}- leading={leadingGlyph(item, s)}+ leading={leadingGlyph(item, s, historical)}onActivate={onActivate}trailing={canOpen ? (diff --git a/apps/desktop/src/app/contrib/hooks/completed-reply-refresh.test.tsx b/apps/desktop/src/app/contrib/hooks/completed-reply-refresh.test.tsxindex f554c8b084a..033a7f3a3fe 100644--- a/apps/desktop/src/app/contrib/hooks/completed-reply-refresh.test.tsx+++ b/apps/desktop/src/app/contrib/hooks/completed-reply-refresh.test.tsx@@ -24,7 +24,13 @@ import {setSelectedStoredSessionId} from '@/store/session'import { $sessionStates, $sessionTiles, clearAllSessionStates } from '@/store/session-states'-import { $todosBySession, clearSessionTodos, setSessionTodos } from '@/store/todos'+import {+ $retainedTodosBySession,+ $todosBySession,+ clearSessionTodos,+ restoreSessionTodosFromSnapshot,+ setSessionTodos+} from '@/store/todos'import type { SessionMessage } from '@/types/hermes'import {@@ -234,6 +240,88 @@ afterEach(() => {vi.restoreAllMocks()})+it('keeps an idle Todo snapshot for review when post-turn history refresh clears the live panel', async () => {+ const todos = [{ id: 'next', content: 'Next task', status: 'in_progress' as const }]++ const saved: SessionMessage[] = [+ ...history,+ {+ id: 4,+ role: 'assistant',+ content: '',+ timestamp: 4,+ tool_calls: [{ id: 'todo-call', type: 'function', function: { name: 'todo_list', arguments: '{}' } }]+ },+ {+ id: 5,+ role: 'tool',+ content: JSON.stringify({ todos, revision: 3 }),+ timestamp: 5,+ tool_call_id: 'todo-call',+ tool_name: 'todo_list'+ },+ { id: 6, role: 'assistant', content: FINAL, timestamp: 6 }+ ]++ render(<Harness />)+ act(() => restoreSessionTodosFromSnapshot(RUNTIME, { todos, revision: 3 }, false))+ expect($retainedTodosBySession.get()[RUNTIME]).toEqual(todos)+ vi.mocked(getLatestSessionMessages).mockResolvedValueOnce({ session_id: STORED, messages: saved })++ await act(async () => {+ await hydrateStoredSessionTranscript({+ attempts: 1,+ storedSessionId: STORED,+ runtimeSessionId: RUNTIME,+ storedProfile: 'default',+ updateSessionState: cache.updateSessionState+ })+ })+ expect($todosBySession.get()[RUNTIME]).toBeUndefined()+ expect($retainedTodosBySession.get()[RUNTIME]).toEqual(todos)++ // Deferred Desktop resumes initially return no todo_state. The subsequent+ // persisted transcript fetch must provide the same read-only list by itself.+ act(() => clearSessionTodos(RUNTIME))+ vi.mocked(getLatestSessionMessages).mockResolvedValueOnce({ session_id: STORED, messages: saved })+ await act(async () => {+ await hydrateStoredSessionTranscript({+ attempts: 1,+ storedSessionId: STORED,+ runtimeSessionId: RUNTIME,+ storedProfile: 'default',+ updateSessionState: cache.updateSessionState+ })+ })+ expect($retainedTodosBySession.get()[RUNTIME]).toEqual(todos)++ // A legacy unversioned empty result is still an explicit clear. An older+ // revisioned snapshot must not keep the previous button pinned.+ const cleared: SessionMessage[] = [+ ...saved,+ {+ id: 7,+ role: 'assistant',+ content: '',+ timestamp: 7,+ tool_calls: [{ id: 'clear-call', type: 'function', function: { name: 'todo_list', arguments: '{"todos":[]}' } }]+ },+ { id: 8, role: 'tool', content: '{"todos":[]}', timestamp: 8, tool_call_id: 'clear-call', tool_name: 'todo_list' }+ ]++ vi.mocked(getLatestSessionMessages).mockResolvedValueOnce({ session_id: STORED, messages: cleared })+ await act(async () => {+ await hydrateStoredSessionTranscript({+ attempts: 1,+ storedSessionId: STORED,+ runtimeSessionId: RUNTIME,+ storedProfile: 'default',+ updateSessionState: cache.updateSessionState+ })+ })+ expect($retainedTodosBySession.get()[RUNTIME]).toBeUndefined()+})+it.each([false, true])('rejects a history read spanning a completed turn, then accepts fresh history (tile: %s)',async tile => {diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.tsindex 5b9c99ea627..109ff86c9df 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts@@ -11,7 +11,7 @@ import { getLatestSessionMessages, type ProfileScope } from '@/hermes'import { type ChatMessage, preserveLocalAssistantErrors, sealOpenToolParts, toChatMessages } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'import { sessionMessagesSignature } from '@/lib/session-signatures'-import { latestSessionTodos } from '@/lib/todos'+import { latestSessionTodos, latestSessionTodoSnapshot } from '@/lib/todos'import { pendingSessionReplay } from '@/store/gateway'import { $sidebarShowArchived } from '@/store/layout'import { $changeEventsAvailable, $cronChangeTick, $projectsChangeTick, $sessionsChangeTick } from '@/store/live-sync'@@ -39,7 +39,13 @@ import {setSessionStalled} from '@/store/session-states'import { loadArchivedSessions } from '@/store/sidebar-archive'-import { clearSessionTodos, setSessionTodos, todosForHydration } from '@/store/todos'+import {+ clearActiveSessionTodos,+ clearSessionTodos,+ restoreSessionTodosFromSnapshot,+ setSessionTodos,+ todosForHydration+} from '@/store/todos'import type { ClientSessionState } from '../../types'import type { GatewayRequester } from '../types'@@ -396,12 +402,27 @@ export async function hydrateStoredSessionTranscript({}),storedSessionId)- const restored = todosForHydration(latestSessionTodos(messages))+ const snapshot = latestSessionTodoSnapshot(messages)++ if (snapshot) {+ // Deferred Desktop resume sends no todo_state on its initial ACK.+ // The persisted tool result is the first authoritative snapshot.+ restoreSessionTodosFromSnapshot(runtimeSessionId, snapshot, false)+ }- if (restored) {+ const latestTodos = latestSessionTodos(messages)+ const restored = todosForHydration(latestTodos)++ if (latestTodos?.length === 0) {+ // An explicit empty result retires the list; missing paged history does not.+ // A valid older snapshot must not mask a newer legacy clear without a revision.+ if (!snapshot || snapshot.todos.length > 0) {+ clearSessionTodos(runtimeSessionId)+ }+ } else if (restored) {setSessionTodos(runtimeSessionId, restored)} else {- clearSessionTodos(runtimeSessionId)+ clearActiveSessionTodos(runtimeSessionId)}returndiff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex f12f251593a..df82a8cf02e 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx@@ -92,6 +92,7 @@ import {sessionTileOwnerRoute} from '@/store/session-states'import { $sessionSeenCounts, $unreadFinishedMarkers } from '@/store/session-unread'+import { $retainedTodosBySession, clearSessionTodos } from '@/store/todos'import { loadTranscriptTail, saveTranscriptTail } from '@/store/transcript-tail-cache'import sessionResumeActiveTurn from '../../../../../../tests/fixtures/session-resume-active-turn.json'@@ -1145,6 +1146,7 @@ describe('resumeSession failure recovery', () => {$removedSessionIds.set(new Set())$sessionMutationsInFlight.set(new Set())clearClarifyRequest()+ clearSessionTodos('runtime-1')vi.restoreAllMocks()})@@ -1517,6 +1519,52 @@ describe('resumeSession failure recovery', () => {expect(resumedState?.turnStartedAt).toBe(1_700_000_000_000)})+ it('restores a paused checklist from REST when deferred resume has no todo_state', async () => {+ const todos = [{ id: 'next', content: 'Next task', status: 'in_progress' as const }]+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: 'stored-1',+ messages: [+ { id: 1, role: 'user', content: 'Work through the list', timestamp: 1 },+ {+ id: 2,+ role: 'assistant',+ content: '',+ timestamp: 2,+ tool_calls: [{ id: 'todo-call', type: 'function', function: { name: 'todo_list', arguments: '{}' } }]+ },+ {+ id: 3,+ role: 'tool',+ tool_call_id: 'todo-call',+ tool_name: 'todo_list',+ content: JSON.stringify({ todos, revision: 3 }),+ timestamp: 3+ },+ { id: 4, role: 'assistant', content: 'Continuing later', timestamp: 4 }+ ]+ } as never)++ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'session.resume') {+ return {+ session_id: 'runtime-1',+ session_key: 'stored-1',+ resumed: 'stored-1',+ messages_omitted: true,+ messages: [],+ message_count: 4,+ running: false,+ info: {}+ } as never+ }++ return {} as never+ })++ await runResume(requestGateway)+ expect($retainedTodosBySession.get()['runtime-1']).toEqual(todos)+ })+it('preserves a runtime-cache delta that arrives while cold resume waits for REST', async () => {const persisted = deferred<Awaited<ReturnType<typeof getLatestSessionMessages>>>()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 9dca0a39922..fbf69bbccbf 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@@ -30,6 +30,7 @@ import {import { markReasoningEffortPending } from '@/lib/chat-runtime'import { isMissingRpcMethod } from '@/lib/gateway-rpc'import { recoverInFlightTurnJournal } from '@/lib/inflight-turn-journal'+import { latestSessionTodoSnapshot } from '@/lib/todos'import { setSessionYolo } from '@/lib/yolo-session'import { $clarifyRequests } from '@/store/clarify'import { announceGoneSessionDraft, announceNewSessionDraftKey, migrateSessionDraft } from '@/store/composer'@@ -1712,6 +1713,14 @@ export function useSessionActions({clearedClarifyProjection?.messages ??activatedMessages+ if (!running) {+ restoreSessionTodosFromSnapshot(+ cachedRuntimeId,+ latestSessionTodoSnapshot(visibleActivatedMessages),+ false+ )+ }+releaseTranscriptView()const reconcileActivatedState = (state: ClientSessionState): ClientSessionState => {@@ -2064,6 +2073,14 @@ export function useSessionActions({restoreSessionTodosFromSnapshot(resumed.session_id, resumed.todo_state, resumedRunning)+ if (!resumedRunning && prefetchApplied && prefetchMatchesResumedSession && prefetchedTranscriptMessages) {+ restoreSessionTodosFromSnapshot(+ resumed.session_id,+ latestSessionTodoSnapshot(prefetchedTranscriptMessages),+ false+ )+ }+// Crash-survivable turn progress: fold a journaled in-flight tail// (persisted by use-session-state-cache while the turn streamed;// survives renderer/app death) back onto the restored transcript. Thediff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex b9bf8982663..808507e2313 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2444,6 +2444,7 @@ export const ar = defineLocale({goalWaiting: 'الهدف قيد الانتظار',subagents: count => `${count} ${count === 1 ? 'وكيل فرعي' : 'وكيل فرعي'}`,todos: (done, total) => `المهام ${done}/${total}`,+ previousTodos: (done, total) => `المهام السابقة ${done}/${total}`,running: 'قيد التشغيل',stop: 'إيقاف',dismiss: 'تجاهل',diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.tsindex 9d496680f03..1bcfa2ab51d 100644--- a/apps/desktop/src/i18n/de.ts+++ b/apps/desktop/src/i18n/de.ts@@ -4384,6 +4384,7 @@ export const deOverrides = {goalWaiting: 'Ziel wartet',subagents: count => `${count} Subagent${count === 1 ? '' : 'en'}`,todos: (done, total) => `Aufgaben ${done}/${total}`,+ previousTodos: (done, total) => `Frühere Aufgaben ${done}/${total}`,running: 'Läuft',stop: 'Stopp',dismiss: 'Verwerfen',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex d205b5a880b..ec5796fb42b 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3998,6 +3998,7 @@ export const en: Translations = {goalWaiting: 'Goal waiting',subagents: count => `${count} Subagent${count === 1 ? '' : 's'}`,todos: (done, total) => `Tasks ${done}/${total}`,+ previousTodos: (done, total) => `Previous tasks ${done}/${total}`,running: 'Running',stop: 'Stop',dismiss: 'Dismiss',diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.tsindex a416a02055d..cfc51866b27 100644--- a/apps/desktop/src/i18n/es.ts+++ b/apps/desktop/src/i18n/es.ts@@ -4374,6 +4374,7 @@ export const esOverrides = {goalWaiting: 'Objetivo esperando',subagents: count => `${count} subagente${count === 1 ? '' : 's'}`,todos: (done, total) => `Tareas ${done}/${total}`,+ previousTodos: (done, total) => `Tareas anteriores ${done}/${total}`,running: 'En ejecución',stop: 'Detener',dismiss: 'Descartar',diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.tsindex a1c536c60cd..f3bf23576f1 100644--- a/apps/desktop/src/i18n/fr.ts+++ b/apps/desktop/src/i18n/fr.ts@@ -4396,6 +4396,7 @@ export const frOverrides = {goalWaiting: 'Objectif en attente',subagents: count => `${count} sous-agent${count === 1 ? '' : 's'}`,todos: (done, total) => `Tâches ${done}/${total}`,+ previousTodos: (done, total) => `Tâches précédentes ${done}/${total}`,running: 'En cours',stop: 'Arrêter',dismiss: 'Rejeter',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex fabbc7a04cd..f61886162e7 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2862,6 +2862,7 @@ export const ja = defineLocale({goalWaiting: '目標待機中',subagents: count => `サブエージェント ${count} 件`,todos: (done, total) => `タスク ${done}/${total}`,+ previousTodos: (done, total) => `以前のタスク ${done}/${total}`,running: '実行中',stop: '停止',dismiss: '閉じる',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 975e1b71b81..84d0f9b7f5d 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -3101,6 +3101,7 @@ export const ru = defineLocale({goalWaiting: 'Цель ожидает',subagents: count => `${count} ${RU_PLURAL(count, 'субагент', 'субагента', 'субагентов')}`,todos: (done, total) => `Задачи ${done}/${total}`,+ previousTodos: (done, total) => `Прошлые задачи ${done}/${total}`,running: 'Выполняется',stop: 'Стоп',dismiss: 'Скрыть',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex f3841d11e2c..16dd7fb03be 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -3305,6 +3305,7 @@ export interface Translations {goalWaiting: stringsubagents: (count: number) => stringtodos: (done: number, total: number) => string+ previousTodos: (done: number, total: number) => stringrunning: stringstop: stringdismiss: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex cad566a8098..6055b6c6094 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -3072,6 +3072,7 @@ export const zhHant = defineLocale({goalWaiting: '目標等待中',subagents: count => `${count} 個子代理`,todos: (done, total) => `任務 ${done}/${total}`,+ previousTodos: (done, total) => `先前任務 ${done}/${total}`,running: '執行中',stop: '停止',dismiss: '關閉',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 0cb9214797c..7b309d09ad7 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3770,6 +3770,7 @@ export const zh = defineLocale({goalWaiting: '目标等待中',subagents: count => `${count} 个子代理`,todos: (done, total) => `任务 ${done}/${total}`,+ previousTodos: (done, total) => `以往任务 ${done}/${total}`,running: '运行中',stop: '停止',dismiss: '关闭',diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.tsindex 22556c1f8fe..b01afb7a1c2 100644--- a/apps/desktop/src/lib/chat-messages/hydration.ts+++ b/apps/desktop/src/lib/chat-messages/hydration.ts@@ -2,6 +2,7 @@ import { skillInvocationText } from '@hermes/shared'import { extractImageRefs } from '@/lib/embedded-images'import { dedupeGeneratedImageEchoesInParts } from '@/lib/generated-images'+import { isTodoToolName } from '@/lib/todos'import type { MessageReaction, SessionMessage } from '@/types/hermes'import {@@ -286,6 +287,37 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {// (see ChatMessage.serverRowSpan).let pendingToolRows = 0let activeAssistantIndex: null | number = null+ // Todo history is stateful. Only a result from the nearest prior assistant+ // call in this turn may update it; a display-only orphan can still render.+ let nearestAssistant: null | SessionMessage = null++ const pairedTodoResult = (toolMessage: SessionMessage): boolean => {+ const id = toolMessage.tool_call_id++ if (!id || !Array.isArray(nearestAssistant?.tool_calls)) {+ return false+ }++ return nearestAssistant.tool_calls.some((call, index) => {+ const part = toolPartFromStoredCall(call, index)++ if (part.type !== 'tool-call' || part.toolCallId !== id) {+ return false+ }++ if (isTodoToolName(part.toolName)) {+ return true+ }++ const args = part.args as { calls?: unknown }++ return (+ part.toolName === 'tool_call' &&+ Array.isArray(args?.calls) &&+ args.calls.some(inner => inner && typeof inner === 'object' && isTodoToolName(inner.name))+ )+ })+ }const clearPendingTools = () => {pendingToolParts = []@@ -348,7 +380,21 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {}messages.forEach((message, index) => {+ if (message.role === 'assistant') {+ nearestAssistant = message+ } else if (message.role === 'user' || message.role === 'system') {+ nearestAssistant = null+ }+if (message.role === 'tool') {+ if (isTodoToolName(message.tool_name) && !pairedTodoResult(message)) {+ pendingToolParts = [...pendingToolParts, storedToolMessagePart(message, index)]+ pendingToolTimestamp ??= message.timestamp+ pendingToolRows += 1++ return+ }+const updatedPendingToolParts = applyStoredToolResultToParts(pendingToolParts, message)if (updatedPendingToolParts) {diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.tsindex 2ab4b77ebf6..33d29107778 100644--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts@@ -865,6 +865,7 @@ export function applyStoredToolResultToParts(next[partIndex] = {...existing,completedAt: toolMessage.timestamp,+ storedResultToolName: toolName,result: parseStoredToolResult(content),toolResultMetadata: storedToolResultMetadata(toolMessage),isError: false@@ -888,6 +889,7 @@ export function storedToolMessagePart(toolMessage: SessionMessage, fallbackIndextype: 'tool-call',toolCallId: toolMessage.tool_call_id || `stored-tool-message-${fallbackIndex}`,toolName: name,+ unpairedStoredToolResult: true,args: args as never,argsText: Object.keys(args).length ? JSON.stringify(args) : '',timestamp: toolMessage.timestamp,diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.tsindex 970bb04195b..e09b9075795 100644--- a/apps/desktop/src/lib/chat-messages/types.ts+++ b/apps/desktop/src/lib/chat-messages/types.ts@@ -17,6 +17,11 @@ export interface TimelinePartMetadata {/** Raw streamed text behind a `text` part whose MEDIA tags are already rendered,* so the next delta re-renders from the source instead of the render. */mediaSource?: string+ /** Stored tool result without a matching assistant call in the loaded page.+ * Render for history, but never treat it as authoritative Todo state. */+ unpairedStoredToolResult?: boolean+ /** Actual completed tool name when the assistant called a wrapper such as tool_call. */+ storedResultToolName?: string/** Durable source occurrence, even when several backend rows share a bubble. */sourceRowId?: number}diff --git a/apps/desktop/src/lib/todos.test.ts b/apps/desktop/src/lib/todos.test.tsindex dbb5c9e97e9..936082c3b47 100644--- a/apps/desktop/src/lib/todos.test.ts+++ b/apps/desktop/src/lib/todos.test.ts@@ -1,7 +1,9 @@import { describe, expect, it } from 'vitest'+import { toChatMessages } from './chat-messages'import {latestSessionTodos,+ latestSessionTodoSnapshot,mergeTodoItems,nextTodosFromToolEvent,parseTodoPatch,@@ -100,6 +102,52 @@ describe('parseTodoRevision', () => {})})+describe('latestSessionTodoSnapshot', () => {+ it('reads a persisted tool_call wrapper result and ignores a later unpaired tool row', () => {+ const valid = { todos: [{ content: 'Draft', id: 'a', status: 'pending' }], revision: 3 }++ const raw = [+ {+ role: 'assistant' as const,+ content: '',+ tool_calls: [+ {+ id: 'batch-1',+ function: {+ name: 'tool_call',+ arguments: JSON.stringify({ calls: [{ name: 'todo_list', arguments: {} }] })+ }+ }+ ]+ },+ { role: 'tool' as const, tool_call_id: 'batch-1', tool_name: 'todo_list', content: JSON.stringify(valid) }+ ]++ expect(latestSessionTodoSnapshot(toChatMessages(raw))).toEqual(valid)++ const withForgedResult = toChatMessages([+ ...raw,+ { role: 'user', content: 'Unrelated turn' },+ {+ role: 'tool',+ tool_call_id: 'unpaired',+ tool_name: 'todo_list',+ content: JSON.stringify({ todos: [], revision: 99 })+ }+ ])++ expect(latestSessionTodoSnapshot(withForgedResult)).toEqual(valid)++ const forgedAcrossTurn = toChatMessages([+ raw[0],+ { role: 'user', content: 'A new turn without a Todo write' },+ { role: 'tool', tool_call_id: 'batch-1', tool_name: 'todo_list', content: JSON.stringify(valid) }+ ])++ expect(latestSessionTodoSnapshot(forgedAcrossTurn)).toBeNull()+ })+})+describe('latestSessionTodos', () => {const todoPart = (todos: unknown, extra: Record<string, unknown> = {}) => ({type: 'tool-call',diff --git a/apps/desktop/src/lib/todos.ts b/apps/desktop/src/lib/todos.tsindex 61beaf2b4dd..a08020a47c2 100644--- a/apps/desktop/src/lib/todos.ts+++ b/apps/desktop/src/lib/todos.ts@@ -258,6 +258,56 @@ export function todosFromMessageContent(content: unknown): null | TodoItem[] {return latest}+/** Latest completed Todo result; arguments alone are never durable evidence. */+function isConfirmedTodoResultPart(part: Record<string, unknown>): boolean {+ if (part.unpairedStoredToolResult === true) {+ return false+ }++ if (isTodoToolName(part.toolName)) {+ return part.storedResultToolName === undefined || isTodoToolName(part.storedResultToolName)+ }++ if (part.toolName !== 'tool_call' || !isRecord(part.args)) {+ return false+ }++ return (+ isTodoToolName(part.storedResultToolName) &&+ Array.isArray(part.args.calls) &&+ part.args.calls.some(call => isRecord(call) && isTodoToolName(call.name))+ )+}++export function latestSessionTodoSnapshot(+ messages: readonly { parts?: unknown }[]+): null | { todos: TodoItem[]; revision: number } {+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ const parts = messages[i]?.parts++ if (!Array.isArray(parts)) {+ continue+ }++ for (let j = parts.length - 1; j >= 0; j -= 1) {+ const part = parts[j]++ if (!isRecord(part) || part.type !== 'tool-call' || !isConfirmedTodoResultPart(part)) {+ continue+ }++ const todos = parseTodos(part.result)+ const revision = parseTodoRevision(part.result)++ if (todos !== null && revision !== null) {+ return { todos, revision }+ }+ }+ }++ return null+}+/** Current todo state for a whole transcript — the last list wins. */export function latestSessionTodos(messages: readonly { parts?: unknown }[]): null | TodoItem[] {for (let i = messages.length - 1; i >= 0; i -= 1) {diff --git a/apps/desktop/src/store/gateway-switch.test.ts b/apps/desktop/src/store/gateway-switch.test.tsindex 7b3e960b271..b6cf8a18230 100644--- a/apps/desktop/src/store/gateway-switch.test.ts+++ b/apps/desktop/src/store/gateway-switch.test.ts@@ -23,6 +23,7 @@ import {setSessionsLoading} from '@/store/session'import { $stalledSessionIds } from '@/store/session-states'+import { $retainedTodosBySession, restoreSessionTodosFromSnapshot } from '@/store/todos'import {$transcriptTailBySessionId,clearTranscriptTailPaging,@@ -79,8 +80,18 @@ describe('wipeSessionListsForGatewaySwitch', () => {})it('clears lists and arms loading so sidebar skeletons retrigger', () => {+ restoreSessionTodosFromSnapshot(+ 's1',+ {+ revision: 2,+ todos: [{ id: 'task', content: 'Old gateway task', status: 'in_progress' }]+ },+ false+ )wipeSessionListsForGatewaySwitch()+ expect($retainedTodosBySession.get().s1).toBeUndefined()+expect($sessions.get()).toEqual([])expect($sessionProfilesTruncated.get()).toEqual({})expect($cronSessions.get()).toEqual([])diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.tsindex 6bbd337657f..bbb0f938a9f 100644--- a/apps/desktop/src/store/gateway-switch.ts+++ b/apps/desktop/src/store/gateway-switch.ts@@ -31,6 +31,7 @@ import {import { clearAllSessionControl } from '@/store/session-control'import { resetSessionPinMirror } from '@/store/session-pin-sync'import { clearAllSessionStates } from '@/store/session-states'+import { clearAllSessionTodos } from '@/store/todos'import { clearTranscriptTailPaging } from '@/store/transcript-tail'import { clearTranscriptTails } from '@/store/transcript-tail-cache'@@ -216,6 +217,9 @@ export function wipeSessionListsForGatewaySwitch(): void {// session-unread.ts are keyed by durable session id and repaint the rows// that are still unread once the next gateway's lists load — so a profile// round-trip doesn't swallow green dots.+ // Runtime ids can be reused by the next backend. Retire both the live+ // checklist and its review snapshot before any new session is bound.+ clearAllSessionTodos()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).diff --git a/apps/desktop/src/store/todos.test.ts b/apps/desktop/src/store/todos.test.tsindex c427562a064..29a67419fba 100644--- a/apps/desktop/src/store/todos.test.ts+++ b/apps/desktop/src/store/todos.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { TodoItem } from '@/lib/todos'import {+ $retainedTodosBySession,$todoRevisionsBySession,$todosBySession,clearActiveSessionTodos,@@ -148,6 +149,20 @@ describe('revisioned snapshots', () => {expect($todosBySession.get().s1?.[0]?.id).toBe('active')})+ it('keeps an idle snapshot available for review without reviving live work', () => {+ const saved = [todo('a', 'completed'), todo('b', 'in_progress')]+ restoreSessionTodosFromSnapshot('s1', { revision: 7, todos: saved }, false)++ expect($todosBySession.get().s1).toBeUndefined()+ expect($retainedTodosBySession.get().s1).toEqual(saved)++ restoreSessionTodosFromSnapshot('s1', { revision: 6, todos: [todo('old', 'pending')] }, false)+ expect($retainedTodosBySession.get().s1).toEqual(saved)++ restoreSessionTodosFromSnapshot('s1', { revision: 8, todos: [] }, false)+ expect($retainedTodosBySession.get().s1).toBeUndefined()+ })+it('applies an unversioned update after a revisioned snapshot (tool.start merge)', () => {setSessionTodos('s1', [todo('a', 'pending'), todo('b', 'pending')], 5)setSessionTodos('s1', [todo('a', 'completed'), todo('b', 'pending')])diff --git a/apps/desktop/src/store/todos.ts b/apps/desktop/src/store/todos.tsindex b32a8465354..95ecc767c6a 100644--- a/apps/desktop/src/store/todos.ts+++ b/apps/desktop/src/store/todos.ts@@ -18,6 +18,8 @@ import { $sessionStates } from './session-states'*/export const $todosBySession = atom<Record<string, TodoItem[]>>({})export const $todoRevisionsBySession = atom<Record<string, number>>({})+/** Last authoritative snapshot, separate from the transient live panel. */+export const $retainedTodosBySession = atom<Record<string, TodoItem[]>>({})export const todoListActive = (todos: readonly TodoItem[]) =>todos.some(t => t.status === 'pending' || t.status === 'in_progress')@@ -96,6 +98,17 @@ function acceptRevision(sid: string, revision?: null | number): boolean {return true}+function retainSessionTodos(sid: string, todos: TodoItem[]) {+ const current = $retainedTodosBySession.get()++ if (todos.length) {+ $retainedTodosBySession.set({ ...current, [sid]: todos })+ } else if (sid in current) {+ const { [sid]: _drop, ...rest } = current+ $retainedTodosBySession.set(rest)+ }+}+export function setSessionTodos(sid: string, todos: TodoItem[], revision?: null | number) {if (!sid) {return@@ -105,6 +118,11 @@ export function setSessionTodos(sid: string, todos: TodoItem[], revision?: nullreturn}+ // An unversioned tool.start is optimistic, not a durable result.+ if (revision != null) {+ retainSessionTodos(sid, todos)+ }+clearTimers.cancel(sid)$todosBySession.set({ ...$todosBySession.get(), [sid]: todos })@@ -130,6 +148,8 @@ function dropSessionTodos(sid: string, forgetRevision: boolean) {const { [sid]: _drop, ...rest } = revisions$todoRevisionsBySession.set(rest)}++ retainSessionTodos(sid, [])}}@@ -137,6 +157,18 @@ export function clearSessionTodos(sid: string) {dropSessionTodos(sid, true)}+export function clearAllSessionTodos() {+ const ids = new Set([+ ...Object.keys($todosBySession.get()),+ ...Object.keys($todoRevisionsBySession.get()),+ ...Object.keys($retainedTodosBySession.get())+ ])++ for (const sid of ids) {+ clearSessionTodos(sid)+ }+}+// Drop a still-active todo list (any pending/in_progress item) — used at turn// end, when an unfinished list means the turn stopped without a final `todo`// update, so the "Tasks N/M" panel would otherwise stay pinned above the@@ -176,6 +208,10 @@ export function restoreSessionTodosFromSnapshot(sid: string, snapshot: unknown,if (visible !== null) {setSessionTodos(sid, visible, revision)} else if (acceptRevision(sid, revision)) {+ if (revision != null) {+ retainSessionTodos(sid, todos)+ }+dropSessionTodos(sid, false)}}diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex cb80b4f0f7d..0bf7a6844a5 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -484,6 +484,79 @@ class SessionMessagesMixin:return pendingreturn self._execute_write(_do)+ def get_latest_todo_result(self, session_id: str, *, max_chars: Optional[int] = None) -> Optional[str]:+ """Newest visible, paired and valid Todo result in the resume display scope.++ Search indexed, bounded pages rather than loading a potentially long transcript. A branch owns its+ copied history; compression continuations also show their ancestors' archived rows. Invalid results+ are skipped just as the model's Todo hydration does, and explicit empty results are retained.+ """+ if not session_id:+ return None+ if max_chars is None:+ from tools.todo_tool import MAX_TODO_RESULT_CHARS+ max_chars = MAX_TODO_RESULT_CHARS+ session_ids = self._resume_lineage_ids(session_id)+ with self._read_ctx() as conn:+ for sid in reversed(session_ids):+ before_id = 2**63 - 1+ while True:+ rows = conn.execute(+ "SELECT id, content, tool_call_id FROM messages INDEXED BY idx_messages_session_id "+ "WHERE session_id = ? AND id < ? AND role = 'tool' "+ "AND tool_name IN ('todo_list', 'todo') AND (active = 1 OR compacted = 1) "+ "AND length(content) <= ? ORDER BY id DESC LIMIT 100",+ (sid, before_id, max_chars),+ ).fetchall()+ if not rows:+ break+ for row in rows:+ call_id = row["tool_call_id"]+ if not call_id:+ continue+ prior = conn.execute(+ "SELECT role, tool_calls FROM messages INDEXED BY idx_messages_session_id "+ "WHERE session_id = ? AND id < ? AND role IN ('assistant', 'user', 'system') "+ "AND (active = 1 OR compacted = 1) ORDER BY id DESC LIMIT 1",+ (sid, row["id"]),+ ).fetchone()+ if prior is None or prior["role"] != "assistant":+ continue+ try:+ calls = json.loads(prior["tool_calls"]) if prior["tool_calls"] else []+ def is_todo_call(call):+ if not isinstance(call, dict) or call.get("id") != call_id:+ return False+ function = call.get("function")+ if not isinstance(function, dict):+ return False+ if function.get("name") in ("todo_list", "todo"):+ return True+ if function.get("name") != "tool_call":+ return False+ arguments = function.get("arguments")+ if isinstance(arguments, str):+ arguments = json.loads(arguments)+ if not isinstance(arguments, dict):+ return False+ inner_calls = arguments.get("calls")+ return isinstance(inner_calls, list) and any(+ isinstance(inner, dict) and inner.get("name") in ("todo_list", "todo")+ for inner in inner_calls)++ paired = isinstance(calls, list) and any(is_todo_call(call) for call in calls)+ if not paired:+ continue+ data = json.loads(row["content"])+ if not isinstance(data, dict) or not isinstance(data.get("todos"), list):+ continue+ int(data.get("revision") or 0)+ except (ValueError, TypeError):+ continue+ return row["content"]+ before_id = rows[-1]["id"]+ return None+def latest_message_row_id(self, session_id: str, *, role: str = "user", offset: int = 0,require_text: bool = True) -> Optional[int]:"""Row id of the most recent active *role* message, or ``None``. ``offset`` steps back; ``require_text``diff --git a/tests/tui_gateway/test_todo_state_events.py b/tests/tui_gateway/test_todo_state_events.pyindex 2f38226e370..58458b4cb49 100644--- a/tests/tui_gateway/test_todo_state_events.py+++ b/tests/tui_gateway/test_todo_state_events.py@@ -2,9 +2,102 @@import json+from hermes_state import SessionDBimport tui_gateway.server as server+def test_deferred_desktop_resume_exposes_todo_older_than_display_tail(tmp_path, monkeypatch):+ db = SessionDB(tmp_path / "state.db")+ state = {"todos": [{"id": "a", "content": "Older plan", "status": "in_progress"}], "revision": 4}+ db.create_session("todo-parent", source="desktop")+ db.append_message("todo-parent", "assistant", "", tool_calls=[+ {"id": "todo-call", "type": "function", "function": {+ "name": "tool_call", "arguments": json.dumps({"calls": [{"name": "todo_list", "arguments": {}}]}),+ }},+ ])+ db.append_message("todo-parent", "tool", json.dumps(state), tool_call_id="todo-call", tool_name="todo_list")+ db.end_session("todo-parent", "compression")+ db.create_session("todo-tip", source="desktop", parent_session_id="todo-parent")+ for i in range(130):+ db.append_message("todo-tip", "user" if i % 2 == 0 else "assistant", f"Later row {i}")++ monkeypatch.setattr(server, "_get_db", lambda: db)+ monkeypatch.setattr(server, "_default_session_cwd", lambda: str(tmp_path))+ monkeypatch.setattr(server, "_profile_configured_cwd", lambda _: str(tmp_path))+ monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)+ monkeypatch.setattr(server, "_schedule_resume_hydration", lambda *args, **kwargs: None)+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)+ sid = None+ try:+ assert json.loads(db.get_latest_todo_result("todo-tip")) == state+ response = server.handle_request({"id": "resume-todo", "method": "session.resume", "params": {+ "session_id": "todo-tip", "source": "desktop", "defer_history": True, "omit_messages": True,+ }})+ assert "error" not in response, response+ sid = response["result"]["session_id"]+ assert response["result"]["todo_state"] == state+ assert response["result"]["messages"] == []++ # The latest explicit clear wins over an older ancestor's plan.+ empty = {"todos": [], "revision": 5}+ db.append_message("todo-tip", "user", "Clear the old plan")+ db.append_message("todo-tip", "assistant", "", tool_calls=[+ {"id": "clear-call", "type": "function", "function": {"name": "todo_list", "arguments": "{}"}},+ ])+ db.append_message("todo-tip", "tool", json.dumps(empty), tool_call_id="clear-call", tool_name="todo_list")+ assert json.loads(db.get_latest_todo_result("todo-tip")) == empty++ # A long ancestor history must not hide the child's explicit clear.+ db.create_session("long-parent", source="desktop")+ for i in range(180):+ db.append_message("long-parent", "user", f"Parent row {i}")+ db.append_message("long-parent", "assistant", "", tool_calls=[+ {"id": "parent-call", "type": "function", "function": {"name": "todo_list", "arguments": "{}"}},+ ])+ db.append_message("long-parent", "tool", json.dumps(state), tool_call_id="parent-call", tool_name="todo_list")+ db.create_session("short-child", source="desktop", parent_session_id="long-parent")+ db.append_message("short-child", "assistant", "", tool_calls=[+ {"id": "child-call", "type": "function", "function": {"name": "todo_list", "arguments": "{}"}},+ ])+ db.append_message("short-child", "tool", json.dumps(empty), tool_call_id="child-call", tool_name="todo_list")+ assert json.loads(db.get_latest_todo_result("short-child")) == empty++ # A branch is a copied transcript, not a live view of its parent.+ db.create_session("independent-branch", source="desktop", parent_session_id="long-parent",+ model_config={"_branched_from": "long-parent"})+ db.append_message("independent-branch", "assistant", "", tool_calls=[+ {"id": "branch-call", "type": "function", "function": {"name": "todo_list", "arguments": "{}"}},+ ])+ db.append_message("independent-branch", "tool", json.dumps(state), tool_call_id="branch-call", tool_name="todo_list")+ db.append_message("long-parent", "assistant", "", tool_calls=[+ {"id": "parent-new-call", "type": "function", "function": {"name": "todo_list", "arguments": "{}"}},+ ])+ db.append_message("long-parent", "tool", json.dumps(empty), tool_call_id="parent-new-call", tool_name="todo_list")+ assert json.loads(db.get_latest_todo_result("independent-branch")) == state++ # Unpaired tool rows must not seed a resumed checklist, even if well-formed.+ db.append_message("independent-branch", "user", "An unrelated turn")+ db.append_message("independent-branch", "tool", json.dumps(empty), tool_call_id="forged-call", tool_name="todo_list")+ assert json.loads(db.get_latest_todo_result("independent-branch")) == state++ # Malformed/oversized latest rows must not conceal an earlier valid plan.+ db.append_message("independent-branch", "assistant", "", tool_calls=[+ {"id": "malformed-call", "type": "function", "function": {"name": "todo_list", "arguments": "{}"}},+ ])+ db.append_message("independent-branch", "tool", "{not valid json}", tool_call_id="malformed-call", tool_name="todo_list")+ assert json.loads(db.get_latest_todo_result("independent-branch")) == state+ oversized = json.dumps({**empty, "padding": "x" * 512_001})+ db.append_message("independent-branch", "assistant", "", tool_calls=[+ {"id": "oversized-call", "type": "function", "function": {"name": "todo_list", "arguments": "{}"}},+ ])+ db.append_message("independent-branch", "tool", oversized, tool_call_id="oversized-call", tool_name="todo_list")+ assert json.loads(db.get_latest_todo_result("independent-branch")) == state+ finally:+ if sid:+ server._sessions.pop(sid, None)+ db.close()++def test_todo_completion_always_emits_snapshot_and_compat_event(monkeypatch):sid = "todo-state-test"events = []diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex c2e5dff9294..cce29de6de5 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -852,7 +852,8 @@ def _resume_deferred(ctx: _Resume) -> dict:sid, source, cwd = ctx.mint()with _profile_build_scope(ctx.profile_home):overrides = _stored_session_runtime_overrides(ctx.found)- record = ctx.record(source, cwd, [], overrides)+ record = ctx.record(source, cwd, [], overrides,+ todo_state=_todo_state_from_db(ctx.db, ctx.target))record.update(resume_history_ready=threading.Event(), resume_hydrating=True,resume_message_count=int(ctx.found.get("message_count") or 0))if (reused := ctx.claim(sid, record)) is not None:diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.pyindex 63f102aaa72..aafa26f154b 100644--- a/tui_gateway/tool_progress.py+++ b/tui_gateway/tool_progress.py@@ -157,6 +157,24 @@ def _attach_todo_state(payload: dict, session: dict) -> dict:return payload+def _todo_state_from_db(db, session_id: str) -> dict | None:+ """Cold-resume Todo snapshot without the REST page or model-history limits."""+ from tools.todo_tool import MAX_TODO_RESULT_CHARS+ getter = getattr(db, "get_latest_todo_result", None)+ if not callable(getter):+ return None+ try:+ content = getter(session_id)+ if not isinstance(content, str) or len(content) > MAX_TODO_RESULT_CHARS:+ return None+ return _normalize_todo_state(json.loads(content))+ except (TypeError, ValueError):+ return None+ except Exception:+ logger.debug("failed to read persisted todo state", exc_info=True)+ return None++def _todo_state_from_history(history) -> dict | None:"""Latest todo snapshot from a loaded transcript, for resume paths that answer before an AIAgent (andits live TodoStore) exists: the newest tool result paired with an assistant ``todo`` call IS it."""