Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
feat(assistant): retry re-runs the turn in place and the last answer gains regenerate
rcourtman60ce8924bbfa
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 186d40cb65..5e5dca8666 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -493,6 +493,13 @@ same browser-safe history boundary. Lifecycle surfaces, MCP adapters, andagents may display the updated title as human navigation metadata, but theymust not treat a renamed title as command authorization, host identity,enrollment state, capability evidence, or install-token disclosure.+Assistant turn undo through `POST /api/ai/sessions/{id}/undo` (including the+optional expected-prompt guard body used by retry/regenerate) is the same+kind of conversation-history mutation: it rewrites chat transcript state+only. Lifecycle surfaces and agents must not interpret an undone or+regenerated Assistant turn as reverting any lifecycle action, approval, or+agent command the original turn produced; governed action history remains+the only revert authority for infrastructure changes.The native Assistant surface-tool inventory at`GET /api/ai/assistant/surface-tools` is also AI-runtime/API-contract metadata:lifecycle surfaces may display which Assistant tools are available, but mustdiff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 8d7b270954..a44f2868df 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -2624,6 +2624,22 @@ query...`, and `Reading storage...` before streamed tool arguments arefinding id, handoff metadata, approval/autonomous override, and selectedmodel route when available so the operator can edit and resend withoutreconstructing hidden context from transcript prose.+ Retry and regenerate are turn re-runs over the same undo boundary, not a+ parallel history mutation path. `POST /api/ai/sessions/{id}/undo` accepts an+ optional JSON body (`chat.SessionTurnUndoOptions`) whose `expected_prompt`+ field, when non-empty, makes the removal conditional on the latest+ user-authored prompt matching the prompt being re-run, so a retry whose+ failed send never reached the session cannot remove a different turn.+ Frontend retry ("Try again" on a failed turn, model-route switch retry) and+ regenerate must remove the replaced turn through this guarded undo before+ re-sending so session history never records the prompt twice; a failed+ guard or transport error degrades to a plain re-send rather than blocking+ the retry. The removed turn stays redoable until the re-sent message lands,+ at which point the normal new-message rule clears redo state. The+ regenerate affordance is offered only on the latest settled assistant+ answer (nothing streaming, no error block, no pending approval or+ question, and a user prompt available to re-send) because the undo+ boundary only operates on the last durable turn.The empty Assistant drawer may surface recent non-empty sessions as directresume actions using the backend session list already owned by the drawer;it must not create a parallel recent-chat store or product-authored promptdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 05b659fac0..feec69dbe9 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1296,10 +1296,17 @@ payload shape change when the portal presents compact client rows.`chat.IsSystemSessionID`; browser clients must not re-derive thatownership from ID string patterns, and must keep system sessions out ofresumable-chat offers (quick-resume) while leaving them listable for- inspection. Browser clients must use the- shared `AIChatAPI.undoLastTurn(sessionId)` and- `AIChatAPI.redoLastTurn(sessionId)` helpers so path encoding and response- shape stay canonical.+ inspection. The undo endpoint accepts an optional JSON body+ (`chat.SessionTurnUndoOptions`) whose `expected_prompt` field makes the+ removal conditional on the latest user-authored prompt matching the+ prompt being re-run; retry/regenerate flows send it so a stale retry can+ never remove a different turn, and a guard mismatch returns+ `success:false` with a browser-safe message rather than an error status.+ An absent or empty body preserves the unguarded undo shape. Browser+ clients must use the shared+ `AIChatAPI.undoLastTurn(sessionId, { expectedPrompt })` and+ `AIChatAPI.redoLastTurn(sessionId)` helpers so path encoding, guard+ trimming, and response shape stay canonical.OpenCode-style file diff/revert session routes are deliberately not partof Pulse's supported Assistant session contract: Pulse sessions do not ownlocal code-file edits, and infrastructure mutations must be revieweddiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex b43b57634c..d213bee98b 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -152,6 +152,14 @@ token may allow agent reporting for the scoped tenant workspace, but it must notgrant backup visibility, recovery authority, or storage health privileges; thoseremain governed by the setup-script and source-specific backup API boundariesbelow.+Assistant chat-session history endpoints in `internal/api/ai_handler.go`+(session list/rename/fork/summarize and turn undo/redo, including the+retry/regenerate expected-prompt guard on `POST /api/ai/sessions/{id}/undo`)+are ai-runtime conversation-state surfaces only. Undoing or regenerating an+Assistant turn rewrites chat transcript history; it is never a restore+operation, does not revert storage mutations or governed actions the original+turn produced, and must not be surfaced or interpreted as backup coverage,+restore readiness, or recovery evidence.Operations-loop status wiring in `internal/api/agent_resource_context.go` isstorage/recovery-adjacent only through the shared action-audit and verificationprojection. Sibling handlers in `internal/api/` such as the AI settings handlerdiff --git a/frontend-modern/src/api/__tests__/aiChat.test.ts b/frontend-modern/src/api/__tests__/aiChat.test.tsindex eaea5e991a..12b43419ce 100644--- a/frontend-modern/src/api/__tests__/aiChat.test.ts+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts@@ -1407,6 +1407,37 @@ describe('AIChatAPI', () => {});});+ it('sends the expected-prompt guard body when undo runs for a retry', async () => {+ const undoResult = {+ success: true,+ session_id: 'session/root',+ restored_prompt: 'show me the affected hosts',+ removed_messages: 2,+ can_redo: true,+ };+ apiFetchJSONMock.mockResolvedValueOnce(undoResult);++ await expect(+ AIChatAPI.undoLastTurn('session/root', { expectedPrompt: ' show me the affected hosts ' }),+ ).resolves.toEqual(undoResult);++ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/sessions/session%2Froot/undo', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ expected_prompt: 'show me the affected hosts' }),+ });+ });++ it('keeps the undo request bodyless when no guard is provided', async () => {+ apiFetchJSONMock.mockResolvedValueOnce({ success: true, session_id: 's', can_redo: false });++ await AIChatAPI.undoLastTurn('s', { expectedPrompt: ' ' });++ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/sessions/s/undo', {+ method: 'POST',+ });+ });+it('compacts a session through the summarize endpoint', async () => {const result = {success: true,diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.tsindex dfb898f463..059ce3f4b0 100644--- a/frontend-modern/src/api/aiChat.ts+++ b/frontend-modern/src/api/aiChat.ts@@ -384,9 +384,21 @@ export class AIChatAPI {}// Undo latest chat turn and return the user prompt so the composer can restore it.- static async undoLastTurn(sessionId: string): Promise<ChatSessionUndoResult> {+ // Retry/regenerate passes expectedPrompt so a stale retry can never remove a+ // turn other than the one being re-run.+ static async undoLastTurn(+ sessionId: string,+ options?: { expectedPrompt?: string },+ ): Promise<ChatSessionUndoResult> {+ const expectedPrompt = options?.expectedPrompt?.trim();return apiFetchJSON(`${this.baseUrl}/sessions/${encodeURIComponent(sessionId)}/undo`, {method: 'POST',+ ...(expectedPrompt+ ? {+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ expected_prompt: expectedPrompt }),+ }+ : {}),}) as Promise<ChatSessionUndoResult>;}diff --git a/frontend-modern/src/components/AI/Chat/ChatMessages.tsx b/frontend-modern/src/components/AI/Chat/ChatMessages.tsxindex e94343cc0b..1e22afed0a 100644--- a/frontend-modern/src/components/AI/Chat/ChatMessages.tsx+++ b/frontend-modern/src/components/AI/Chat/ChatMessages.tsx@@ -28,6 +28,7 @@ interface ChatMessagesProps {) => void;onSkipQuestion: (messageId: string, questionId: string) => void;onRetry?: (messageId: string) => void;+ onRegenerate?: (messageId: string) => void;onChangeModel?: () => void;getModelRouteLabel?: (modelId: string) => string;getModelRouteAlternative?: (message: ChatMessage) => ModelRouteRecoveryOption | null;@@ -71,6 +72,20 @@ export const ChatMessages: Component<ChatMessagesProps> = (props) => {setMirroredMessages(reconcile(props.messages, { key: 'id', merge: false }));});+ // Regenerate re-runs the LAST turn via session undo, so only the final+ // assistant answer qualifies, and only once it has settled with nothing+ // pending and a user prompt to re-send.+ const regenerableMessageId = createMemo(() => {+ if (!props.onRegenerate) return null;+ const msgs = props.messages;+ if (msgs.length === 0) return null;+ const last = msgs[msgs.length - 1];+ if (last.role !== 'assistant' || last.isStreaming || last.error) return null;+ if (last.pendingApprovals?.length || last.pendingQuestions?.length) return null;+ const hasPrompt = msgs.some((m) => m.role === 'user' && m.content.trim());+ return hasPrompt ? last.id : null;+ });+const isContainerNearBottom = () => {if (!containerRef) return true;const { scrollTop, scrollHeight, clientHeight } = containerRef;@@ -286,6 +301,11 @@ export const ChatMessages: Component<ChatMessagesProps> = (props) => {}onSkipQuestion={(questionId) => props.onSkipQuestion(message.id, questionId)}onRetry={props.onRetry}+ onRegenerate={+ message.id === regenerableMessageId()+ ? () => props.onRegenerate?.(message.id)+ : undefined+ }onChangeModel={props.onChangeModel}getModelRouteLabel={props.getModelRouteLabel}modelRouteAlternative={props.getModelRouteAlternative?.(message)}diff --git a/frontend-modern/src/components/AI/Chat/MessageItem.tsx b/frontend-modern/src/components/AI/Chat/MessageItem.tsxindex 82d2b9a069..49fd5d0370 100644--- a/frontend-modern/src/components/AI/Chat/MessageItem.tsx+++ b/frontend-modern/src/components/AI/Chat/MessageItem.tsx@@ -55,6 +55,9 @@ interface MessageItemProps {) => void;onSkipQuestion: (questionId: string) => void;onRetry?: (messageId: string) => void;+ // Provided only for the latest settled assistant answer: re-runs the turn in+ // place (same prompt, fresh generation).+ onRegenerate?: () => void;onChangeModel?: () => void;getModelRouteLabel?: (modelId: string) => string;modelRouteAlternative?: ModelRouteRecoveryOption | null;@@ -660,6 +663,18 @@ export const MessageItem: Component<MessageItemProps> = (props) => {class="ml-auto opacity-0 shadow-sm transition-opacity focus:opacity-100 group-hover:opacity-100"/></Show>+ <Show when={props.onRegenerate}>+ <ActionIconButton+ onClick={() => props.onRegenerate?.()}+ label="Regenerate response"+ title="Regenerate response"+ tone="outline"+ size="sm"+ class={`${canCopy() ? '' : 'ml-auto '}opacity-0 shadow-sm transition-opacity focus:opacity-100 group-hover:opacity-100`}+ >+ <RotateCcwIcon class="h-3.5 w-3.5" aria-hidden="true" />+ </ActionIconButton>+ </Show></div><div>diff --git a/frontend-modern/src/components/AI/Chat/__tests__/ChatMessages.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/ChatMessages.test.tsxindex 1f77ace0ba..f28d25a4f6 100644--- a/frontend-modern/src/components/AI/Chat/__tests__/ChatMessages.test.tsx+++ b/frontend-modern/src/components/AI/Chat/__tests__/ChatMessages.test.tsx@@ -20,6 +20,7 @@ let capturedMessageItemProps: Array<{answers: Array<{ id: string; value: string }>,) => void;onSkipQuestion: (questionId: string) => void;+ onRegenerate?: () => void;onChangeModel?: () => void;getModelRouteLabel?: (modelId: string) => string;modelRouteAlternative?: ModelRouteRecoveryOption | null;@@ -41,6 +42,7 @@ vi.mock('../MessageItem', () => ({answers: Array<{ id: string; value: string }>,) => void;onSkipQuestion: (questionId: string) => void;+ onRegenerate?: () => void;onChangeModel?: () => void;getModelRouteLabel?: (modelId: string) => string;modelRouteAlternative?: ModelRouteRecoveryOption | null;@@ -377,6 +379,58 @@ describe('ChatMessages', () => {expect(handlers.onApprove).toHaveBeenCalledWith('msg-42', fakeApproval);});+ it('provides onRegenerate only for the last settled assistant answer', () => {+ const handlers = makeHandlers();+ const onRegenerate = vi.fn();+ const messages = [+ makeMessage({ id: 'u1', role: 'user', content: 'first prompt' }),+ makeMessage({ id: 'a1', role: 'assistant', content: 'first answer' }),+ makeMessage({ id: 'u2', role: 'user', content: 'second prompt' }),+ makeMessage({ id: 'a2', role: 'assistant', content: 'second answer' }),+ ];+ render(() => (+ <ChatMessages messages={messages} {...handlers} onRegenerate={onRegenerate} />+ ));++ const earlier = capturedMessageItemProps.find((p) => p.message.id === 'a1');+ const last = capturedMessageItemProps.find((p) => p.message.id === 'a2');+ expect(earlier!.onRegenerate).toBeUndefined();+ expect(last!.onRegenerate).toBeDefined();++ last!.onRegenerate!();+ expect(onRegenerate).toHaveBeenCalledWith('a2');+ });++ it('withholds onRegenerate while the last answer is streaming, failed, or awaiting input', () => {+ const handlers = makeHandlers();+ const onRegenerate = vi.fn();+ const variants: Array<Partial<ChatMessage>> = [+ { isStreaming: true },+ { error: 'provider unreachable' },+ {+ pendingApprovals: [+ { command: 'reboot', toolId: 't1', toolName: 'pulse_control', runOnHost: false },+ ],+ },+ ];+ for (const overrides of variants) {+ capturedMessageItemProps = [];+ const { unmount } = render(() => (+ <ChatMessages+ messages={[+ makeMessage({ id: 'u1', role: 'user', content: 'prompt' }),+ makeMessage({ id: 'a1', role: 'assistant', content: 'answer', ...overrides }),+ ]}+ {...handlers}+ onRegenerate={onRegenerate}+ />+ ));+ const last = capturedMessageItemProps.find((p) => p.message.id === 'a1');+ expect(last!.onRegenerate).toBeUndefined();+ unmount();+ }+ });+it('forwards onSkip with message.id prepended', () => {const handlers = makeHandlers();render(() => <ChatMessages messages={[makeMessage({ id: 'msg-99' })]} {...handlers} />);diff --git a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.tsindex 33d1a12733..c51aee5eee 100644--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts@@ -557,7 +557,8 @@ describe('useChat', () => {expect(chat.messages()).toHaveLength(2);mockChat.mockResolvedValueOnce(undefined);- chat.retryMessage(failed!.id);+ mockUndoLastTurn.mockResolvedValueOnce({ success: true, session_id: 'sess', can_redo: false });+ await chat.retryMessage(failed!.id);await new Promise((r) => setTimeout(r, 0));const msgs = chat.messages();@@ -565,6 +566,28 @@ describe('useChat', () => {expect(msgs.filter((m) => m.role === 'user')).toHaveLength(1);expect(msgs.some((m) => m.error)).toBe(false);expect(mockChat).toHaveBeenCalledTimes(2);+ // The persisted turn is removed (guarded by the retried prompt) so the+ // re-send does not double-record the prompt in session history.+ expect(mockUndoLastTurn).toHaveBeenCalledWith('sess', { expectedPrompt: 'hello' });+ expect(mockUndoLastTurn.mock.invocationCallOrder[0]).toBeLessThan(+ mockChat.mock.invocationCallOrder[1],+ );+ dispose();+ });++ it('retryMessage still re-sends when the history undo fails', async () => {+ mockChat.mockRejectedValueOnce(new Error('server error'));+ const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 'sess' }));+ await chat.sendMessage('hello');++ const failed = chat.messages().find((m) => m.role === 'assistant');+ mockChat.mockResolvedValueOnce(undefined);+ mockUndoLastTurn.mockRejectedValueOnce(new Error('network down'));+ await chat.retryMessage(failed!.id);+ await new Promise((r) => setTimeout(r, 0));++ expect(mockChat).toHaveBeenCalledTimes(2);+ expect(chat.messages().some((m) => m.error)).toBe(false);dispose();});@@ -603,7 +626,7 @@ describe('useChat', () => {const failed = chat.messages().find((m) => m.role === 'assistant');expect(failed?.error).toContain('server error');- chat.retryMessage(failed!.id);+ await chat.retryMessage(failed!.id);await new Promise((r) => setTimeout(r, 0));expect(mockChat).toHaveBeenCalledTimes(2);diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.tsindex 7061b8dc88..1961a751d0 100644--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts@@ -2439,10 +2439,11 @@ export function useChat(options: UseChatOptions = {}) {});};- // Retry a failed assistant turn: drop the failed assistant message and the- // user prompt that triggered it from the view, then re-send that prompt so the- // conversation shows a single clean attempt instead of a dead-end error.- const retryMessage = (assistantMessageId: string, sendOptionOverrides?: SendMessageOptions) => {+ // Retry an assistant turn (failed or regenerated): drop the assistant message+ // and the user prompt that triggered it from the view AND from the persisted+ // session, then re-send that prompt so the conversation shows a single clean+ // attempt instead of a dead-end error plus a double-recorded prompt.+ const retryMessage = async (assistantMessageId: string, sendOptionOverrides?: SendMessageOptions) => {const msgs = messages();const idx = msgs.findIndex((m) => m.id === assistantMessageId);if (idx < 0) return;@@ -2456,6 +2457,19 @@ export function useChat(options: UseChatOptions = {}) {...(sendOptionsFromRequestContext(request) || {}),...(sendOptionOverrides || {}),};+ // Remove the retried turn from the durable session so the re-send doesn't+ // double-record the prompt. The expected-prompt guard makes this a no-op+ // when the failed send never reached the session; a transport error here+ // degrades to the old duplicate-history behavior rather than blocking the+ // retry.+ const currentSessionId = sessionId().trim();+ if (currentSessionId) {+ try {+ await AIChatAPI.undoLastTurn(currentSessionId, { expectedPrompt: prompt });+ } catch (error) {+ logger.warn('[useChat] Retry could not remove the previous turn from session history', error);+ }+ }const removeIds = new Set([msgs[userIdx].id, assistantMessageId]);setMessages((prev) => prev.filter((m) => !removeIds.has(m.id)));void sendMessage(diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsxindex c7ab281644..a40045d927 100644--- a/frontend-modern/src/components/AI/Chat/index.tsx+++ b/frontend-modern/src/components/AI/Chat/index.tsx@@ -2417,7 +2417,7 @@ export const AIChat: Component<AIChatProps> = (props) => {const switchToModelRoute = (modelId: string, failedMessageId?: string) => {selectModel(modelId);if (failedMessageId) {- chat.retryMessage(failedMessageId, { model: modelId });+ void chat.retryMessage(failedMessageId, { model: modelId });}focusComposer();};@@ -4833,7 +4833,10 @@ export const AIChat: Component<AIChatProps> = (props) => {onSkip={handleSkip}onAnswerQuestion={handleAnswerQuestion}onSkipQuestion={handleSkipQuestion}- onRetry={(messageId) => chat.retryMessage(messageId)}+ onRetry={(messageId) => void chat.retryMessage(messageId)}+ onRegenerate={+ chat.isLoading() ? undefined : (messageId) => void chat.retryMessage(messageId)+ }onChangeModel={openModelSelectorFromError}getModelRouteLabel={formatChatMessageModelRoute}getModelRouteAlternative={getFailedTurnModelRouteAlternative}diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 1e82af4fae..176b6c4ade 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -3344,7 +3344,7 @@ func (s *Service) ForkSession(ctx context.Context, sessionID string) (*Session,}// UndoLastTurn removes the latest user turn from the durable chat session.-func (s *Service) UndoLastTurn(ctx context.Context, sessionID string) (*SessionTurnUndoResult, error) {+func (s *Service) UndoLastTurn(ctx context.Context, sessionID string, opts SessionTurnUndoOptions) (*SessionTurnUndoResult, error) {s.mu.RLock()sessions := s.sessionss.mu.RUnlock()@@ -3353,7 +3353,7 @@ func (s *Service) UndoLastTurn(ctx context.Context, sessionID string) (*SessionTreturn nil, fmt.Errorf("service not started")}- return sessions.UndoLastTurn(sessionID)+ return sessions.UndoLastTurnWithOptions(sessionID, opts)}// RedoLastTurn restores the latest turn removed by UndoLastTurn.diff --git a/internal/ai/chat/service_test.go b/internal/ai/chat/service_test.goindex df7fee1095..88b0457d0f 100644--- a/internal/ai/chat/service_test.go+++ b/internal/ai/chat/service_test.go@@ -352,7 +352,7 @@ func TestService_SessionWrappers(t *testing.T) {Role: "assistant",Content: "There are 42 device nodes.",}))- undo, err := service.UndoLastTurn(ctx, forked.ID)+ undo, err := service.UndoLastTurn(ctx, forked.ID, SessionTurnUndoOptions{})require.NoError(t, err)require.NotNil(t, undo)assert.True(t, undo.Success)diff --git a/internal/ai/chat/session.go b/internal/ai/chat/session.goindex 63c6f3f63d..986d4dcde3 100644--- a/internal/ai/chat/session.go+++ b/internal/ai/chat/session.go@@ -818,6 +818,13 @@ func (s *SessionStore) Fork(id string) (*Session, error) {// UndoLastTurn removes the latest user-authored turn from a session and stores// the removed messages so RedoLastTurn can restore them.func (s *SessionStore) UndoLastTurn(id string) (*SessionTurnUndoResult, error) {+ return s.UndoLastTurnWithOptions(id, SessionTurnUndoOptions{})+}++// UndoLastTurnWithOptions removes the latest user-authored turn subject to the+// given options: an expected-prompt guard so retry/regenerate flows cannot+// remove a turn other than the one being re-run.+func (s *SessionStore) UndoLastTurnWithOptions(id string, opts SessionTurnUndoOptions) (*SessionTurnUndoResult, error) {if err := validateSessionID(id); err != nil {return nil, err}@@ -845,6 +852,15 @@ func (s *SessionStore) UndoLastTurn(id string) (*SessionTurnUndoResult, error) {Message: "No user turn to undo.",}, nil}+ if expected := strings.TrimSpace(opts.ExpectedPrompt); expected != "" &&+ strings.TrimSpace(data.Messages[lastUserIndex].Content) != expected {+ return &SessionTurnUndoResult{+ Success: false,+ SessionID: data.ID,+ CanRedo: len(data.TurnRedoStack) > 0,+ Message: "The latest turn no longer matches the prompt being retried.",+ }, nil+ }removed := cloneSessionMessages(data.Messages[lastUserIndex:])prompt := ""diff --git a/internal/ai/chat/session_test.go b/internal/ai/chat/session_test.goindex 4c0f7b609c..221c09e10d 100644--- a/internal/ai/chat/session_test.go+++ b/internal/ai/chat/session_test.go@@ -337,6 +337,43 @@ func TestSessionStoreUndoRedoLastTurn(t *testing.T) {assert.Equal(t, "No undone turn to redo.", redo.Message)}+func TestSessionStoreUndoLastTurnExpectedPromptGuard(t *testing.T) {+ store, err := NewSessionStore(t.TempDir())+ require.NoError(t, err)++ session, err := store.Create()+ require.NoError(t, err)++ require.NoError(t, store.AddMessage(session.ID, Message{ID: "u1", Role: "user", Content: "First prompt"}))+ require.NoError(t, store.AddMessage(session.ID, Message{ID: "a1", Role: "assistant", Content: "First answer"}))++ // A retry whose prompt never reached the session must not remove the+ // previous turn.+ undo, err := store.UndoLastTurnWithOptions(session.ID, SessionTurnUndoOptions{+ ExpectedPrompt: "Prompt that never persisted",+ })+ require.NoError(t, err)+ require.NotNil(t, undo)+ assert.False(t, undo.Success)+ assert.Equal(t, "The latest turn no longer matches the prompt being retried.", undo.Message)++ messages, err := store.GetMessages(session.ID)+ require.NoError(t, err)+ require.Len(t, messages, 2)++ // A matching prompt (modulo surrounding whitespace) removes the turn.+ undo, err = store.UndoLastTurnWithOptions(session.ID, SessionTurnUndoOptions{+ ExpectedPrompt: " First prompt ",+ })+ require.NoError(t, err)+ assert.True(t, undo.Success)+ assert.Equal(t, "First prompt", undo.RestoredPrompt)++ messages, err = store.GetMessages(session.ID)+ require.NoError(t, err)+ assert.Empty(t, messages)+}+func TestSessionStoreForkRejectsMissingOrInvalidSession(t *testing.T) {store, err := NewSessionStore(t.TempDir())require.NoError(t, err)diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.goindex 6df795fa48..fcfeee71c5 100644--- a/internal/ai/chat/types.go+++ b/internal/ai/chat/types.go@@ -45,6 +45,16 @@ type SessionTurnUndoResult struct {Message string `json:"message,omitempty"`}+// SessionTurnUndoOptions controls how the latest user turn is removed.+type SessionTurnUndoOptions struct {+ // ExpectedPrompt, when non-empty, only removes the turn if the latest+ // user prompt matches it, so a retry can never remove a different turn+ // (e.g. when the failed send never reached the session). The removed+ // turn stays redoable until the retried send lands, at which point+ // AddMessage clears the redo stack like any other new message.+ ExpectedPrompt string `json:"expected_prompt"`+}+// SessionTurnRedoResult is returned when a previously undone turn is restored.type SessionTurnRedoResult struct {Success bool `json:"success"`diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.goindex 40793547c7..10e2b02a1b 100644--- a/internal/api/ai_handler.go+++ b/internal/api/ai_handler.go@@ -59,7 +59,7 @@ type AIService interface {AbortSession(ctx context.Context, sessionID string) errorSummarizeSession(ctx context.Context, sessionID string) (map[string]interface{}, error)ForkSession(ctx context.Context, sessionID string) (*chat.Session, error)- UndoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnUndoResult, error)+ UndoLastTurn(ctx context.Context, sessionID string, opts chat.SessionTurnUndoOptions) (*chat.SessionTurnUndoResult, error)RedoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnRedoResult, error)AnswerQuestion(ctx context.Context, questionID string, answers []chat.QuestionAnswer) errorAssistantSurfaceToolContract(ctx context.Context) agentcapabilities.SurfaceToolContract@@ -3207,6 +3207,8 @@ func (h *AIHandler) HandleFork(w http.ResponseWriter, r *http.Request, sessionID}// HandleUndoLastTurn handles POST /api/ai/sessions/{id}/undo.+// The body is optional; retry/regenerate sends SessionTurnUndoOptions with the+// prompt being re-run so a stale retry can never remove a different turn.func (h *AIHandler) HandleUndoLastTurn(w http.ResponseWriter, r *http.Request, sessionID string) {ctx := r.Context()if !h.IsRunning(ctx) {@@ -3220,7 +3222,15 @@ func (h *AIHandler) HandleUndoLastTurn(w http.ResponseWriter, r *http.Request, sreturn}- result, err := svc.UndoLastTurn(ctx, sessionID)+ var opts chat.SessionTurnUndoOptions+ if r.Body != nil {+ if err := json.NewDecoder(r.Body).Decode(&opts); err != nil && err != io.EOF {+ http.Error(w, "Invalid request body", http.StatusBadRequest)+ return+ }+ }++ result, err := svc.UndoLastTurn(ctx, sessionID, opts)if err != nil {http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)returndiff --git a/internal/api/ai_handler_recovery_wiring_test.go b/internal/api/ai_handler_recovery_wiring_test.goindex 9afcb0065d..a9dbc5bdf2 100644--- a/internal/api/ai_handler_recovery_wiring_test.go+++ b/internal/api/ai_handler_recovery_wiring_test.go@@ -63,7 +63,7 @@ func (s *capturingAIService) SummarizeSession(ctx context.Context, sessionID strfunc (s *capturingAIService) ForkSession(ctx context.Context, sessionID string) (*chat.Session, error) {return &chat.Session{ID: "fork"}, nil}-func (s *capturingAIService) UndoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnUndoResult, error) {+func (s *capturingAIService) UndoLastTurn(ctx context.Context, sessionID string, opts chat.SessionTurnUndoOptions) (*chat.SessionTurnUndoResult, error) {return &chat.SessionTurnUndoResult{Success: true, SessionID: sessionID}, nil}func (s *capturingAIService) RedoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnRedoResult, error) {diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.goindex 992d357592..cfd6a41f88 100644--- a/internal/api/ai_handler_test.go+++ b/internal/api/ai_handler_test.go@@ -189,8 +189,8 @@ func (m *MockAIService) ForkSession(ctx context.Context, sessionID string) (*chareturn args.Get(0).(*chat.Session), args.Error(1)}-func (m *MockAIService) UndoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnUndoResult, error) {- args := m.Called(ctx, sessionID)+func (m *MockAIService) UndoLastTurn(ctx context.Context, sessionID string, opts chat.SessionTurnUndoOptions) (*chat.SessionTurnUndoResult, error) {+ args := m.Called(ctx, sessionID, opts)if args.Get(0) == nil {return nil, args.Error(1)}diff --git a/internal/api/router_routes_additional_test.go b/internal/api/router_routes_additional_test.goindex 779f979616..d2b43ff470 100644--- a/internal/api/router_routes_additional_test.go+++ b/internal/api/router_routes_additional_test.go@@ -204,7 +204,7 @@ func TestRouteAISessions_Fork(t *testing.T) {func TestRouteAISessions_UndoLastTurn(t *testing.T) {mockSvc := &MockAIService{}mockSvc.On("IsRunning").Return(true)- mockSvc.On("UndoLastTurn", mock.Anything, "session-1").Return(&chat.SessionTurnUndoResult{+ mockSvc.On("UndoLastTurn", mock.Anything, "session-1", chat.SessionTurnUndoOptions{}).Return(&chat.SessionTurnUndoResult{Success: true,SessionID: "session-1",RestoredPrompt: "Inspect storage warnings",@@ -226,6 +226,32 @@ func TestRouteAISessions_UndoLastTurn(t *testing.T) {mockSvc.AssertExpectations(t)}+func TestRouteAISessions_UndoLastTurnRetryOptions(t *testing.T) {+ mockSvc := &MockAIService{}+ mockSvc.On("IsRunning").Return(true)+ mockSvc.On("UndoLastTurn", mock.Anything, "session-1", chat.SessionTurnUndoOptions{+ ExpectedPrompt: "Inspect storage warnings",+ }).Return(&chat.SessionTurnUndoResult{+ Success: true,+ SessionID: "session-1",+ }, nil)++ handler := &AIHandler{}+ setUnexportedField(t, handler, "defaultService", mockSvc)++ router := &Router{aiHandler: handler}+ body := strings.NewReader(`{"expected_prompt":"Inspect storage warnings"}`)+ req := httptest.NewRequest(http.MethodPost, "/api/ai/sessions/session-1/undo", body)+ rec := httptest.NewRecorder()++ router.routeAISessions(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d", http.StatusOK, rec.Code)+ }+ mockSvc.AssertExpectations(t)+}+func TestRouteAISessions_RedoLastTurn(t *testing.T) {mockSvc := &MockAIService{}mockSvc.On("IsRunning").Return(true)