diff --git a/packages/app/e2e/browser/agent-message-rewind.spec.ts b/packages/app/e2e/browser/agent-message-rewind.spec.ts index 8d4e773259..d570ad526e 100644 --- a/packages/app/e2e/browser/agent-message-rewind.spec.ts +++ b/packages/app/e2e/browser/agent-message-rewind.spec.ts @@ -2,9 +2,11 @@ import type { Locator } from "@playwright/test"; import { expect, test, type Page } from "../support/fixtures"; import { expectAgentIdle, expectAgentReadyToInterrupt } from "../support/helpers/agent-stream"; import { + blurComposerInput, cancelAgent, fillComposerDraft, expectComposerDraft, + expectComposerNotFocused, expectComposerVisible, submitMessage, } from "../support/helpers/composer"; @@ -71,6 +73,7 @@ test.describe("Agent message rewind", () => { minDistanceFromBottom: 300, }); await fillComposerDraft(page, preservedDraft); + await blurComposerInput(page); rewindCompletion.clearTimelineStreamCount(); const rewind = rewindConversation(page, userMessage, rewoundPrompt); @@ -84,6 +87,7 @@ test.describe("Agent message rewind", () => { 0, ); await expectComposerDraft(page, preservedDraft); + await expectComposerNotFocused(page); await expectNearBottom(page); } finally { await agent.cleanup(); diff --git a/packages/app/e2e/browser/rewind-menu.ui-contract.spec.ts b/packages/app/e2e/browser/rewind-menu.ui-contract.spec.ts index e2c04aa315..6200afd5c7 100644 --- a/packages/app/e2e/browser/rewind-menu.ui-contract.spec.ts +++ b/packages/app/e2e/browser/rewind-menu.ui-contract.spec.ts @@ -1,16 +1,29 @@ import type { Locator } from "@playwright/test"; import { expect, test, type Page } from "../support/fixtures"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; -import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate"; -import { scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor"; import { + closeCommandCenter, + openCommandCenter, + selectCommandCenterTab, +} from "../support/helpers/command-center"; +import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate"; +import { + attachComposerTestImage, composerLocator, expectComposerDraft, + expectComposerFocused, + expectComposerNotFocused, expectComposerVisible, fillComposerDraft, submitMessage, + submitMessageWithButton, } from "../support/helpers/composer"; import { readReplicaCache, writeReplicaCache } from "../support/helpers/replica-cache-storage"; +import { + disconnectViewedTimeline, + releaseHeldCatchUp, + restoreViewedTimelineHoldingCatchUp, +} from "../support/helpers/timeline-resume"; // UI plumbing contract against the dev mock provider. Real-provider behavior is tested in `daemon-e2e/*-rewind.real.e2e.test.ts`. @@ -33,6 +46,17 @@ async function selectRewindOption(page: Page, name: string): Promise { await option.click(); } +async function searchRewindActions(page: Page): Promise { + const palette = await openCommandCenter(page); + await selectCommandCenterTab(palette, "Actions"); + await palette.getByRole("textbox").fill("rewind last turn"); + return palette; +} + +function rewindAction(palette: Locator, name: string): Locator { + return palette.getByRole("button", { name: `${name} This action cannot be undone`, exact: true }); +} + async function rewriteCachedMessageAsLegacyRow( page: Page, input: { prompt: string; agentId: string; workspaceId: string }, @@ -199,10 +223,6 @@ test.describe("Rewind sheet", () => { await expectUserMessageCount(page, 2); await session.client.waitForFinish(session.agentId); - await scrollChatAwayFromBottom(page, { - deltaY: -900, - minDistanceFromBottom: 300, - }); await userMessage(page, firstPrompt).hover(); await page.getByTestId("rewind-menu-trigger").first().click(); const rewindSheet = page.getByTestId("rewind-menu-content"); @@ -217,6 +237,7 @@ test.describe("Rewind sheet", () => { await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0); await expectUserMessageCount(page, 1); await expectComposerDraft(page, firstPrompt); + await expectComposerFocused(page); await submitMessage(page, replacementPrompt); await expectUserMessageVisible(page, replacementPrompt); @@ -232,17 +253,7 @@ test.describe("Rewind sheet", () => { await selectRewindOption(page, "Rewind files"); await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0); await expectComposerDraft(page, ""); - await expectUserMessageCount(page, 2); - - const preservedDraft = "Keep this human draft after rewind."; - await fillComposerDraft(page, preservedDraft); - await composerLocator(page).evaluate((element) => element.blur()); - await userMessage(page, replacementPrompt).hover(); - await page.getByTestId("rewind-menu-trigger").last().click(); - await expect(page.getByTestId("rewind-menu-content")).toBeVisible(); - await selectRewindOption(page, "Rewind files"); - await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0); - await expectComposerDraft(page, preservedDraft); + await expectComposerNotFocused(page); await expectUserMessageCount(page, 2); await fillComposerDraft(page, ""); @@ -253,12 +264,109 @@ test.describe("Rewind sheet", () => { await selectRewindOption(page, "Rewind conversation and files"); await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0); await expectComposerDraft(page, replacementPrompt); + await expectComposerFocused(page); await expectUserMessageCount(page, 1); } finally { await session.cleanup(); } }); + test("rewinds the latest turn from the Command Center", async ({ page }) => { + const firstPrompt = "Keep this earlier turn."; + const latestPrompt = "Edit this latest turn."; + const session = await seedMockAgentWorkspace({ + repoPrefix: "rewind-command-center-e2e-", + title: "Command Center rewind", + initialPrompt: firstPrompt, + }); + + try { + await openAgentRoute(page, session); + await expectComposerVisible(page); + await submitMessage(page, latestPrompt); + await expectUserMessageVisible(page, latestPrompt); + await session.client.waitForFinish(session.agentId); + + const palette = await searchRewindActions(page); + await expect(rewindAction(palette, "Rewind files")).toBeVisible(); + await expect(rewindAction(palette, "Rewind conversation and files")).toBeVisible(); + await rewindAction(palette, "Rewind conversation").click(); + + await expectUserMessageVisible(page, firstPrompt); + await expect(userMessage(page, latestPrompt)).toHaveCount(0); + await expectComposerDraft(page, latestPrompt); + await expectComposerFocused(page); + } finally { + await session.cleanup(); + } + }); + + test("waits for the latest prompt before offering Command Center rewind after reconnect", async ({ + page, + }) => { + const cachedPrompt = "Keep the prompt that was visible before reconnect."; + const latestPrompt = "Rewind the prompt sent while the app was disconnected."; + const gate = await installDaemonWebSocketGate(page); + const session = await seedMockAgentWorkspace({ + repoPrefix: "rewind-reconnect-e2e-", + title: "Rewind after reconnect", + initialPrompt: cachedPrompt, + }); + + try { + await openAgentRoute(page, session); + await expectUserMessageVisible(page, cachedPrompt); + const initialPalette = await searchRewindActions(page); + await expect(rewindAction(initialPalette, "Rewind conversation")).toBeVisible(); + await closeCommandCenter(page); + + await disconnectViewedTimeline(page, gate); + await session.client.sendAgentMessage(session.agentId, latestPrompt); + await session.client.waitForFinish(session.agentId); + await restoreViewedTimelineHoldingCatchUp(page, gate); + + const palette = await searchRewindActions(page); + await expect(palette.getByText("No matches", { exact: true })).toBeVisible(); + await releaseHeldCatchUp(page, gate); + await rewindAction(palette, "Rewind conversation").click(); + + await expectUserMessageVisible(page, cachedPrompt); + await expectComposerDraft(page, latestPrompt); + } finally { + gate.restore(); + await session.cleanup(); + } + }); + + test("hides rewind when the latest prompt only contains an attachment", async ({ page }) => { + const session = await seedMockAgentWorkspace({ + repoPrefix: "rewind-image-only-e2e-", + title: "Rewind image-only prompt", + initialPrompt: "Earlier text prompt.", + }); + + try { + await openAgentRoute(page, session); + await expectComposerVisible(page); + const palette = await searchRewindActions(page); + await expect(rewindAction(palette, "Rewind conversation")).toBeVisible(); + await closeCommandCenter(page); + + await attachComposerTestImage(page); + await submitMessageWithButton(page, ""); + const imagePrompt = page.getByTestId("user-message").filter({ + has: page.getByRole("button", { name: "Open image attachment" }), + }); + await expect(imagePrompt).toHaveAttribute("aria-busy", "false"); + await session.client.waitForFinish(session.agentId); + + const reopened = await searchRewindActions(page); + await expect(reopened.getByText("No matches", { exact: true })).toBeVisible(); + } finally { + await session.cleanup(); + } + }); + test("surfaces rewind failures without crashing the page", async ({ page }) => { const firstPrompt = "emit 1 coalesced agent stream updates for failed rewind turn."; const rewindError = "No file checkpoint found for message rewind-failure-e2e."; @@ -277,6 +385,10 @@ test.describe("Rewind sheet", () => { await expectUserMessageVisible(page, firstPrompt); + const palette = await searchRewindActions(page); + await rewindAction(palette, "Rewind conversation").click(); + await expect(page.getByTestId("app-toast-message")).toHaveText(rewindError); + await userMessage(page, firstPrompt).hover(); await page.getByTestId("rewind-menu-trigger").first().click(); const rewindSheet = page.getByTestId("rewind-menu-content"); diff --git a/packages/app/src/components/message.tsx b/packages/app/src/components/message.tsx index f119e55e97..3e8b3aa1c3 100644 --- a/packages/app/src/components/message.tsx +++ b/packages/app/src/components/message.tsx @@ -11,8 +11,12 @@ import { } from "@/components/attachment-pill"; import { MarkdownRenderer } from "@/components/markdown/renderer"; import { useRetainedPanelActive } from "@/components/retained-panel"; -import { RewindMenu, type RewindMode } from "@/components/rewind/rewind-menu"; -import { useRewindAgentMutation } from "@/components/rewind/use-rewind-agent-mutation"; +import { + isRewindableMessage, + RewindMenu, + useRewindAgentMutation, + type RewindMode, +} from "@/components/rewind"; import { TaskListRow } from "@/components/task-list-row"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { useIsCompactFormFactor } from "@/constants/layout"; @@ -530,7 +534,7 @@ export const UserMessage = memo(function UserMessage({ {formattedTimestamp} - {capabilities && messageId ? ( + {capabilities && isRewindableMessage(messageId, message) ? ( state.sessions[serverId]?.client); + const message = useSessionStore((state) => { + const session = state.sessions[serverId]; + if ( + !canSelectLatestMessage || + !session || + hasActiveMessageSubmission(session.messageSubmissions.get(agentId)) + ) { + return undefined; + } + const timeline = selectAgentTimelineState(session, agentId); + if (timeline.status !== "synced" || timeline.newer === "available") { + return undefined; + } + return ( + session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ?? + timeline.items.findLast((item) => item.kind === "user_message") + ); + }); + const { rewindAgent, isPending } = useRewindAgentMutation({ + serverId, + agentId, + client, + messageId: message?.messageId, + }); + const items = useRewindMenuItems(capabilities); + const actions = useMemo(() => { + if (!message || !isRewindableMessage(message.messageId, message.text)) return []; + return items.map((item, rank) => ({ + id: `rewind:${item.mode}`, + group: "rewind", + groupRank: 1.5, + rank, + visibility: "query", + keywords: ["rewind last turn", ...(item.mode === "files" ? [] : ["rewind chat"])], + presentation: { + kind: "action", + title: item.label, + subtitle: t("rewind.warning"), + icon: getCommandCenterIcon(Undo2), + }, + run: async () => { + const dismiss = toast.show(`${item.label}…`, { durationMs: null }); + try { + await rewindAgent({ mode: item.mode, rewoundText: message.text }); + } catch { + // The mutation reports the failure through the app toast. + } finally { + dismiss(); + } + }, + })); + }, [items, message, rewindAgent, t, toast]); + + useCommandCenterActions({ + sourceId: `rewind:${serverId}:${agentId}`, + enabled: canSelectLatestMessage && Boolean(client) && !isPending, + actions, + }); + return null; +} diff --git a/packages/app/src/components/rewind/composer-restore.tsx b/packages/app/src/components/rewind/composer-restore.tsx index 07e645d225..cdded3c4c8 100644 --- a/packages/app/src/components/rewind/composer-restore.tsx +++ b/packages/app/src/components/rewind/composer-restore.tsx @@ -8,7 +8,7 @@ interface RewindComposerRestoreContextValue { interface RewindComposerRestoreProviderProps { textSource: ComposerTextSource; setText: (text: string) => void; - onRewindComplete: () => void; + onRewindComplete: (restoredComposerText: boolean) => void; children: ReactNode; } @@ -37,10 +37,11 @@ export function RewindComposerRestoreProvider({ currentText: currentText, rewoundText, }); - if (nextText !== currentText) { + const restoredComposerText = nextText !== currentText; + if (restoredComposerText) { setText(nextText); } - onRewindComplete(); + onRewindComplete(restoredComposerText); }, [onRewindComplete, setText, textSource], ); diff --git a/packages/app/src/components/rewind/index.ts b/packages/app/src/components/rewind/index.ts new file mode 100644 index 0000000000..0cf69aa966 --- /dev/null +++ b/packages/app/src/components/rewind/index.ts @@ -0,0 +1,5 @@ +export { RewindCommandCenterRegistration } from "./command-center-registration"; +export { RewindComposerRestoreProvider } from "./composer-restore"; +export { RewindMenu } from "./rewind-menu"; +export { useRewindAgentMutation } from "./use-rewind-agent-mutation"; +export { isRewindableMessage, type RewindMode } from "./use-rewind-capabilities"; diff --git a/packages/app/src/components/rewind/rewind-menu.tsx b/packages/app/src/components/rewind/rewind-menu.tsx index ca13d0ad2d..7d500123c5 100644 --- a/packages/app/src/components/rewind/rewind-menu.tsx +++ b/packages/app/src/components/rewind/rewind-menu.tsx @@ -11,11 +11,9 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; -import { type RewindMode, useRewindCapabilities } from "./use-rewind-capabilities"; +import { type RewindMode, useRewindMenuItems } from "./use-rewind-capabilities"; import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types"; -export type { RewindMode }; - interface RewindMenuProps { capabilities: AgentCapabilityFlags; rewoundText: string; @@ -44,15 +42,7 @@ export const RewindMenu = memo(function RewindMenu({ }: RewindMenuProps) { const { theme } = useUnistyles(); const { t } = useTranslation(); - const rewindLabels = useMemo( - () => ({ - conversation: t("rewind.actions.conversation"), - files: t("rewind.actions.files"), - both: t("rewind.actions.both"), - }), - [t], - ); - const items = useRewindCapabilities(capabilities, rewindLabels); + const items = useRewindMenuItems(capabilities); const [isOpen, setIsOpen] = useState(false); const [pendingMode, setPendingMode] = useState(null); const isLocked = isPendingProp || pendingMode !== null; diff --git a/packages/app/src/components/rewind/use-rewind-agent-mutation.ts b/packages/app/src/components/rewind/use-rewind-agent-mutation.ts index f6d3d0325c..7d2df49c4d 100644 --- a/packages/app/src/components/rewind/use-rewind-agent-mutation.ts +++ b/packages/app/src/components/rewind/use-rewind-agent-mutation.ts @@ -1,7 +1,7 @@ import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan"; -import { useCallback } from "react"; +import { useCallback, useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { useMutation } from "@tanstack/react-query"; +import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query"; import { useToast } from "@/contexts/toast-context"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import type { RewindMode } from "./use-rewind-capabilities"; @@ -29,7 +29,14 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): { const toast = useToast(); const { t } = useTranslation(); const composerRestore = useRewindComposerRestore(); - const { isPending, mutateAsync } = useMutation({ + const queryClient = useQueryClient(); + const mutationKey = useMemo( + () => ["agent-rewind", input.serverId, input.agentId], + [input.serverId, input.agentId], + ); + const isPending = useIsMutating({ mutationKey, exact: true }) > 0; + const { mutateAsync } = useMutation({ + mutationKey, mutationFn: async ({ mode }: RewindAgentInput) => { if (!input.client || !input.agentId || !input.messageId) { throw new Error(t("common.errors.daemonClientUnavailable")); @@ -61,12 +68,12 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): { const rewindAgent = useCallback( async (rewindInput: RewindAgentInput) => { - if (isPending) { + if (queryClient.isMutating({ mutationKey, exact: true }) > 0) { return; } await mutateAsync(rewindInput); }, - [isPending, mutateAsync], + [mutateAsync, mutationKey, queryClient], ); return { diff --git a/packages/app/src/components/rewind/use-rewind-capabilities.ts b/packages/app/src/components/rewind/use-rewind-capabilities.ts index d125bfce37..0249335a03 100644 --- a/packages/app/src/components/rewind/use-rewind-capabilities.ts +++ b/packages/app/src/components/rewind/use-rewind-capabilities.ts @@ -1,4 +1,5 @@ import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types"; export type RewindMode = "conversation" | "files" | "both"; @@ -21,6 +22,10 @@ const DEFAULT_REWIND_MENU_LABELS: RewindMenuLabels = { both: "Rewind conversation and files", }; +export function isRewindableMessage(messageId: string | undefined, text: string): boolean { + return Boolean(messageId) && text.trim().length > 0; +} + export function resolveRewindMenuItems( capabilities: | Pick< @@ -60,9 +65,17 @@ export function resolveRewindMenuItems( return items; } -export function useRewindCapabilities( +export function useRewindMenuItems( capabilities: Parameters[0], - labels?: Partial, ): RewindMenuItem[] { - return useMemo(() => resolveRewindMenuItems(capabilities, labels), [capabilities, labels]); + const { t } = useTranslation(); + return useMemo( + () => + resolveRewindMenuItems(capabilities, { + conversation: t("rewind.actions.conversation"), + files: t("rewind.actions.files"), + both: t("rewind.actions.both"), + }), + [capabilities, t], + ); } diff --git a/packages/app/src/composer/editing-session/index.tsx b/packages/app/src/composer/editing-session/index.tsx index 237b15251a..ca0e4ac1b2 100644 --- a/packages/app/src/composer/editing-session/index.tsx +++ b/packages/app/src/composer/editing-session/index.tsx @@ -45,6 +45,9 @@ export class ComposerEditingSession { if (this.editor === editor) this.editor = null; }; } + focus() { + this.editor?.focus(); + } insertCommand(command: string) { const editor = this.editor; if (!editor) return; diff --git a/packages/app/src/panels/agent-panel.tsx b/packages/app/src/panels/agent-panel.tsx index 709281ed7d..46096dd6b6 100644 --- a/packages/app/src/panels/agent-panel.tsx +++ b/packages/app/src/panels/agent-panel.tsx @@ -39,7 +39,10 @@ import { resolveComposerTrackTailClearance, } from "@/composer/pill-styles"; import { getActiveMessageSubmissions } from "@/composer/submission/model"; -import { RewindComposerRestoreProvider } from "@/components/rewind/composer-restore"; +import { + RewindCommandCenterRegistration, + RewindComposerRestoreProvider, +} from "@/components/rewind"; import { useAgentDescriptor } from "@/agent-presentation"; import { useToastHost, type ToastApi, type ToastState } from "@/components/toast-host"; import type { WorkspaceComposerAttachment } from "@/attachments/types"; @@ -57,6 +60,7 @@ import { type AgentScreenReadySyncState, } from "@/hooks/use-agent-screen-state-machine"; import { useArchiveAgent } from "@/hooks/use-archive-agent"; +import { useStableEvent } from "@/hooks/use-stable-event"; import { useContainerWidthBelow } from "@/hooks/use-container-width"; import { reconcileMissingAgentStateWithPresentAgent } from "@/panels/agent-panel-load-state"; import { TimelineSyncStatus } from "@/timeline/sync-status"; @@ -864,10 +868,6 @@ function ChatAgentContent({ streamViewRef.current?.scrollToBottom("message-sent"); }, [agentId]); - const handleRewindComplete = useCallback(() => { - streamViewRef.current?.scrollToBottom("rewind"); - }, []); - const retryAgentLoad = useCallback(() => { setMissingAgentState({ kind: "idle" }); if (!agentId || !viewedTimelineSync) return; @@ -1022,7 +1022,6 @@ function ChatAgentContent({ streamViewRef={streamViewRef} handleComposerHeightChange={handleComposerHeightChange} handleMessageSent={handleMessageSent} - handleRewindComplete={handleRewindComplete} timelineSync={isPaneVisible && viewState.tag === "ready" ? viewState.sync : null} showHistorySyncOverlay={showHistorySyncOverlay} showHistorySyncError={showHistorySyncError} @@ -1054,7 +1053,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ streamViewRef, handleComposerHeightChange, handleMessageSent, - handleRewindComplete, timelineSync, showHistorySyncOverlay, showHistorySyncError, @@ -1083,7 +1081,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ streamViewRef: React.RefObject; handleComposerHeightChange: (height: number) => void; handleMessageSent: () => void; - handleRewindComplete: () => void; timelineSync: AgentScreenReadySyncState | null; showHistorySyncOverlay: boolean; showHistorySyncError: boolean; @@ -1102,6 +1099,22 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ const composerEditingSession = useComposerEditingSession("chat"); const isComposerFullscreen = useComposerFullscreen(composerEditingSession); const hasActiveComposer = !agentState.archivedAt && !isArchivingCurrentAgent; + const focusRestoredComposer = useStableEvent(() => { + if (isPaneFocused && showsComposer && hasActiveComposer) { + composerEditingSession.focus(); + } + }); + const handleRewindComplete = useCallback( + (restoredComposerText: boolean) => { + streamViewRef.current?.scrollToBottom("rewind"); + if (restoredComposerText) { + // Defer focus so the editor can apply the restored draft and the menu can start closing. + requestAnimationFrame(focusRestoredComposer); + } + }, + [focusRestoredComposer, streamViewRef], + ); + const hasAgentComposer = showsComposer && hasActiveComposer && !draft; const parentAgentId = useParentAgentId(serverId, agentId); // With a composer the parent is a pill above it; without one, the box takes the composer's place. const parentPillAgentId = showsComposer ? parentAgentId : null; @@ -1262,6 +1275,15 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ setText={agentInputDraft.replaceText} onRewindComplete={handleRewindComplete} > + {hasAgentComposer ? ( + + ) : null} {dock} @@ -1276,7 +1298,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({ ); return wrapAgentCommandProvider({ - enabled: showsComposer && hasActiveComposer && !draft, + enabled: hasAgentComposer, serverId, agentId, editingSession: composerEditingSession,