Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Add Assistant turn undo and redo

rcourtman44e8a1b2bde0
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index d59eb1935d..e8984cceaa 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1542,6 +1542,12 @@ run-history lookup so AI runtime can rebuild model-only run context, but the
resulting scoped resources, runtime failure summaries, and follow-up session
metadata must not become agent command authorization, reachability proof,
install state, profile assignment, or fleet lifecycle evidence.
+Assistant session undo/redo through `POST /api/ai/sessions/{id}/undo` and
+`POST /api/ai/sessions/{id}/redo` follows the same adjacent AI/runtime boundary.
+The restored prompt, redo availability flag, and restored message count are
+conversation repair metadata only; lifecycle-adjacent surfaces must not treat
+them as agent enrollment state, command authorization, update readiness, or
+fleet-control evidence.
That same shared dependency now also assumes hosted cloud handoff authorizes
tenant org access before browser lifecycle continues. Lifecycle-adjacent opens
into hosted workspaces may depend on `internal/api/cloud_handoff_handlers.go`,
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index af9f3aa347..8d1104bbae 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -762,6 +762,22 @@ runtime cost control, and shared AI transport surfaces.
return the updated `ChatSession`, update the visible row without closing the
picker, and leave messages, handoff context, approvals, and tool evidence
unchanged.
+ Assistant turn undo/redo is also a source-backed session repair workflow,
+ not a transcript-local delete button. The referenced OpenCode source in
+ `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx` registers
+ `session.undo` and `session.redo` as first-class session commands and uses
+ runtime revert/unrevert responses to restore the user's prompt into the
+ composer. Pulse adapts that behavior through
+ `POST /api/ai/sessions/{id}/undo` and
+ `POST /api/ai/sessions/{id}/redo`: the backend session store must remove the
+ latest user-authored turn plus following assistant/tool messages as one
+ durable turn, persist a bounded redo stack, expose `can_redo` on the
+ browser-safe session summary, clear redo state when a new message or trim
+ changes the transcript, and keep forked sessions independent from the source
+ redo stack. The drawer must restore the removed prompt, structured mentions,
+ finding id, handoff metadata, approval/autonomous override, and selected
+ model route when available so the operator can edit and resend without
+ reconstructing hidden context from transcript prose.
The empty Assistant drawer may surface recent non-empty sessions as direct
resume actions using the backend session list already owned by the drawer;
it must not create a parallel recent-chat store or product-authored prompt
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index d08d3b0823..8c8caf81d6 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -444,10 +444,25 @@ payload shape change when the portal presents compact client rows.
browser-safe `ChatSession` projection. Rename must not expose or mutate
stored prompts, messages, provider reasoning, model handoff context,
approvals, action state, or tool evidence. Browser clients must call the
- shared `AIChatAPI.renameSession(sessionId, title)` helper so path encoding
- and JSON body shape stay canonical.
- Resource-context follow-up turns are different from Patrol-run rehydration:
- browser-safe `handoff_metadata.kind=resource_context` must not replace a
+ shared `AIChatAPI.renameSession(sessionId, title)` helper so path encoding
+ and JSON body shape stay canonical.
+ `POST /api/ai/sessions/{id}/undo` and
+ `POST /api/ai/sessions/{id}/redo` own the Assistant turn-repair API
+ contract. Undo removes the latest user-authored turn and all later
+ assistant/tool messages as one durable unit, returns a browser-safe
+ `restored_prompt`, `removed_messages`, and `can_redo`, and must not expose
+ provider reasoning, raw tool output, model-only handoff text, approval
+ payload internals, or remediation command data. Redo restores the latest
+ undone turn and returns `restored_messages` plus the remaining `can_redo`
+ state. `GET /api/ai/sessions` and other `ChatSession` projections may
+ expose only the boolean `can_redo` hint alongside safe title/timestamp,
+ count, and handoff-summary fields so the drawer can re-enable redo after a
+ reload without reading the redo stack itself. Browser clients must use the
+ shared `AIChatAPI.undoLastTurn(sessionId)` and
+ `AIChatAPI.redoLastTurn(sessionId)` helpers so path encoding and response
+ shape stay canonical.
+ Resource-context follow-up turns are different from Patrol-run rehydration:
+ browser-safe `handoff_metadata.kind=resource_context` must not replace a
stored rich handoff envelope with a partial metadata-only envelope, and the
handler must not ask the browser to resend resource context that the chat
runtime can rehydrate from the stored selected-resource envelope.
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 07453c0cc4..f1aa8b0df8 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -317,6 +317,13 @@ scan-friendly without hiding any container from drilldown.
`handoffMetadata` while preserving the safe visible briefing and scoped
approval-required posture, so later turns rely on backend session hydration
instead of resending stale browser context. Patrol handoffs must not include
+ Persisted Assistant redo availability is safe session chrome, not transcript
+ content. The drawer may consume `ChatSession.can_redo` from the backend
+ session list to re-enable Redo after reload or session refresh, but it must
+ not read or duplicate the redo stack in frontend state. Undo restores the
+ editable prompt draft and safe structured send metadata into the composer;
+ Redo clears that recovered draft only after the backend restores the turn.
+ Patrol handoffs must not include
safe next-step labels, action kinds, or whitelisted app-route hrefs in
`handoffMetadata`; the drawer must treat
`handoff_summary.requires_approval` as a current pending-decision flag, not a
@@ -2314,6 +2321,11 @@ selection, and `frontend-modern/src/components/shared/commandPaletteModel.ts`
owns canonical command construction plus query normalization and filtering
policy. Future command-palette work should extend those owners instead of
pushing route construction or search policy back into the shared shell.
+Assistant command-palette actions are shell requests, not duplicated chat
+logic. New session, session picker, model picker, Undo, and Redo commands must
+flow through the shared `frontend-modern/src/stores/aiChat.ts` command request
+contract so the drawer owns disabled/loading state, prompt restoration, and
+notifications while the palette remains only a searchable command surface.
The shared search field now follows that same owner split.
`frontend-modern/src/components/shared/SearchField.tsx` stays the render shell,
`frontend-modern/src/components/shared/useSearchFieldState.ts` owns focused-
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 89993ec602..c767f02054 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -236,6 +236,12 @@ regression protection.
capability check, but router setup and auth gating must not scan session
files, load transcripts, hydrate handoff context, or inspect model/tool
history before the route-local handler owns the single title mutation.
+ Assistant session undo/redo routing follows the same bounded router rule:
+ `POST /api/ai/sessions/{id}/undo` and
+ `POST /api/ai/sessions/{id}/redo` may branch to the AI handler after normal
+ auth/scope checks, but router setup must not scan sessions, read redo stacks,
+ hydrate transcripts, or perform model/provider work before the route-local
+ handler owns the single session mutation.
Report branding follows the same bounded-work rule. Reporting handlers may
read provider-default env configuration and a tenant-local system-settings
record when a report is generated, but router setup and normal protected
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index f6742c275e..f6a3f43af0 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -170,12 +170,20 @@ controls as normal product settings.
read-only Agent-context boundary. Router glue may connect providers, but
it must not become an alternate command path, raw provider-command path,
config path, environment path, or secret-bearing metadata path.
- Assistant session rename routing through `PATCH /api/ai/sessions/{id}`
- stays on that same auth/scope boundary: the route may accept only a
- user-visible title mutation, must not expose transcript contents,
- provider-bound model context, tool evidence, approvals, or action state,
- and must not treat title text as trusted secret-bearing or command-bearing
- input.
+ Assistant session rename routing through `PATCH /api/ai/sessions/{id}`
+ stays on that same auth/scope boundary: the route may accept only a
+ user-visible title mutation, must not expose transcript contents,
+ provider-bound model context, tool evidence, approvals, or action state,
+ and must not treat title text as trusted secret-bearing or command-bearing
+ input.
+ Assistant session undo/redo routing through
+ `POST /api/ai/sessions/{id}/undo` and
+ `POST /api/ai/sessions/{id}/redo` stays on that same trust boundary:
+ responses may expose only browser-safe repair metadata such as restored
+ prompt text, removed/restored message counts, and `can_redo`; they must
+ not expose redo-stack internals, provider reasoning, raw tool output,
+ model-only handoff text, approval payload internals, environment data, or
+ command-bearing remediation details.
## Forbidden Paths
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 7ca72a73b3..86e2df9d16 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -215,6 +215,12 @@ conversation may make protected-item investigation easier to find, but title
text must not become backup coverage evidence, restore entitlement,
storage-owner identity, approval policy, or a provider-local recovery command
handoff.
+Assistant session undo/redo through `POST /api/ai/sessions/{id}/undo` and
+`POST /api/ai/sessions/{id}/redo` is likewise adjacent conversation repair
+state only. A restored prompt or restored message count may help an operator
+continue a protected-item investigation, but it must not become backup coverage
+evidence, recovery freshness, restore entitlement, storage-owner identity,
+approval policy, or a provider-local recovery command handoff.
Storage and recovery may also consume unified-resource TrueNAS app and VM
metadata, TrueNAS native service metadata, plus TrueNAS network-share metadata,
as read-only workload, system, and storage-access context when explaining
@@ -653,6 +659,10 @@ recovery scope, or a storage/recovery-owned secret source.
recovery surfaces may not reinterpret search hits, handoff summaries, or
message counts as backup coverage, recovery freshness, restore capability,
or storage-local action authority.
+ The `can_redo` flag on that same session-list projection is only Assistant
+ conversation repair state. It must not be interpreted as recovery
+ reversibility, restore availability, backup freshness, or any storage-local
+ undo capability.
That same adjacent `internal/api/` boundary still carries Patrol-run
execution identity. Storage and recovery may observe shared Patrol
transport through `internal/api/chat_service_adapter.go`, but they must not
diff --git a/frontend-modern/src/api/__tests__/aiChat.test.ts b/frontend-modern/src/api/__tests__/aiChat.test.ts
index 0563b482ea..a701c22699 100644
--- a/frontend-modern/src/api/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts
@@ -149,6 +149,7 @@ describe('AIChatAPI', () => {
created_at: '2026-05-06T12:00:00Z',
updated_at: '2026-05-06T12:08:00Z',
message_count: 2,
+ can_redo: true,
handoff_summary: {
kind: 'patrol_finding',
finding_id: 'finding-operator-briefing',
@@ -215,6 +216,33 @@ describe('AIChatAPI', () => {
});
});
+ it('undoes and redoes chat turns through explicit session endpoints', async () => {
+ const undoResult = {
+ success: true,
+ session_id: 'session/root',
+ restored_prompt: 'show me the affected hosts',
+ removed_messages: 2,
+ can_redo: true,
+ };
+ const redoResult = {
+ success: true,
+ session_id: 'session/root',
+ restored_messages: 2,
+ can_redo: false,
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(undoResult).mockResolvedValueOnce(redoResult);
+
+ await expect(AIChatAPI.undoLastTurn('session/root')).resolves.toEqual(undoResult);
+ await expect(AIChatAPI.redoLastTurn('session/root')).resolves.toEqual(redoResult);
+
+ expect(apiFetchJSONMock).toHaveBeenNthCalledWith(1, '/api/ai/sessions/session%2Froot/undo', {
+ method: 'POST',
+ });
+ expect(apiFetchJSONMock).toHaveBeenNthCalledWith(2, '/api/ai/sessions/session%2Froot/redo', {
+ method: 'POST',
+ });
+ });
+
it('preserves restored Assistant tool evidence on session messages', async () => {
const messages = [
{
diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.ts
index f82e1d4e8a..7bfbf21eb8 100644
--- a/frontend-modern/src/api/aiChat.ts
+++ b/frontend-modern/src/api/aiChat.ts
@@ -12,9 +12,27 @@ export interface ChatSession {
created_at: string;
updated_at: string;
message_count: number;
+ can_redo?: boolean;
handoff_summary?: ChatSessionHandoffSummary;
}
+export interface ChatSessionUndoResult {
+ success: boolean;
+ session_id: string;
+ restored_prompt?: string;
+ removed_messages?: number;
+ can_redo: boolean;
+ message?: string;
+}
+
+export interface ChatSessionRedoResult {
+ success: boolean;
+ session_id: string;
+ restored_messages?: number;
+ can_redo: boolean;
+ message?: string;
+}
+
export interface ListChatSessionsOptions {
search?: string;
limit?: number;
@@ -303,6 +321,20 @@ export class AIChatAPI {
}) as Promise<ChatSession>;
}
+ // Undo latest chat turn and return the user prompt so the composer can restore it.
+ static async undoLastTurn(sessionId: string): Promise<ChatSessionUndoResult> {
+ return apiFetchJSON(`${this.baseUrl}/sessions/${encodeURIComponent(sessionId)}/undo`, {
+ method: 'POST',
+ }) as Promise<ChatSessionUndoResult>;
+ }
+
+ // Redo the latest chat turn removed by undoLastTurn.
+ static async redoLastTurn(sessionId: string): Promise<ChatSessionRedoResult> {
+ return apiFetchJSON(`${this.baseUrl}/sessions/${encodeURIComponent(sessionId)}/redo`, {
+ method: 'POST',
+ }) as Promise<ChatSessionRedoResult>;
+ }
+
// Revert session changes
static async revertSession(sessionId: string): Promise<{ success: boolean }> {
return apiFetchJSON(`${this.baseUrl}/sessions/${encodeURIComponent(sessionId)}/revert`, {
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
index 2728b77827..989ef48973 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -45,6 +45,8 @@ const {
queuedFollowUpCount: vi.fn(() => 0),
sendMessage: vi.fn().mockResolvedValue(true),
retryMessage: vi.fn(),
+ undoLastTurn: vi.fn().mockResolvedValue(null),
+ redoLastTurn: vi.fn().mockResolvedValue({ success: false, canRedo: false }),
stop: vi.fn(),
cancelQueuedFollowUp: vi.fn(),
takeQueuedFollowUp: vi.fn((): QueuedFollowUp | undefined => undefined),
@@ -128,8 +130,11 @@ const {
const mockAiChatStore = {
isOpenSignal: vi.fn(() => true),
- commandRequestSignal: vi.fn((): { id: number; action: 'new' | 'sessions' | 'models' } | null =>
- null,
+ commandRequestSignal: vi.fn(
+ (): {
+ id: number;
+ action: 'new' | 'sessions' | 'models' | 'undo' | 'redo';
+ } | null => null,
),
ackCommandRequest: vi.fn(),
context: emptyChatContext() as {
@@ -414,6 +419,8 @@ beforeEach(() => {
mockChat.queuedFollowUps.mockReturnValue([]);
mockChat.queuedFollowUpCount.mockReturnValue(0);
mockChat.sendMessage.mockResolvedValue(true);
+ mockChat.undoLastTurn.mockResolvedValue(null);
+ mockChat.redoLastTurn.mockResolvedValue({ success: false, canRedo: false });
mockChat.takeQueuedFollowUp.mockReturnValue(undefined);
mockByType.mockReturnValue([]);
mockResources.mockReturnValue([]);
@@ -2393,6 +2400,91 @@ describe('AIChat', () => {
expect(mockNotificationStore.error).toHaveBeenCalledWith('Failed to fork Assistant session');
});
+ it('undoes the latest Assistant turn and restores the prompt for editing', async () => {
+ mockChat.sessionId.mockReturnValue('session-undo');
+ mockChat.messages.mockReturnValue([
+ {
+ id: 'user-1',
+ role: 'user',
+ content: 'inspect vm-101',
+ timestamp: new Date('2026-06-06T12:34:56Z'),
+ },
+ {
+ id: 'assistant-1',
+ role: 'assistant',
+ content: 'vm-101 has stale guest tools.',
+ timestamp: new Date('2026-06-06T12:35:01Z'),
+ },
+ ]);
+ mockChat.undoLastTurn.mockResolvedValue({
+ prompt: 'inspect vm-101',
+ request: {
+ mentions: [{ id: 'vm:pve:101', name: 'vm-101', type: 'vm', node: 'pve' }],
+ findingId: 'finding-101',
+ model: 'openrouter:deepseek/deepseek-chat',
+ autonomousMode: false,
+ handoffContext: '[Patrol Finding Context]\nVM 101 has stale guest tools',
+ },
+ });
+
+ renderChat();
+ fireEvent.click(screen.getByRole('button', { name: 'Undo last Assistant turn' }));
+
+ const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
+ await waitFor(() => {
+ expect(mockChat.undoLastTurn).toHaveBeenCalledTimes(1);
+ expect(textarea).toHaveValue('inspect vm-101');
+ });
+ expect(mockNotificationStore.success).toHaveBeenCalledWith(
+ 'Last prompt restored for editing',
+ 2000,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
+
+ await waitFor(() => {
+ expect(mockChat.sendMessage).toHaveBeenCalledWith(
+ 'inspect vm-101',
+ [{ id: 'vm:pve:101', name: 'vm-101', type: 'vm', node: 'pve' }],
+ 'finding-101',
+ expect.objectContaining({
+ autonomousMode: false,
+ handoffContext: '[Patrol Finding Context]\nVM 101 has stale guest tools',
+ model: 'openrouter:deepseek/deepseek-chat',
+ }),
+ );
+ });
+ });
+
+ it('redoes the latest undone Assistant turn from the header', async () => {
+ mockChat.sessionId.mockReturnValue('session-redo');
+ mockChat.messages.mockReturnValue([
+ {
+ id: 'user-1',
+ role: 'user',
+ content: 'inspect vm-101',
+ timestamp: new Date('2026-06-06T12:34:56Z'),
+ },
+ ]);
+ mockChat.undoLastTurn.mockResolvedValue({ prompt: 'inspect vm-101' });
+ mockChat.redoLastTurn.mockResolvedValue({ success: true, canRedo: false });
+
+ renderChat();
+ fireEvent.click(screen.getByRole('button', { name: 'Undo last Assistant turn' }));
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Redo last Assistant turn' })).not.toBeDisabled();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Redo last Assistant turn' }));
+
+ await waitFor(() => {
+ expect(mockChat.redoLastTurn).toHaveBeenCalledTimes(1);
+ });
+ expect(screen.getByPlaceholderText('Ask about your infrastructure...')).toHaveValue('');
+ expect(mockNotificationStore.success).toHaveBeenCalledWith('Assistant turn restored', 2000);
+ });
+
it('opens session picker on click', async () => {
renderChat();
const sessionButton = screen.getByRole('button', { name: 'Pulse Assistant sessions' });
@@ -2465,6 +2557,29 @@ describe('AIChat', () => {
});
});
+ it('restores redo availability from the active saved session summary', async () => {
+ mockChat.sessionId.mockReturnValue('session-with-redo');
+ mockAIChatAPI.listSessions.mockResolvedValue([
+ {
+ id: 'session-with-redo',
+ title: 'Needs redo',
+ created_at: '2026-06-06T12:30:00Z',
+ updated_at: '2026-06-06T12:35:00Z',
+ message_count: 1,
+ can_redo: true,
+ },
+ ]);
+
+ renderChat();
+ await waitFor(() => {
+ expect(mockAIChatAPI.listSessions).toHaveBeenCalled();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Redo last Assistant turn' })).not.toBeDisabled();
+ });
+ });
+
it('moves keyboard focus through session picker results', async () => {
mockAIChatAPI.listSessions.mockResolvedValue([
{ id: 's1', title: 'Session One', created_at: '', updated_at: '', message_count: 5 },
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/assistantSlashCommands.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/assistantSlashCommands.test.ts
index 5b285ba9cb..e7c47eea55 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/assistantSlashCommands.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/assistantSlashCommands.test.ts
@@ -18,6 +18,8 @@ describe('assistantSlashCommands', () => {
expect(parseAssistantSlashCommand('/copy')).toBe('copy');
expect(parseAssistantSlashCommand('/export')).toBe('export');
expect(parseAssistantSlashCommand('/fork')).toBe('fork');
+ expect(parseAssistantSlashCommand('/undo')).toBe('undo');
+ expect(parseAssistantSlashCommand('/redo')).toBe('redo');
});
it('normalizes casing and surrounding whitespace', () => {
@@ -39,8 +41,10 @@ describe('assistantSlashCommands', () => {
'copy',
'export',
'fork',
+ 'undo',
+ 'redo',
]);
- expect(filterAssistantSlashCommands('res').map((command) => command.name)).toEqual([
+ expect(filterAssistantSlashCommands('resume').map((command) => command.name)).toEqual([
'sessions',
]);
expect(filterAssistantSlashCommands('provider').map((command) => command.name)).toEqual([
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
index c14e05835c..b1ed3eb725 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
@@ -9,6 +9,8 @@ vi.mock('@/api/aiChat', () => ({
getMessages: vi.fn(),
abortSession: vi.fn(),
answerQuestion: vi.fn(),
+ undoLastTurn: vi.fn(),
+ redoLastTurn: vi.fn(),
},
}));
@@ -38,6 +40,8 @@ const mockChat = AIChatAPI.chat as ReturnType<typeof vi.fn>;
const mockGetMessages = AIChatAPI.getMessages as ReturnType<typeof vi.fn>;
const mockAbortSession = AIChatAPI.abortSession as ReturnType<typeof vi.fn>;
const mockAnswerQuestion = AIChatAPI.answerQuestion as ReturnType<typeof vi.fn>;
+const mockUndoLastTurn = AIChatAPI.undoLastTurn as ReturnType<typeof vi.fn>;
+const mockRedoLastTurn = AIChatAPI.redoLastTurn as ReturnType<typeof vi.fn>;
const mockNotifyError = notificationStore.error as ReturnType<typeof vi.fn>;
type TestStreamEvent = StreamEvent | { type: string; data?: unknown };
@@ -67,6 +71,18 @@ describe('useChat', () => {
beforeEach(() => {
vi.resetAllMocks();
mockAbortSession.mockResolvedValue(undefined);
+ mockUndoLastTurn.mockResolvedValue({
+ success: false,
+ session_id: 's',
+ can_redo: false,
+ message: 'No user turn to undo.',
+ });
+ mockRedoLastTurn.mockResolvedValue({
+ success: false,
+ session_id: 's',
+ can_redo: false,
+ message: 'No undone turn to redo.',
+ });
});
// ──────────────────────────────────────────────
@@ -83,6 +99,8 @@ describe('useChat', () => {
expect(chat.queuedFollowUpCount()).toBe(0);
expect(typeof chat.sendMessage).toBe('function');
expect(typeof chat.retryMessage).toBe('function');
+ expect(typeof chat.undoLastTurn).toBe('function');
+ expect(typeof chat.redoLastTurn).toBe('function');
expect(typeof chat.stop).toBe('function');
expect(typeof chat.cancelQueuedFollowUp).toBe('function');
expect(typeof chat.takeQueuedFollowUp).toBe('function');
@@ -2402,6 +2420,78 @@ describe('useChat', () => {
});
});
+ // ──────────────────────────────────────────────
+ // undo / redo
+ // ──────────────────────────────────────────────
+ describe('undo and redo', () => {
+ it('undoes the latest turn, reloads the session, and returns the editable prompt draft', async () => {
+ const mentions: ChatMention[] = [
+ { id: 'vm:pve:101', name: 'vm-101', type: 'vm', node: 'pve' },
+ ];
+ mockChat.mockResolvedValue(undefined);
+ mockUndoLastTurn.mockResolvedValue({
+ success: true,
+ session_id: 'sess-undo',
+ restored_prompt: 'inspect vm-101',
+ removed_messages: 2,
+ can_redo: true,
+ });
+ mockGetMessages.mockResolvedValue([
+ {
+ id: 'msg-previous',
+ role: 'assistant',
+ content: 'Previous answer',
+ timestamp: '2026-06-06T12:00:00Z',
+ },
+ ]);
+
+ const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 'sess-undo' }));
+ await chat.sendMessage('inspect vm-101', mentions, 'finding-101', {
+ model: 'openrouter:deepseek/deepseek-chat',
+ autonomousMode: false,
+ handoffContext: '[Patrol Finding Context]\nVM 101 has stale guest tools',
+ });
+
+ const draft = await chat.undoLastTurn();
+
+ expect(mockUndoLastTurn).toHaveBeenCalledWith('sess-undo');
+ expect(mockGetMessages).toHaveBeenCalledWith('sess-undo');
+ expect(chat.messages()).toHaveLength(1);
+ expect(draft).toEqual({
+ prompt: 'inspect vm-101',
+ request: {
+ mentions,
+ findingId: 'finding-101',
+ model: 'openrouter:deepseek/deepseek-chat',
+ autonomousMode: false,
+ handoffContext: '[Patrol Finding Context]\nVM 101 has stale guest tools',
+ },
+ });
+ dispose();
+ });
+
+ it('redoes an undone turn and returns remaining redo availability', async () => {
+ mockRedoLastTurn.mockResolvedValue({
+ success: true,
+ session_id: 'sess-redo',
+ restored_messages: 2,
+ can_redo: true,
+ });
+ mockGetMessages.mockResolvedValue([
+ { id: 'msg-1', role: 'user', content: 'hello', timestamp: '2026-06-06T12:00:00Z' },
+ ]);
+
+ const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 'sess-redo' }));
+ const result = await chat.redoLastTurn();
+
+ expect(mockRedoLastTurn).toHaveBeenCalledWith('sess-redo');
+ expect(mockGetMessages).toHaveBeenCalledWith('sess-redo');
+ expect(result).toEqual({ success: true, canRedo: true });
+ expect(chat.messages()).toHaveLength(1);
+ dispose();
+ });
+ });
+
// ──────────────────────────────────────────────
// newSession
// ──────────────────────────────────────────────
diff --git a/frontend-modern/src/components/AI/Chat/assistantSlashCommands.ts b/frontend-modern/src/components/AI/Chat/assistantSlashCommands.ts
index 2ef428ecaf..9af3e37876 100644
--- a/frontend-modern/src/components/AI/Chat/assistantSlashCommands.ts
+++ b/frontend-modern/src/components/AI/Chat/assistantSlashCommands.ts
@@ -4,6 +4,8 @@ export type AssistantSlashCommandAction =
| 'fork'
| 'models'
| 'new'
+ | 'redo'
+ | 'undo'
| 'sessions';
export interface AssistantSlashCommand {
@@ -47,6 +49,16 @@ export const ASSISTANT_SLASH_COMMANDS: AssistantSlashCommand[] = [
action: 'fork',
description: 'Fork this session into a new copy',
},
+ {
+ name: 'undo',
+ action: 'undo',
+ description: 'Restore the last prompt for editing',
+ },
+ {
+ name: 'redo',
+ action: 'redo',
+ description: 'Restore the last undone turn',
+ },
];
const commandByToken = new Map<string, AssistantSlashCommandAction>(
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index 25e1313391..6e4b4c3ddb 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -64,6 +64,16 @@ export interface QueuedFollowUp {
timestamp: Date;
}
+export interface RestoredPromptDraft {
+ prompt: string;
+ request?: ChatMessageRequestContext;
+}
+
+export interface RedoTurnResult {
+ success: boolean;
+ canRedo: boolean;
+}
+
export function useChat(options: UseChatOptions = {}) {
// Core state
const [messages, setMessages] = createSignal<ChatMessage[]>([]);
@@ -728,6 +738,40 @@ export function useChat(options: UseChatOptions = {}) {
const cloneMentions = (mentions?: ChatMention[]): ChatMention[] | undefined =>
mentions?.map((mention) => ({ ...mention }));
+ const cloneRequestContext = (
+ request?: ChatMessageRequestContext,
+ ): ChatMessageRequestContext | undefined => {
+ if (!request) return undefined;
+
+ const cloned: ChatMessageRequestContext = {};
+ if (request.mentions?.length) {
+ cloned.mentions = cloneMentions(request.mentions);
+ }
+ if (request.findingId) {
+ cloned.findingId = request.findingId;
+ }
+ if (request.model) {
+ cloned.model = request.model;
+ }
+ if (typeof request.autonomousMode === 'boolean') {
+ cloned.autonomousMode = request.autonomousMode;
+ }
+ if (request.handoffContext) {
+ cloned.handoffContext = request.handoffContext;
+ }
+ if (request.handoffResources?.length) {
+ cloned.handoffResources = request.handoffResources.map((resource) => ({ ...resource }));
+ }
+ if (request.handoffActions?.length) {
+ cloned.handoffActions = request.handoffActions.map((action) => ({ ...action }));
+ }
+ if (request.handoffMetadata) {
+ cloned.handoffMetadata = { ...request.handoffMetadata };
+ }
+
+ return Object.keys(cloned).length > 0 ? cloned : undefined;
+ };
+
const cloneSendOptions = (
sendOptions?: SendMessageOptions,
): ChatMessageRequestContext | undefined => {
@@ -1651,6 +1695,61 @@ export function useChat(options: UseChatOptions = {}) {
return true;
};
+ const latestUserPromptDraft = (): RestoredPromptDraft | null => {
+ const currentMessages = messages();
+ for (let index = currentMessages.length - 1; index >= 0; index -= 1) {
+ const message = currentMessages[index];
+ if (message.role !== 'user' || !message.content.trim() || message.delivery === 'queued') {
+ continue;
+ }
+ return {
+ prompt: message.content,
+ request: cloneRequestContext(message.request),
+ };
+ }
+ return null;
+ };
+
+ const undoLastTurn = async (): Promise<RestoredPromptDraft | null> => {
+ const currentSessionId = sessionId().trim();
+ if (!currentSessionId || isLoading()) return null;
+
+ const localDraft = latestUserPromptDraft();
+ const result = await AIChatAPI.undoLastTurn(currentSessionId);
+ if (!result.success) {
+ if (result.message) {
+ notificationStore.info(result.message);
+ }
+ return null;
+ }
+
+ await loadSession(currentSessionId);
+ await notifyConversationChanged();
+ const prompt = localDraft?.prompt || result.restored_prompt || '';
+ if (!prompt.trim()) return null;
+ return {
+ prompt,
+ request: localDraft?.request,
+ };
+ };
+
+ const redoLastTurn = async (): Promise<RedoTurnResult> => {
+ const currentSessionId = sessionId().trim();
+ if (!currentSessionId || isLoading()) return { success: false, canRedo: false };
+
+ const result = await AIChatAPI.redoLastTurn(currentSessionId);
+ if (!result.success) {
+ if (result.message) {
+ notificationStore.info(result.message);
+ }
+ return { success: false, canRedo: result.can_redo };
+ }
+
+ const loaded = await loadSession(currentSessionId);
+ await notifyConversationChanged();
+ return { success: loaded, canRedo: result.can_redo };
+ };
+
// Update pending approval state (e.g., to mark as executing or remove)
const updateApproval = (
messageId: string,
@@ -1861,6 +1960,8 @@ export function useChat(options: UseChatOptions = {}) {
queuedFollowUpCount: () => queuedFollowUps().length,
sendMessage,
retryMessage,
+ undoLastTurn,
+ redoLastTurn,
stop,
cancelQueuedFollowUp,
takeQueuedFollowUp,
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index cfb0235153..43b6e06c74 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -17,9 +17,11 @@ import CopyIcon from 'lucide-solid/icons/copy';
import DownloadIcon from 'lucide-solid/icons/download';
import GitForkIcon from 'lucide-solid/icons/git-fork';
import PencilIcon from 'lucide-solid/icons/pencil';
+import Redo2Icon from 'lucide-solid/icons/redo-2';
import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
import RotateCwIcon from 'lucide-solid/icons/rotate-cw';
import SettingsIcon from 'lucide-solid/icons/settings';
+import Undo2Icon from 'lucide-solid/icons/undo-2';
import XIcon from 'lucide-solid/icons/x';
import BookmarkIcon from 'lucide-solid/icons/bookmark';
import CheckIcon from 'lucide-solid/icons/check';
@@ -27,7 +29,12 @@ import LoaderCircleIcon from 'lucide-solid/icons/loader-circle';
import PlusIcon from 'lucide-solid/icons/plus';
import Trash2Icon from 'lucide-solid/icons/trash-2';
import { AIAPI } from '@/api/ai';
-import { AIChatAPI, type ChatSession, type ChatSessionHandoffSummary } from '@/api/aiChat';
+import {
+ AIChatAPI,
+ type ChatMention,
+ type ChatSession,
+ type ChatSessionHandoffSummary,
+} from '@/api/aiChat';
import { SearchField } from '@/components/shared/SearchField';
import { notificationStore } from '@/stores/notifications';
import { aiChatStore, type AIChatContext } from '@/stores/aiChat';
@@ -71,6 +78,11 @@ import {
AI_CHAT_PROVIDER_READINESS_RETRY_LABEL,
AI_CHAT_PROVIDER_READINESS_SETTINGS_HREF,
AI_CHAT_PROVIDER_READINESS_SETTINGS_LABEL,
+ AI_CHAT_REDO_LAST_TURN_EMPTY_MESSAGE,
+ AI_CHAT_REDO_LAST_TURN_ERROR_MESSAGE,
+ AI_CHAT_REDO_LAST_TURN_LABEL,
+ AI_CHAT_REDO_LAST_TURN_LOADING_MESSAGE,
+ AI_CHAT_REDO_LAST_TURN_SUCCESS_MESSAGE,
AI_CHAT_RENAME_SESSION_CANCEL_LABEL,
AI_CHAT_RENAME_SESSION_EMPTY_MESSAGE,
AI_CHAT_RENAME_SESSION_ERROR_MESSAGE,
@@ -89,6 +101,11 @@ import {
AI_CHAT_TRANSCRIPT_FALLBACK_DOWNLOAD_LABEL,
AI_CHAT_TRANSCRIPT_FALLBACK_TEXTAREA_LABEL,
AI_CHAT_TRANSCRIPT_FALLBACK_TITLE,
+ AI_CHAT_UNDO_LAST_TURN_EMPTY_MESSAGE,
+ AI_CHAT_UNDO_LAST_TURN_ERROR_MESSAGE,
+ AI_CHAT_UNDO_LAST_TURN_LABEL,
+ AI_CHAT_UNDO_LAST_TURN_LOADING_MESSAGE,
+ AI_CHAT_UNDO_LAST_TURN_SUCCESS_MESSAGE,
getAIChatProviderReadinessPresentation,
} from '@/utils/aiChatPresentation';
import {
@@ -117,7 +134,12 @@ import {
getPreferredResourceHostname,
} from '@/utils/resourceIdentity';
import { useBreakpoint } from '@/hooks/useBreakpoint';
-import { useChat, type QueuedFollowUp, type SendMessageOptions } from './hooks/useChat';
+import {
+ useChat,
+ type QueuedFollowUp,
+ type RestoredPromptDraft,
+ type SendMessageOptions,
+} from './hooks/useChat';
import { ChatMessages } from './ChatMessages';
import { ModelSelector } from './ModelSelector';
import { MentionAutocomplete, type MentionResource } from './MentionAutocomplete';
@@ -193,6 +215,7 @@ interface ComposerDraftStash {
cursorStart: number;
cursorEnd: number;
editingQueuedFollowUp: QueuedFollowUp | null;
+ restoredPromptDraft: RestoredPromptDraft | null;
}
interface AssistantUsageSummary {
@@ -585,6 +608,9 @@ export const AIChat: Component<AIChatProps> = (props) => {
const [editingQueuedFollowUp, setEditingQueuedFollowUp] = createSignal<QueuedFollowUp | null>(
null,
);
+ const [restoredPromptDraft, setRestoredPromptDraft] = createSignal<RestoredPromptDraft | null>(
+ null,
+ );
const [interruptArmed, setInterruptArmed] = createSignal(false);
const [promptHistory, setPromptHistory] = createSignal<PromptHistoryEntry[]>([]);
const [promptHistoryIndex, setPromptHistoryIndex] = createSignal(-1);
@@ -601,6 +627,9 @@ export const AIChat: Component<AIChatProps> = (props) => {
const [sessionRenameSaving, setSessionRenameSaving] = createSignal(false);
const [sessionDropdownPosition, setSessionDropdownPosition] = createSignal({ top: 0, right: 0 });
const [forkingSession, setForkingSession] = createSignal(false);
+ const [undoingLastTurn, setUndoingLastTurn] = createSignal(false);
+ const [redoingLastTurn, setRedoingLastTurn] = createSignal(false);
+ const [redoLastTurnAvailable, setRedoLastTurnAvailable] = createSignal(false);
let sessionButtonRef: HTMLButtonElement | undefined;
let sessionSearchInputRef: HTMLInputElement | undefined;
let sessionRenameInputRef: HTMLInputElement | undefined;
@@ -691,6 +720,25 @@ export const AIChat: Component<AIChatProps> = (props) => {
};
};
+ const cloneRestoredPromptDraft = (
+ draft: RestoredPromptDraft | null,
+ ): RestoredPromptDraft | null => {
+ if (!draft) return null;
+ const request = draft.request;
+ return {
+ prompt: draft.prompt,
+ request: request
+ ? {
+ ...request,
+ mentions: request.mentions?.map((mention) => ({ ...mention })),
+ handoffResources: request.handoffResources?.map((resource) => ({ ...resource })),
+ handoffActions: request.handoffActions?.map((action) => ({ ...action })),
+ handoffMetadata: request.handoffMetadata ? { ...request.handoffMetadata } : undefined,
+ }
+ : undefined,
+ };
+ };
+
const cloneQueuedFollowUp = (queued: QueuedFollowUp): QueuedFollowUp => ({
...queued,
mentions: queued.mentions?.map((mention) => ({ ...mention })),
@@ -762,7 +810,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
const text = input();
const mentions = accumulatedMentions();
const queuedDraft = editingQueuedFollowUp();
- if (!text.trim() && mentions.length === 0 && !queuedDraft) {
+ const restoredDraft = restoredPromptDraft();
+ if (!text.trim() && mentions.length === 0 && !queuedDraft && !restoredDraft) {
stashedComposerDraft = null;
return;
}
@@ -774,6 +823,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
cursorStart: textareaRef?.selectionStart ?? fallbackCursor,
cursorEnd: textareaRef?.selectionEnd ?? fallbackCursor,
editingQueuedFollowUp: queuedDraft ? cloneQueuedFollowUp(queuedDraft) : null,
+ restoredPromptDraft: cloneRestoredPromptDraft(restoredDraft),
};
};
@@ -788,6 +838,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
setEditingQueuedFollowUp(
draft.editingQueuedFollowUp ? cloneQueuedFollowUp(draft.editingQueuedFollowUp) : null,
);
+ setRestoredPromptDraft(cloneRestoredPromptDraft(draft.restoredPromptDraft));
setMentionActive(false);
setSlashCommandActive(false);
resetPromptHistoryNavigation();
@@ -1232,6 +1283,14 @@ export const AIChat: Component<AIChatProps> = (props) => {
onConversationChanged: refreshSessions,
});
+ createEffect(() => {
+ const currentSessionId = chat.sessionId().trim();
+ if (!currentSessionId) return;
+ const session = findKnownSession(currentSessionId);
+ if (!session) return;
+ setRedoLastTurnAvailable(Boolean(session.can_redo));
+ });
+
const stopActiveResponse = () => {
clearInterruptArm();
chat.stop();
@@ -1246,25 +1305,64 @@ export const AIChat: Component<AIChatProps> = (props) => {
return firstLine || 'Queued follow-up';
};
- const restoreQueuedMentions = (mentions?: QueuedFollowUp['mentions']) => {
+ const restoreChatMentions = (mentions?: ChatMention[]) => {
setAccumulatedMentions(
(mentions || []).map((mention) => ({
id: mention.id,
- label: mention.name,
+ label: mention.name || mention.id,
type: mention.type,
node: mention.node,
})),
);
};
+ const sendOptionsFromRestoredRequest = (
+ request?: RestoredPromptDraft['request'],
+ ): SendMessageOptions => {
+ if (!request) return {};
+ const sendOptions: SendMessageOptions = {};
+ if (request.model) {
+ sendOptions.model = request.model;
+ }
+ if (typeof request.autonomousMode === 'boolean') {
+ sendOptions.autonomousMode = request.autonomousMode;
+ }
+ if (request.handoffContext) {
+ sendOptions.handoffContext = request.handoffContext;
+ }
+ if (request.handoffResources?.length) {
+ sendOptions.handoffResources = request.handoffResources.map((resource) => ({ ...resource }));
+ }
+ if (request.handoffActions?.length) {
+ sendOptions.handoffActions = request.handoffActions.map((action) => ({ ...action }));
+ }
+ if (request.handoffMetadata) {
+ sendOptions.handoffMetadata = { ...request.handoffMetadata };
+ }
+ return sendOptions;
+ };
+
const editQueuedFollowUp = (id: string) => {
const queued = chat.takeQueuedFollowUp(id);
if (!queued) return;
resetPromptHistoryNavigation();
setEditingQueuedFollowUp(queued);
+ setRestoredPromptDraft(null);
setInput(queued.prompt);
- restoreQueuedMentions(queued.mentions);
+ restoreChatMentions(queued.mentions);
+ setMentionActive(false);
+ focusComposer();
+ queueMicrotask(resizeTextarea);
+ };
+
+ const restoreLastTurnDraft = (draft: RestoredPromptDraft) => {
+ resetPromptHistoryNavigation();
+ setEditingQueuedFollowUp(null);
+ setRestoredPromptDraft(cloneRestoredPromptDraft(draft));
+ setInput(draft.prompt);
+ restoreChatMentions(draft.request?.mentions);
setMentionActive(false);
+ setSlashCommandActive(false);
focusComposer();
queueMicrotask(resizeTextarea);
};
@@ -1319,6 +1417,30 @@ export const AIChat: Component<AIChatProps> = (props) => {
!chat.isLoading() &&
!forkingSession(),
);
+ const hasUndoableUserTurn = createMemo(() =>
+ chat.messages().some(
+ (message) =>
+ message.role === 'user' &&
+ message.delivery !== 'queued' &&
+ Boolean(message.content.trim()),
+ ),
+ );
+ const canUndoLastTurn = createMemo(
+ () =>
+ Boolean(chat.sessionId().trim()) &&
+ !chat.isLoading() &&
+ !undoingLastTurn() &&
+ !redoingLastTurn() &&
+ hasUndoableUserTurn(),
+ );
+ const canRedoLastTurn = createMemo(
+ () =>
+ Boolean(chat.sessionId().trim()) &&
+ !chat.isLoading() &&
+ !undoingLastTurn() &&
+ !redoingLastTurn() &&
+ redoLastTurnAvailable(),
+ );
const buildCurrentTranscript = (generatedAt = new Date()) => {
const sessionId = chat.sessionId().trim();
@@ -2234,6 +2356,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
const clearLocalComposerCommand = () => {
stashedComposerDraft = null;
setEditingQueuedFollowUp(null);
+ setRestoredPromptDraft(null);
setInput('');
setAccumulatedMentions([]);
setMentionActive(false);
@@ -2271,6 +2394,12 @@ export const AIChat: Component<AIChatProps> = (props) => {
case 'fork':
void handleForkSession();
break;
+ case 'undo':
+ void handleUndoLastTurn();
+ break;
+ case 'redo':
+ void handleRedoLastTurn();
+ break;
}
};
@@ -2318,11 +2447,16 @@ export const AIChat: Component<AIChatProps> = (props) => {
// Pass findingId from context on the first message, clear after success
const ctx = aiChatStore.context;
const queuedDraft = editingQueuedFollowUp();
- const findingId = queuedDraft ? queuedDraft.findingId : ctx.findingId;
+ const restoredDraft = restoredPromptDraft();
+ const findingId = queuedDraft
+ ? queuedDraft.findingId
+ : (restoredDraft?.request?.findingId ?? ctx.findingId);
const sendOptions: SendMessageOptions = queuedDraft?.sendOptions
? { ...queuedDraft.sendOptions }
+ : restoredDraft?.request
+ ? sendOptionsFromRestoredRequest(restoredDraft.request)
: {};
- if (!queuedDraft) {
+ if (!queuedDraft && !restoredDraft) {
if (typeof ctx.autonomousMode === 'boolean') {
sendOptions.autonomousMode = ctx.autonomousMode;
}
@@ -2370,10 +2504,12 @@ export const AIChat: Component<AIChatProps> = (props) => {
}
stashedComposerDraft = null;
setEditingQueuedFollowUp(null);
- if (!queuedDraft && findingId) {
+ setRestoredPromptDraft(null);
+ setRedoLastTurnAvailable(false);
+ if (!queuedDraft && !restoredDraft && findingId) {
aiChatStore.clearFindingId?.();
}
- if (!queuedDraft && hasRequestHandoffPayload) {
+ if (!queuedDraft && !restoredDraft && hasRequestHandoffPayload) {
aiChatStore.clearRequestHandoffPayload?.();
}
})
@@ -2534,12 +2670,73 @@ export const AIChat: Component<AIChatProps> = (props) => {
}
};
+ const handleUndoLastTurn = async () => {
+ if (undoingLastTurn() || redoingLastTurn()) return;
+ if (chat.isLoading()) {
+ notificationStore.info(AI_CHAT_UNDO_LAST_TURN_LOADING_MESSAGE, 2000);
+ return;
+ }
+ if (!canUndoLastTurn()) {
+ notificationStore.info(AI_CHAT_UNDO_LAST_TURN_EMPTY_MESSAGE, 2000);
+ return;
+ }
+
+ setUndoingLastTurn(true);
+ try {
+ const draft = await chat.undoLastTurn();
+ if (!draft) return;
+ setRedoLastTurnAvailable(true);
+ restoreLastTurnDraft(draft);
+ notificationStore.success(AI_CHAT_UNDO_LAST_TURN_SUCCESS_MESSAGE, 2000);
+ } catch (error) {
+ logger.error('[AIChat] Failed to undo Assistant turn:', error);
+ notificationStore.error(AI_CHAT_UNDO_LAST_TURN_ERROR_MESSAGE);
+ } finally {
+ setUndoingLastTurn(false);
+ }
+ };
+
+ const handleRedoLastTurn = async () => {
+ if (undoingLastTurn() || redoingLastTurn()) return;
+ if (chat.isLoading()) {
+ notificationStore.info(AI_CHAT_REDO_LAST_TURN_LOADING_MESSAGE, 2000);
+ return;
+ }
+ if (!chat.sessionId().trim() || !redoLastTurnAvailable()) {
+ notificationStore.info(AI_CHAT_REDO_LAST_TURN_EMPTY_MESSAGE, 2000);
+ return;
+ }
+
+ setRedoingLastTurn(true);
+ try {
+ const result = await chat.redoLastTurn();
+ setRedoLastTurnAvailable(result.canRedo);
+ if (!result.success) return;
+ setRestoredPromptDraft(null);
+ setEditingQueuedFollowUp(null);
+ setInput('');
+ setAccumulatedMentions([]);
+ setMentionActive(false);
+ setSlashCommandActive(false);
+ notificationStore.success(AI_CHAT_REDO_LAST_TURN_SUCCESS_MESSAGE, 2000);
+ focusComposer();
+ queueMicrotask(resizeTextarea);
+ } catch (error) {
+ logger.error('[AIChat] Failed to redo Assistant turn:', error);
+ notificationStore.error(AI_CHAT_REDO_LAST_TURN_ERROR_MESSAGE);
+ } finally {
+ setRedoingLastTurn(false);
+ }
+ };
+
// New conversation
const handleNewConversation = async () => {
const started = await chat.newSession();
if (!started) return;
resetPromptHistoryNavigation();
setEditingQueuedFollowUp(null);
+ setRestoredPromptDraft(null);
+ setRedoLastTurnAvailable(false);
aiChatStore.clearContext?.();
setShowSessions(false);
setSessionRefreshLoading(false);
@@ -2576,6 +2773,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
resetPromptHistoryNavigation();
setEditingQueuedFollowUp(null);
+ setRestoredPromptDraft(null);
+ setRedoLastTurnAvailable(false);
const restoredContext = buildSessionHandoffContext(forkedSession);
if (restoredContext) {
aiChatStore.setContext(restoredContext);
@@ -2729,6 +2928,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
if (!loaded) return;
resetPromptHistoryNavigation();
setEditingQueuedFollowUp(null);
+ setRestoredPromptDraft(null);
+ setRedoLastTurnAvailable(Boolean(session?.can_redo));
const restoredContext = buildSessionHandoffContext(session);
if (restoredContext) {
aiChatStore.setContext(restoredContext);
@@ -2755,6 +2956,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
chat.clearMessages();
resetPromptHistoryNavigation();
setEditingQueuedFollowUp(null);
+ setRestoredPromptDraft(null);
+ setRedoLastTurnAvailable(false);
}
} catch (_error) {
notificationStore.error('Failed to delete session');
@@ -2909,6 +3112,44 @@ export const AIChat: Component<AIChatProps> = (props) => {
</Show>
</button>
+ <button
+ type="button"
+ onClick={() => {
+ void handleUndoLastTurn();
+ }}
+ disabled={!canUndoLastTurn()}
+ class="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border bg-surface text-muted transition-colors hover:border-border hover:bg-surface-hover hover:text-base-content disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-surface disabled:hover:text-muted"
+ title={AI_CHAT_UNDO_LAST_TURN_LABEL}
+ aria-label={AI_CHAT_UNDO_LAST_TURN_LABEL}
+ aria-busy={undoingLastTurn()}
+ >
+ <Show
+ when={undoingLastTurn()}
+ fallback={<Undo2Icon class="h-4 w-4" aria-hidden="true" />}
+ >
+ <LoaderCircleIcon class="h-4 w-4 animate-spin" aria-hidden="true" />
+ </Show>
+ </button>
+
+ <button
+ type="button"
+ onClick={() => {
+ void handleRedoLastTurn();
+ }}
+ disabled={!canRedoLastTurn()}
+ class="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border bg-surface text-muted transition-colors hover:border-border hover:bg-surface-hover hover:text-base-content disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-surface disabled:hover:text-muted"
+ title={AI_CHAT_REDO_LAST_TURN_LABEL}
+ aria-label={AI_CHAT_REDO_LAST_TURN_LABEL}
+ aria-busy={redoingLastTurn()}
+ >
+ <Show
+ when={redoingLastTurn()}
+ fallback={<Redo2Icon class="h-4 w-4" aria-hidden="true" />}
+ >
+ <LoaderCircleIcon class="h-4 w-4 animate-spin" aria-hidden="true" />
+ </Show>
+ </button>
+
<button
type="button"
onClick={() => {
diff --git a/frontend-modern/src/components/shared/__tests__/CommandPaletteModal.test.tsx b/frontend-modern/src/components/shared/__tests__/CommandPaletteModal.test.tsx
index ac38ee834a..ab095e549a 100644
--- a/frontend-modern/src/components/shared/__tests__/CommandPaletteModal.test.tsx
+++ b/frontend-modern/src/components/shared/__tests__/CommandPaletteModal.test.tsx
@@ -85,6 +85,8 @@ describe('CommandPaletteModal', () => {
expect(commandPaletteModelSource).toContain("id: 'assistant-open'");
expect(commandPaletteModelSource).toContain("id: 'assistant-switch-session'");
expect(commandPaletteModelSource).toContain("id: 'assistant-switch-model'");
+ expect(commandPaletteModelSource).toContain("id: 'assistant-undo-last-turn'");
+ expect(commandPaletteModelSource).toContain("id: 'assistant-redo-last-turn'");
expect(commandPaletteModelSource).not.toContain("id: 'nav-infrastructure'");
expect(commandPaletteModelSource).not.toContain("id: 'nav-workloads'");
expect(commandPaletteModelSource).not.toContain("id: 'nav-storage'");
@@ -104,6 +106,8 @@ describe('CommandPaletteModal', () => {
expect(screen.getByText('New Assistant session')).toBeInTheDocument();
expect(screen.getByText('Switch Assistant session')).toBeInTheDocument();
expect(screen.getByText('Switch Assistant model')).toBeInTheDocument();
+ expect(screen.getByText('Undo last Assistant turn')).toBeInTheDocument();
+ expect(screen.getByText('Redo last Assistant turn')).toBeInTheDocument();
expect(screen.getByText('Go to Machines')).toBeInTheDocument();
expect(screen.getByText('/standalone/machines')).toBeInTheDocument();
expect(screen.getByText('Go to Proxmox')).toBeInTheDocument();
@@ -146,6 +150,25 @@ describe('CommandPaletteModal', () => {
});
});
+ it('routes Assistant undo workflow commands through the Assistant store', async () => {
+ const onClose = vi.fn();
+ const requestCommand = vi.spyOn(aiChatStore, 'requestCommand').mockImplementation(() => {});
+ render(() => (
+ <CommandPaletteModal
+ isOpen={true}
+ onClose={onClose}
+ platformVisibility={platformVisibility}
+ />
+ ));
+
+ await fireEvent.click(screen.getByText('Undo last Assistant turn'));
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ await waitFor(() => {
+ expect(requestCommand).toHaveBeenCalledWith('undo');
+ });
+ });
+
it('opens Pulse Assistant from the command palette after closing the palette', async () => {
const onClose = vi.fn();
const openAssistant = vi.spyOn(aiChatStore, 'open').mockImplementation(() => {});
diff --git a/frontend-modern/src/components/shared/commandPaletteModel.ts b/frontend-modern/src/components/shared/commandPaletteModel.ts
index abab3f3506..8a834bd377 100644
--- a/frontend-modern/src/components/shared/commandPaletteModel.ts
+++ b/frontend-modern/src/components/shared/commandPaletteModel.ts
@@ -34,6 +34,8 @@ export type CommandPaletteAssistantActions = {
newSession: () => void;
sessions: () => void;
models: () => void;
+ undo: () => void;
+ redo: () => void;
};
export function buildCommandPaletteCommands(options: {
@@ -74,6 +76,20 @@ export function buildCommandPaletteCommands(options: {
keywords: ['assistant', 'models', 'model', 'provider', 'openrouter', 'deepseek'],
action: options.assistantActions.models,
},
+ {
+ id: 'assistant-undo-last-turn',
+ label: 'Undo last Assistant turn',
+ description: '/undo',
+ keywords: ['assistant', 'undo', 'edit', 'prompt', 'last', 'turn'],
+ action: options.assistantActions.undo,
+ },
+ {
+ id: 'assistant-redo-last-turn',
+ label: 'Redo last Assistant turn',
+ description: '/redo',
+ keywords: ['assistant', 'redo', 'restore', 'prompt', 'last', 'turn'],
+ action: options.assistantActions.redo,
+ },
);
}
diff --git a/frontend-modern/src/components/shared/useCommandPaletteState.ts b/frontend-modern/src/components/shared/useCommandPaletteState.ts
index c420bd229b..78eb758fac 100644
--- a/frontend-modern/src/components/shared/useCommandPaletteState.ts
+++ b/frontend-modern/src/components/shared/useCommandPaletteState.ts
@@ -50,6 +50,8 @@ export function useCommandPaletteState(props: CommandPaletteModalProps) {
newSession: () => requestAssistantCommand('new'),
sessions: () => requestAssistantCommand('sessions'),
models: () => requestAssistantCommand('models'),
+ undo: () => requestAssistantCommand('undo'),
+ redo: () => requestAssistantCommand('redo'),
},
}),
);
diff --git a/frontend-modern/src/stores/__tests__/aiChat.test.ts b/frontend-modern/src/stores/__tests__/aiChat.test.ts
index 8061e2e81a..09995fded7 100644
--- a/frontend-modern/src/stores/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/stores/__tests__/aiChat.test.ts
@@ -50,6 +50,9 @@ describe('aiChatStore', () => {
aiChatStore.ackCommandRequest(request!.id);
expect(aiChatStore.commandRequest).toBeNull();
+
+ aiChatStore.requestCommand('undo');
+ expect(aiChatStore.commandRequest).toMatchObject({ action: 'undo' });
});
it('sets legacy context and clears it', () => {
diff --git a/frontend-modern/src/stores/aiChat.ts b/frontend-modern/src/stores/aiChat.ts
index 284a8f2463..5d85d8f3aa 100644
--- a/frontend-modern/src/stores/aiChat.ts
+++ b/frontend-modern/src/stores/aiChat.ts
@@ -78,7 +78,7 @@ export interface AIChatContext {
autonomousMode?: boolean;
}
-export type AIChatCommandRequestAction = 'new' | 'sessions' | 'models';
+export type AIChatCommandRequestAction = 'new' | 'sessions' | 'models' | 'undo' | 'redo';
export interface AIChatCommandRequest {
id: number;
diff --git a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
index 2b46daa699..ec09480526 100644
--- a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
@@ -30,6 +30,11 @@ import {
AI_CHAT_RENAME_SESSION_ERROR_MESSAGE,
AI_CHAT_RENAME_SESSION_LABEL,
AI_CHAT_RENAME_SESSION_SAVE_LABEL,
+ AI_CHAT_REDO_LAST_TURN_EMPTY_MESSAGE,
+ AI_CHAT_REDO_LAST_TURN_ERROR_MESSAGE,
+ AI_CHAT_REDO_LAST_TURN_LABEL,
+ AI_CHAT_REDO_LAST_TURN_LOADING_MESSAGE,
+ AI_CHAT_REDO_LAST_TURN_SUCCESS_MESSAGE,
AI_CHAT_SESSION_EMPTY_STATE,
AI_CHAT_SESSION_LOADING_STATE,
AI_CHAT_SESSION_MENU_TITLE,
@@ -39,6 +44,11 @@ import {
AI_CHAT_SESSION_SEARCH_PLACEHOLDER,
AI_CHAT_SESSION_SEARCH_TITLE,
AI_CHAT_SWITCH_TO_APPROVAL_LABEL,
+ AI_CHAT_UNDO_LAST_TURN_EMPTY_MESSAGE,
+ AI_CHAT_UNDO_LAST_TURN_ERROR_MESSAGE,
+ AI_CHAT_UNDO_LAST_TURN_LABEL,
+ AI_CHAT_UNDO_LAST_TURN_LOADING_MESSAGE,
+ AI_CHAT_UNDO_LAST_TURN_SUCCESS_MESSAGE,
getAIChatProviderReadinessPresentation,
getAIChatLauncherTitle,
} from '@/utils/aiChatPresentation';
@@ -65,6 +75,16 @@ describe('aiChatPresentation', () => {
expect(AI_CHAT_RENAME_SESSION_CANCEL_LABEL).toBe('Cancel Assistant session rename');
expect(AI_CHAT_RENAME_SESSION_EMPTY_MESSAGE).toBe('Session title cannot be empty');
expect(AI_CHAT_RENAME_SESSION_ERROR_MESSAGE).toBe('Failed to rename Assistant session');
+ expect(AI_CHAT_UNDO_LAST_TURN_LABEL).toBe('Undo last Assistant turn');
+ expect(AI_CHAT_UNDO_LAST_TURN_EMPTY_MESSAGE).toBe('No Assistant turn to undo');
+ expect(AI_CHAT_UNDO_LAST_TURN_LOADING_MESSAGE).toBe('Assistant is still working');
+ expect(AI_CHAT_UNDO_LAST_TURN_ERROR_MESSAGE).toBe('Failed to undo Assistant turn');
+ expect(AI_CHAT_UNDO_LAST_TURN_SUCCESS_MESSAGE).toBe('Last prompt restored for editing');
+ expect(AI_CHAT_REDO_LAST_TURN_LABEL).toBe('Redo last Assistant turn');
+ expect(AI_CHAT_REDO_LAST_TURN_EMPTY_MESSAGE).toBe('No undone Assistant turn to redo');
+ expect(AI_CHAT_REDO_LAST_TURN_LOADING_MESSAGE).toBe('Assistant is still working');
+ expect(AI_CHAT_REDO_LAST_TURN_ERROR_MESSAGE).toBe('Failed to redo Assistant turn');
+ expect(AI_CHAT_REDO_LAST_TURN_SUCCESS_MESSAGE).toBe('Assistant turn restored');
expect(AI_CHAT_LAUNCHER_ARIA_LABEL).toBe('Expand Pulse Assistant');
expect(AI_CHAT_CLOSE_LABEL).toBe('Close Pulse Assistant');
expect(AI_CHAT_SESSION_MENU_TITLE).toBe('Pulse Assistant sessions');
diff --git a/frontend-modern/src/utils/aiChatPresentation.ts b/frontend-modern/src/utils/aiChatPresentation.ts
index 0972984988..b4c138bcc5 100644
--- a/frontend-modern/src/utils/aiChatPresentation.ts
+++ b/frontend-modern/src/utils/aiChatPresentation.ts
@@ -16,6 +16,16 @@ export const AI_CHAT_FORK_SESSION_LOAD_ERROR_MESSAGE =
'Forked Assistant session but failed to load it';
export const AI_CHAT_FORK_SESSION_ERROR_MESSAGE = 'Failed to fork Assistant session';
export const AI_CHAT_FORK_SESSION_SUCCESS_MESSAGE = 'Assistant session forked';
+export const AI_CHAT_UNDO_LAST_TURN_LABEL = 'Undo last Assistant turn';
+export const AI_CHAT_UNDO_LAST_TURN_EMPTY_MESSAGE = 'No Assistant turn to undo';
+export const AI_CHAT_UNDO_LAST_TURN_LOADING_MESSAGE = 'Assistant is still working';
+export const AI_CHAT_UNDO_LAST_TURN_ERROR_MESSAGE = 'Failed to undo Assistant turn';
+export const AI_CHAT_UNDO_LAST_TURN_SUCCESS_MESSAGE = 'Last prompt restored for editing';
+export const AI_CHAT_REDO_LAST_TURN_LABEL = 'Redo last Assistant turn';
+export const AI_CHAT_REDO_LAST_TURN_EMPTY_MESSAGE = 'No undone Assistant turn to redo';
+export const AI_CHAT_REDO_LAST_TURN_LOADING_MESSAGE = 'Assistant is still working';
+export const AI_CHAT_REDO_LAST_TURN_ERROR_MESSAGE = 'Failed to redo Assistant turn';
+export const AI_CHAT_REDO_LAST_TURN_SUCCESS_MESSAGE = 'Assistant turn restored';
export const AI_CHAT_RENAME_SESSION_LABEL = 'Rename Assistant session';
export const AI_CHAT_RENAME_SESSION_SAVE_LABEL = 'Save Assistant session title';
export const AI_CHAT_RENAME_SESSION_CANCEL_LABEL = 'Cancel Assistant session rename';
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 5692f3af85..5ac8fecb8b 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -3522,6 +3522,32 @@ func (s *Service) UnrevertSession(ctx context.Context, sessionID string) (map[st
return map[string]interface{}{"status": "not_implemented"}, nil
}
+// UndoLastTurn removes the latest user turn from the durable chat session.
+func (s *Service) UndoLastTurn(ctx context.Context, sessionID string) (*SessionTurnUndoResult, error) {
+ s.mu.RLock()
+ sessions := s.sessions
+ s.mu.RUnlock()
+
+ if sessions == nil {
+ return nil, fmt.Errorf("service not started")
+ }
+
+ return sessions.UndoLastTurn(sessionID)
+}
+
+// RedoLastTurn restores the latest turn removed by UndoLastTurn.
+func (s *Service) RedoLastTurn(ctx context.Context, sessionID string) (*SessionTurnRedoResult, error) {
+ s.mu.RLock()
+ sessions := s.sessions
+ s.mu.RUnlock()
+
+ if sessions == nil {
+ return nil, fmt.Errorf("service not started")
+ }
+
+ return sessions.RedoLastTurn(sessionID)
+}
+
// GetBaseURL returns empty since there's no sidecar
func (s *Service) GetBaseURL() string {
return ""
diff --git a/internal/ai/chat/service_test.go b/internal/ai/chat/service_test.go
index 0478f3d198..34853df2a5 100644
--- a/internal/ai/chat/service_test.go
+++ b/internal/ai/chat/service_test.go
@@ -330,6 +330,36 @@ func TestService_SessionWrappers(t *testing.T) {
assert.Equal(t, "I will inspect the device nodes.", forkedMessages[0].Content)
assert.NotContains(t, forkedMessages[0].Content, "pulse_read")
+ require.NoError(t, service.sessions.AddMessage(forked.ID, Message{
+ Role: "user",
+ Content: "How many device nodes?",
+ }))
+ require.NoError(t, service.sessions.AddMessage(forked.ID, Message{
+ Role: "assistant",
+ Content: "There are 42 device nodes.",
+ }))
+ undo, err := service.UndoLastTurn(ctx, forked.ID)
+ require.NoError(t, err)
+ require.NotNil(t, undo)
+ assert.True(t, undo.Success)
+ assert.Equal(t, "How many device nodes?", undo.RestoredPrompt)
+ assert.True(t, undo.CanRedo)
+
+ forkedMessages, err = service.GetMessages(ctx, forked.ID)
+ require.NoError(t, err)
+ require.Len(t, forkedMessages, 1)
+ assert.Equal(t, "I will inspect the device nodes.", forkedMessages[0].Content)
+
+ redo, err := service.RedoLastTurn(ctx, forked.ID)
+ require.NoError(t, err)
+ require.NotNil(t, redo)
+ assert.True(t, redo.Success)
+ assert.False(t, redo.CanRedo)
+
+ forkedMessages, err = service.GetMessages(ctx, forked.ID)
+ require.NoError(t, err)
+ require.Len(t, forkedMessages, 3)
+
list, err = service.ListSessions(ctx)
require.NoError(t, err)
assert.Len(t, list, 2)
diff --git a/internal/ai/chat/session.go b/internal/ai/chat/session.go
index 8b97e17449..47093d431b 100644
--- a/internal/ai/chat/session.go
+++ b/internal/ai/chat/session.go
@@ -41,14 +41,22 @@ type SessionStore struct {
knowledgeAccumulators map[string]*KnowledgeAccumulator
}
+const maxSessionTurnRedoStack = 10
+
// sessionData is the on-disk format for a session
type sessionData struct {
- ID string `json:"id"`
- Title string `json:"title"`
- Messages []Message `json:"messages"`
- ModelContext *sessionModelContext `json:"model_context,omitempty"`
- CreatedAt time.Time `json:"created_at"`
- UpdatedAt time.Time `json:"updated_at"`
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Messages []Message `json:"messages"`
+ ModelContext *sessionModelContext `json:"model_context,omitempty"`
+ TurnRedoStack []sessionTurnRedoEntry `json:"turn_redo_stack,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+type sessionTurnRedoEntry struct {
+ Messages []Message `json:"messages"`
+ UpdatedAt time.Time `json:"updated_at"`
}
type sessionModelContext struct {
@@ -60,6 +68,17 @@ type sessionModelContext struct {
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
+func cloneSessionMessages(messages []Message) []Message {
+ if len(messages) == 0 {
+ return nil
+ }
+ cloned := make([]Message, len(messages))
+ for i, msg := range messages {
+ cloned[i] = msg.NormalizeCollections()
+ }
+ return cloned
+}
+
func normalizeHandoffResources(resources []HandoffResource) []HandoffResource {
if len(resources) == 0 {
return nil
@@ -360,6 +379,18 @@ func modelContextHandoffSummary(modelContext *sessionModelContext) *SessionHando
return summary
}
+func sessionSummaryFromData(data sessionData) Session {
+ return Session{
+ ID: data.ID,
+ Title: data.Title,
+ CreatedAt: data.CreatedAt,
+ UpdatedAt: data.UpdatedAt,
+ MessageCount: len(data.Messages),
+ CanRedo: len(data.TurnRedoStack) > 0,
+ HandoffSummary: modelContextHandoffSummary(data.ModelContext),
+ }
+}
+
const (
maxSessionIDLength = 128
maxSessionTitleRunes = 120
@@ -487,14 +518,7 @@ func (s *SessionStore) List() ([]Session, error) {
data.Messages[i] = data.Messages[i].NormalizeCollections()
}
- sessions = append(sessions, Session{
- ID: data.ID,
- Title: data.Title,
- CreatedAt: data.CreatedAt,
- UpdatedAt: data.UpdatedAt,
- MessageCount: len(data.Messages),
- HandoffSummary: modelContextHandoffSummary(data.ModelContext),
- })
+ sessions = append(sessions, sessionSummaryFromData(data))
}
// Sort by updated_at descending (newest first)
@@ -523,12 +547,8 @@ func (s *SessionStore) Create() (*Session, error) {
return nil, err
}
- return &Session{
- ID: data.ID,
- Title: data.Title,
- CreatedAt: data.CreatedAt,
- UpdatedAt: data.UpdatedAt,
- }, nil
+ session := sessionSummaryFromData(data)
+ return &session, nil
}
// Get retrieves a session by ID
@@ -541,14 +561,8 @@ func (s *SessionStore) Get(id string) (*Session, error) {
return nil, err
}
- return &Session{
- ID: data.ID,
- Title: data.Title,
- CreatedAt: data.CreatedAt,
- UpdatedAt: data.UpdatedAt,
- MessageCount: len(data.Messages),
- HandoffSummary: modelContextHandoffSummary(data.ModelContext),
- }, nil
+ session := sessionSummaryFromData(*data)
+ return &session, nil
}
// Rename updates a session title without touching messages or handoff context.
@@ -572,14 +586,8 @@ func (s *SessionStore) Rename(id, title string) (*Session, error) {
return nil, err
}
- return &Session{
- ID: data.ID,
- Title: data.Title,
- CreatedAt: data.CreatedAt,
- UpdatedAt: data.UpdatedAt,
- MessageCount: len(data.Messages),
- HandoffSummary: modelContextHandoffSummary(data.ModelContext),
- }, nil
+ session := sessionSummaryFromData(*data)
+ return &session, nil
}
// Fork clones a persisted session into a new durable session. The copied
@@ -599,10 +607,7 @@ func (s *SessionStore) Fork(id string) (*Session, error) {
}
now := time.Now()
- messages := make([]Message, len(source.Messages))
- for i, msg := range source.Messages {
- messages[i] = msg.NormalizeCollections()
- }
+ messages := cloneSessionMessages(source.Messages)
title := strings.TrimSpace(source.Title)
if title == "" {
@@ -631,13 +636,114 @@ func (s *SessionStore) Fork(id string) (*Session, error) {
return nil, err
}
- return &Session{
- ID: fork.ID,
- Title: fork.Title,
- CreatedAt: fork.CreatedAt,
- UpdatedAt: fork.UpdatedAt,
- MessageCount: len(fork.Messages),
- HandoffSummary: modelContextHandoffSummary(fork.ModelContext),
+ session := sessionSummaryFromData(fork)
+ return &session, nil
+}
+
+// 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) {
+ if err := validateSessionID(id); err != nil {
+ return nil, err
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ data, err := s.readSession(id)
+ if err != nil {
+ return nil, err
+ }
+
+ lastUserIndex := -1
+ for i := len(data.Messages) - 1; i >= 0; i-- {
+ if strings.EqualFold(data.Messages[i].Role, "user") {
+ lastUserIndex = i
+ break
+ }
+ }
+ if lastUserIndex < 0 {
+ return &SessionTurnUndoResult{
+ Success: false,
+ SessionID: data.ID,
+ CanRedo: len(data.TurnRedoStack) > 0,
+ Message: "No user turn to undo.",
+ }, nil
+ }
+
+ removed := cloneSessionMessages(data.Messages[lastUserIndex:])
+ prompt := ""
+ for _, msg := range removed {
+ if strings.EqualFold(msg.Role, "user") {
+ prompt = msg.Content
+ break
+ }
+ }
+
+ now := time.Now()
+ data.Messages = cloneSessionMessages(data.Messages[:lastUserIndex])
+ data.TurnRedoStack = append(data.TurnRedoStack, sessionTurnRedoEntry{
+ Messages: removed,
+ UpdatedAt: now,
+ })
+ if len(data.TurnRedoStack) > maxSessionTurnRedoStack {
+ data.TurnRedoStack = data.TurnRedoStack[len(data.TurnRedoStack)-maxSessionTurnRedoStack:]
+ }
+ data.UpdatedAt = now
+
+ if err := s.writeSession(*data); err != nil {
+ return nil, err
+ }
+
+ return &SessionTurnUndoResult{
+ Success: true,
+ SessionID: data.ID,
+ RestoredPrompt: prompt,
+ RemovedMessages: len(removed),
+ CanRedo: len(data.TurnRedoStack) > 0,
+ }, nil
+}
+
+// RedoLastTurn restores the most recently undone turn, if one is available.
+func (s *SessionStore) RedoLastTurn(id string) (*SessionTurnRedoResult, error) {
+ if err := validateSessionID(id); err != nil {
+ return nil, err
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ data, err := s.readSession(id)
+ if err != nil {
+ return nil, err
+ }
+ if len(data.TurnRedoStack) == 0 {
+ return &SessionTurnRedoResult{
+ Success: false,
+ SessionID: data.ID,
+ CanRedo: false,
+ Message: "No undone turn to redo.",
+ }, nil
+ }
+
+ entryIndex := len(data.TurnRedoStack) - 1
+ entry := data.TurnRedoStack[entryIndex]
+ data.TurnRedoStack = data.TurnRedoStack[:entryIndex]
+ data.Messages = append(data.Messages, cloneSessionMessages(entry.Messages)...)
+ if len(data.TurnRedoStack) == 0 {
+ data.TurnRedoStack = nil
+ }
+ data.UpdatedAt = time.Now()
+
+ if err := s.writeSession(*data); err != nil {
+ return nil, err
+ }
+
+ return &SessionTurnRedoResult{
+ Success: true,
+ SessionID: data.ID,
+ RestoredMessages: len(entry.Messages),
+ CanRedo: len(data.TurnRedoStack) > 0,
}, nil
}
@@ -723,6 +829,7 @@ func (s *SessionStore) TrimMessages(id string, keepMostRecent int) error {
trimmed := make([]Message, keepMostRecent)
copy(trimmed, data.Messages[start:])
data.Messages = trimmed
+ data.TurnRedoStack = nil
data.UpdatedAt = time.Now()
return s.writeSession(*data)
}
@@ -747,6 +854,7 @@ func (s *SessionStore) AddMessage(id string, msg Message) error {
msg = msg.NormalizeCollections()
data.Messages = append(data.Messages, msg)
+ data.TurnRedoStack = nil
data.UpdatedAt = time.Now()
// Auto-generate title from first user message if not set
@@ -1126,6 +1234,9 @@ func (s *SessionStore) readSessionWithLegacyScan(id string, allowLegacyScan bool
for i := range data.Messages {
data.Messages[i] = data.Messages[i].NormalizeCollections()
}
+ for i := range data.TurnRedoStack {
+ data.TurnRedoStack[i].Messages = cloneSessionMessages(data.TurnRedoStack[i].Messages)
+ }
return &data, nil
}
@@ -1138,6 +1249,12 @@ func (s *SessionStore) writeSession(data sessionData) error {
for i := range data.Messages {
data.Messages[i] = data.Messages[i].NormalizeCollections()
}
+ for i := range data.TurnRedoStack {
+ data.TurnRedoStack[i].Messages = cloneSessionMessages(data.TurnRedoStack[i].Messages)
+ }
+ if len(data.TurnRedoStack) == 0 {
+ data.TurnRedoStack = nil
+ }
file, err := json.MarshalIndent(data, "", " ")
if err != nil {
@@ -1235,12 +1352,8 @@ func (s *SessionStore) EnsureSession(id string) (*Session, error) {
data, err := s.readSessionFast(id)
s.mu.RUnlock()
if err == nil {
- return &Session{
- ID: data.ID,
- Title: data.Title,
- CreatedAt: data.CreatedAt,
- UpdatedAt: data.UpdatedAt,
- }, nil
+ session := sessionSummaryFromData(*data)
+ return &session, nil
}
if !errors.Is(err, errSessionNotFound) {
return nil, err
@@ -1253,12 +1366,8 @@ func (s *SessionStore) EnsureSession(id string) (*Session, error) {
data, err = s.readSessionFast(id)
if err == nil {
- return &Session{
- ID: data.ID,
- Title: data.Title,
- CreatedAt: data.CreatedAt,
- UpdatedAt: data.UpdatedAt,
- }, nil
+ session := sessionSummaryFromData(*data)
+ return &session, nil
}
if !errors.Is(err, errSessionNotFound) {
return nil, err
@@ -1277,11 +1386,8 @@ func (s *SessionStore) EnsureSession(id string) (*Session, error) {
return nil, err
}
- return &Session{
- ID: data.ID,
- CreatedAt: data.CreatedAt,
- UpdatedAt: data.UpdatedAt,
- }, nil
+ session := sessionSummaryFromData(*data)
+ return &session, nil
}
func validateSessionID(id string) error {
diff --git a/internal/ai/chat/session_test.go b/internal/ai/chat/session_test.go
index f49210a12e..386cec427e 100644
--- a/internal/ai/chat/session_test.go
+++ b/internal/ai/chat/session_test.go
@@ -253,6 +253,89 @@ func TestSessionStoreForkClonesTranscriptAndHandoffSummary(t *testing.T) {
require.Len(t, sourceMessages, 2)
}
+func TestSessionStoreUndoRedoLastTurn(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"}))
+ require.NoError(t, store.AddMessage(session.ID, Message{ID: "u2", Role: "user", Content: "Second prompt"}))
+ require.NoError(t, store.AddMessage(session.ID, Message{ID: "a2", Role: "assistant", Content: "Second answer"}))
+
+ undo, err := store.UndoLastTurn(session.ID)
+ require.NoError(t, err)
+ require.NotNil(t, undo)
+ assert.True(t, undo.Success)
+ assert.Equal(t, "Second prompt", undo.RestoredPrompt)
+ assert.Equal(t, 2, undo.RemovedMessages)
+ assert.True(t, undo.CanRedo)
+
+ summary, err := store.Get(session.ID)
+ require.NoError(t, err)
+ assert.True(t, summary.CanRedo)
+
+ messages, err := store.GetMessages(session.ID)
+ require.NoError(t, err)
+ require.Len(t, messages, 2)
+ assert.Equal(t, "u1", messages[0].ID)
+ assert.Equal(t, "a1", messages[1].ID)
+
+ undo, err = store.UndoLastTurn(session.ID)
+ 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)
+
+ redo, err := store.RedoLastTurn(session.ID)
+ require.NoError(t, err)
+ require.NotNil(t, redo)
+ assert.True(t, redo.Success)
+ assert.Equal(t, 2, redo.RestoredMessages)
+ assert.True(t, redo.CanRedo)
+
+ messages, err = store.GetMessages(session.ID)
+ require.NoError(t, err)
+ require.Len(t, messages, 2)
+ assert.Equal(t, "First prompt", messages[0].Content)
+
+ redo, err = store.RedoLastTurn(session.ID)
+ require.NoError(t, err)
+ assert.True(t, redo.Success)
+ assert.False(t, redo.CanRedo)
+
+ summary, err = store.Get(session.ID)
+ require.NoError(t, err)
+ assert.False(t, summary.CanRedo)
+
+ messages, err = store.GetMessages(session.ID)
+ require.NoError(t, err)
+ require.Len(t, messages, 4)
+ assert.Equal(t, "Second prompt", messages[2].Content)
+
+ undo, err = store.UndoLastTurn(session.ID)
+ require.NoError(t, err)
+ assert.True(t, undo.CanRedo)
+ summary, err = store.Get(session.ID)
+ require.NoError(t, err)
+ assert.True(t, summary.CanRedo)
+ require.NoError(t, store.AddMessage(session.ID, Message{ID: "u3", Role: "user", Content: "Replacement"}))
+ summary, err = store.Get(session.ID)
+ require.NoError(t, err)
+ assert.False(t, summary.CanRedo)
+
+ redo, err = store.RedoLastTurn(session.ID)
+ require.NoError(t, err)
+ assert.False(t, redo.Success)
+ assert.False(t, redo.CanRedo)
+ assert.Equal(t, "No undone turn to redo.", redo.Message)
+}
+
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.go
index 11386a34fe..56aadaae5d 100644
--- a/internal/ai/chat/types.go
+++ b/internal/ai/chat/types.go
@@ -18,9 +18,30 @@ type Session struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
MessageCount int `json:"message_count,omitempty"`
+ CanRedo bool `json:"can_redo,omitempty"`
HandoffSummary *SessionHandoffSummary `json:"handoff_summary,omitempty"`
}
+// SessionTurnUndoResult is returned when the chat runtime removes the latest
+// user turn and makes that prompt available for editing.
+type SessionTurnUndoResult struct {
+ Success bool `json:"success"`
+ SessionID string `json:"session_id"`
+ RestoredPrompt string `json:"restored_prompt,omitempty"`
+ RemovedMessages int `json:"removed_messages,omitempty"`
+ CanRedo bool `json:"can_redo"`
+ Message string `json:"message,omitempty"`
+}
+
+// SessionTurnRedoResult is returned when a previously undone turn is restored.
+type SessionTurnRedoResult struct {
+ Success bool `json:"success"`
+ SessionID string `json:"session_id"`
+ RestoredMessages int `json:"restored_messages,omitempty"`
+ CanRedo bool `json:"can_redo"`
+ Message string `json:"message,omitempty"`
+}
+
// SessionHandoffSummary is the browser-safe public summary of private
// session-scoped model handoff metadata. It intentionally omits model-only
// context text and raw remediation details.
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index 400efe25a5..7050e887ba 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -58,6 +58,8 @@ type AIService interface {
ForkSession(ctx context.Context, sessionID string) (*chat.Session, error)
RevertSession(ctx context.Context, sessionID string) (map[string]interface{}, error)
UnrevertSession(ctx context.Context, sessionID string) (map[string]interface{}, error)
+ UndoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnUndoResult, error)
+ RedoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnRedoResult, error)
AnswerQuestion(ctx context.Context, questionID string, answers []chat.QuestionAnswer) error
SetAlertProvider(provider chat.MCPAlertProvider)
SetFindingsProvider(provider chat.MCPFindingsProvider)
@@ -2936,6 +2938,54 @@ func (h *AIHandler) HandleFork(w http.ResponseWriter, r *http.Request, sessionID
json.NewEncoder(w).Encode(session)
}
+// HandleUndoLastTurn handles POST /api/ai/sessions/{id}/undo.
+func (h *AIHandler) HandleUndoLastTurn(w http.ResponseWriter, r *http.Request, sessionID string) {
+ ctx := r.Context()
+ if !h.IsRunning(ctx) {
+ http.Error(w, "Pulse Assistant is not running", http.StatusServiceUnavailable)
+ return
+ }
+
+ svc := h.GetService(ctx)
+ if svc == nil {
+ http.Error(w, "Pulse Assistant service not available", http.StatusServiceUnavailable)
+ return
+ }
+
+ result, err := svc.UndoLastTurn(ctx, sessionID)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(result)
+}
+
+// HandleRedoLastTurn handles POST /api/ai/sessions/{id}/redo.
+func (h *AIHandler) HandleRedoLastTurn(w http.ResponseWriter, r *http.Request, sessionID string) {
+ ctx := r.Context()
+ if !h.IsRunning(ctx) {
+ http.Error(w, "Pulse Assistant is not running", http.StatusServiceUnavailable)
+ return
+ }
+
+ svc := h.GetService(ctx)
+ if svc == nil {
+ http.Error(w, "Pulse Assistant service not available", http.StatusServiceUnavailable)
+ return
+ }
+
+ result, err := svc.RedoLastTurn(ctx, sessionID)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(result)
+}
+
// HandleRevert handles POST /api/ai/sessions/{id}/revert
// Reverts file changes from the session
func (h *AIHandler) HandleRevert(w http.ResponseWriter, r *http.Request, sessionID string) {
diff --git a/internal/api/ai_handler_recovery_wiring_test.go b/internal/api/ai_handler_recovery_wiring_test.go
index 3ab713f5ca..c444540f49 100644
--- a/internal/api/ai_handler_recovery_wiring_test.go
+++ b/internal/api/ai_handler_recovery_wiring_test.go
@@ -71,6 +71,12 @@ func (s *capturingAIService) RevertSession(ctx context.Context, sessionID string
func (s *capturingAIService) UnrevertSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
return nil, nil
}
+func (s *capturingAIService) UndoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnUndoResult, error) {
+ return &chat.SessionTurnUndoResult{Success: true, SessionID: sessionID}, nil
+}
+func (s *capturingAIService) RedoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnRedoResult, error) {
+ return &chat.SessionTurnRedoResult{Success: true, SessionID: sessionID}, nil
+}
func (s *capturingAIService) AnswerQuestion(ctx context.Context, questionID string, answers []chat.QuestionAnswer) error {
return nil
}
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index 49e0de6d6e..8ec196180d 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -176,6 +176,22 @@ func (m *MockAIService) UnrevertSession(ctx context.Context, sessionID string) (
return args.Get(0).(map[string]interface{}), args.Error(1)
}
+func (m *MockAIService) UndoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnUndoResult, error) {
+ args := m.Called(ctx, sessionID)
+ if args.Get(0) == nil {
+ return nil, args.Error(1)
+ }
+ return args.Get(0).(*chat.SessionTurnUndoResult), args.Error(1)
+}
+
+func (m *MockAIService) RedoLastTurn(ctx context.Context, sessionID string) (*chat.SessionTurnRedoResult, error) {
+ args := m.Called(ctx, sessionID)
+ if args.Get(0) == nil {
+ return nil, args.Error(1)
+ }
+ return args.Get(0).(*chat.SessionTurnRedoResult), args.Error(1)
+}
+
func (m *MockAIService) AnswerQuestion(ctx context.Context, questionID string, answers []chat.QuestionAnswer) error {
args := m.Called(ctx, questionID, answers)
return args.Error(0)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index f27c79e444..1451658865 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -524,8 +524,10 @@ func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
}
chatSessionText := string(chatSessionSource)
+ if !regexp.MustCompile(`ModelContext\s+\*sessionModelContext`).MatchString(chatSessionText) {
+ t.Fatalf("chat session store must persist model-only handoff metadata outside messages: missing %q", "ModelContext *sessionModelContext")
+ }
for _, required := range []string{
- "ModelContext *sessionModelContext",
"SetModelHandoffFindingID",
"SetModelHandoffEnvelope",
"GetModelHandoffFindingID",
diff --git a/internal/api/router.go b/internal/api/router.go
index 88f2d5db85..a2efe9c533 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -833,7 +833,7 @@ func (h *LicenseHandlers) RemoveTenantService(orgID string) {
// routeAISessions routes session-specific AI chat requests
func (r *Router) routeAISessions(w http.ResponseWriter, req *http.Request) {
- // Extract session ID from path: /api/ai/sessions/{id}[/messages|/abort|/summarize|/diff|/fork|/revert|/unrevert]
+ // Extract session ID from path: /api/ai/sessions/{id}[/messages|/abort|/summarize|/diff|/fork|/undo|/redo|/revert|/unrevert]
path := strings.TrimPrefix(req.URL.Path, "/api/ai/sessions/")
parts := strings.SplitN(path, "/", 2)
sessionID := parts[0]
@@ -871,6 +871,16 @@ func (r *Router) routeAISessions(w http.ResponseWriter, req *http.Request) {
return
}
r.aiHandler.HandleFork(w, req, sessionID)
+ case "undo":
+ if !ensureScope(w, req, config.ScopeAIChat) {
+ return
+ }
+ r.aiHandler.HandleUndoLastTurn(w, req, sessionID)
+ case "redo":
+ if !ensureScope(w, req, config.ScopeAIChat) {
+ return
+ }
+ r.aiHandler.HandleRedoLastTurn(w, req, sessionID)
case "revert":
if !ensureScope(w, req, config.ScopeAIChat) {
return
diff --git a/internal/api/router_routes_additional_test.go b/internal/api/router_routes_additional_test.go
index 65986f504c..5ba0e88eee 100644
--- a/internal/api/router_routes_additional_test.go
+++ b/internal/api/router_routes_additional_test.go
@@ -203,6 +203,56 @@ func TestRouteAISessions_Fork(t *testing.T) {
mockSvc.AssertExpectations(t)
}
+func TestRouteAISessions_UndoLastTurn(t *testing.T) {
+ mockSvc := &MockAIService{}
+ mockSvc.On("IsRunning").Return(true)
+ mockSvc.On("UndoLastTurn", mock.Anything, "session-1").Return(&chat.SessionTurnUndoResult{
+ Success: true,
+ SessionID: "session-1",
+ RestoredPrompt: "Inspect storage warnings",
+ CanRedo: true,
+ }, nil)
+
+ handler := &AIHandler{}
+ setUnexportedField(t, handler, "defaultService", mockSvc)
+
+ router := &Router{aiHandler: handler}
+ req := httptest.NewRequest(http.MethodPost, "/api/ai/sessions/session-1/undo", nil)
+ 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)
+ mockSvc.On("RedoLastTurn", mock.Anything, "session-1").Return(&chat.SessionTurnRedoResult{
+ Success: true,
+ SessionID: "session-1",
+ RestoredMessages: 2,
+ CanRedo: false,
+ }, nil)
+
+ handler := &AIHandler{}
+ setUnexportedField(t, handler, "defaultService", mockSvc)
+
+ router := &Router{aiHandler: handler}
+ req := httptest.NewRequest(http.MethodPost, "/api/ai/sessions/session-1/redo", nil)
+ 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_Revert(t *testing.T) {
mockSvc := &MockAIService{}
mockSvc.On("IsRunning").Return(true)