mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 04:36:26 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6404462843 | ||
|
|
7eef6dab43 |
@@ -9,7 +9,9 @@ import {
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import {
|
||||
attachComposerTestImage,
|
||||
attachFileFromMenu,
|
||||
composerLocator,
|
||||
expectAttachmentPill,
|
||||
expectComposerDraft,
|
||||
expectComposerFocused,
|
||||
expectComposerNotFocused,
|
||||
@@ -46,6 +48,13 @@ async function selectRewindOption(page: Page, name: string): Promise<void> {
|
||||
await option.click();
|
||||
}
|
||||
|
||||
async function rewindMessageWithImage(page: Page, prompt: string): Promise<void> {
|
||||
const message = userMessage(page, prompt);
|
||||
await expect(message.getByRole("button", { name: "Open image attachment" })).toBeVisible();
|
||||
await message.getByRole("button", { name: "Rewind to this message" }).press("Enter");
|
||||
await selectRewindOption(page, "Rewind conversation");
|
||||
}
|
||||
|
||||
async function searchRewindActions(page: Page): Promise<Locator> {
|
||||
const palette = await openCommandCenter(page);
|
||||
await selectCommandCenterTab(palette, "Actions");
|
||||
@@ -379,6 +388,140 @@ test.describe("Rewind sheet", () => {
|
||||
}
|
||||
});
|
||||
|
||||
for (const prompt of ["Review these attachments", ""]) {
|
||||
test(`restores images and files after rewind (${prompt ? "with text" : "attachments only"})`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const session = await seedMockAgentWorkspace({
|
||||
repoPrefix: "rewind-attachments-e2e-",
|
||||
title: "Rewind attachments",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, session);
|
||||
await expectComposerVisible(page);
|
||||
await attachComposerTestImage(page);
|
||||
await attachFileFromMenu(page, {
|
||||
name: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
buffer: Buffer.from("Review notes"),
|
||||
});
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
|
||||
await expect(page.getByTestId("composer-file-attachment-pill")).toContainText("notes.txt");
|
||||
await fillComposerDraft(page, prompt);
|
||||
await page.getByRole("button", { name: "Send message", exact: true }).click();
|
||||
await expect(page.getByTestId("user-message")).toHaveCount(1);
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
|
||||
await expect(page.getByTestId("composer-file-attachment-pill")).toHaveCount(0);
|
||||
await session.client.waitForFinish(session.agentId);
|
||||
await page.getByTestId("user-message").getByText("notes.txt", { exact: true }).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").click();
|
||||
await selectRewindOption(page, "Rewind conversation");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, prompt);
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
|
||||
await expect(page.getByTestId("composer-file-attachment-pill")).toContainText("notes.txt");
|
||||
await page.getByRole("button", { name: "Send message", exact: true }).click();
|
||||
await expect(page.getByTestId("user-message").last()).toContainText("notes.txt");
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("user-message")
|
||||
.last()
|
||||
.getByRole("button", { name: "Open image attachment" }),
|
||||
).toBeVisible();
|
||||
await expectComposerDraft(page, "");
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
|
||||
await expect(page.getByTestId("composer-file-attachment-pill")).toHaveCount(0);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("restores a sent image when rewinding after reload", async ({ page }) => {
|
||||
const prompt = "Review this image after reloading the chat.";
|
||||
const session = await seedMockAgentWorkspace({
|
||||
repoPrefix: "rewind-uploaded-image-e2e-",
|
||||
title: "Rewind uploaded image",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, session);
|
||||
await expectComposerVisible(page);
|
||||
await attachComposerTestImage(page);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await submitMessageWithButton(page, prompt);
|
||||
await expect(
|
||||
userMessage(page, prompt).getByRole("button", { name: "Open image attachment" }),
|
||||
).toBeVisible();
|
||||
await session.client.waitForFinish(session.agentId);
|
||||
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await rewindMessageWithImage(page, prompt);
|
||||
await expectComposerDraft(page, prompt);
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
|
||||
|
||||
await submitMessageWithButton(page, prompt);
|
||||
await expect(
|
||||
userMessage(page, prompt).getByRole("button", { name: "Open image attachment" }),
|
||||
).toBeVisible();
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
const existingDrafts = [
|
||||
{
|
||||
name: "typed text",
|
||||
text: "Keep this draft.",
|
||||
fileCount: 0,
|
||||
prepare: (page: Page) => fillComposerDraft(page, "Keep this draft."),
|
||||
},
|
||||
{
|
||||
name: "an uploaded file",
|
||||
text: "",
|
||||
fileCount: 1,
|
||||
prepare: async (page: Page) => {
|
||||
await attachFileFromMenu(page, {
|
||||
name: "draft.txt",
|
||||
mimeType: "text/plain",
|
||||
buffer: Buffer.from("Keep this draft file"),
|
||||
});
|
||||
await expectAttachmentPill(page, "composer-file-attachment-pill");
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
for (const draft of existingDrafts) {
|
||||
test(`preserves a draft containing ${draft.name} when rewinding a sent image`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const prompt = "Review this image before rewind.";
|
||||
const session = await seedMockAgentWorkspace({
|
||||
repoPrefix: "rewind-keeps-draft-e2e-",
|
||||
title: "Rewind with an existing draft",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, session);
|
||||
await expectComposerVisible(page);
|
||||
await attachComposerTestImage(page);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await submitMessageWithButton(page, prompt);
|
||||
await session.client.waitForFinish(session.agentId);
|
||||
await draft.prepare(page);
|
||||
|
||||
await rewindMessageWithImage(page, prompt);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectComposerDraft(page, draft.text);
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
|
||||
await expect(page.getByTestId("composer-file-attachment-pill")).toHaveCount(
|
||||
draft.fileCount,
|
||||
);
|
||||
} 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.";
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { createAssistantImageAcquisitionCache } from "@/assistant-image/acquisition-cache";
|
||||
import { retainAttachmentForGarbageCollection } from "@/attachments/gc-retention";
|
||||
import { persistAttachmentFromBytes } from "@/attachments/service";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
|
||||
import type { DaemonUploadedImageAttachment } from "@/types/stream";
|
||||
|
||||
type UploadedImageSource = Pick<
|
||||
DaemonUploadedImageAttachment,
|
||||
"id" | "path" | "mimeType" | "fileName"
|
||||
>;
|
||||
|
||||
const uploadedImageCache = createAssistantImageAcquisitionCache<AttachmentMetadata>({
|
||||
capacity: 200,
|
||||
onRetain: (attachment) => retainAttachmentForGarbageCollection(attachment.id),
|
||||
});
|
||||
|
||||
export function daemonUploadedImageCacheKey(
|
||||
serverId: string | undefined,
|
||||
image: Pick<UploadedImageSource, "id" | "path">,
|
||||
): string {
|
||||
return [serverId ?? "local", image.id, image.path].join("\u0000");
|
||||
}
|
||||
|
||||
function buildLocalAttachmentId(serverId: string | undefined, uploadId: string): string {
|
||||
const safeServer = (serverId ?? "local").replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
const safeUpload = uploadId.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
return `daemon-upload-${safeServer}-${safeUpload}`;
|
||||
}
|
||||
|
||||
export function acquireDaemonUploadedImage(input: {
|
||||
image: UploadedImageSource;
|
||||
client: Pick<DaemonClient, "readFile">;
|
||||
serverId?: string;
|
||||
}) {
|
||||
const { client, image, serverId } = input;
|
||||
return uploadedImageCache.acquireRetained(
|
||||
daemonUploadedImageCacheKey(serverId, image),
|
||||
async () => {
|
||||
const target = resolveFilePreviewReadTarget({ path: image.path });
|
||||
if (!target) throw new Error("Invalid uploaded image path.");
|
||||
const file = await client.readFile(target.cwd, target.path);
|
||||
return await persistAttachmentFromBytes({
|
||||
id: buildLocalAttachmentId(serverId, image.id),
|
||||
bytes: file.bytes,
|
||||
mimeType: image.mimeType || file.mime,
|
||||
fileName: image.fileName,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export async function acquireUserMessageImage(input: {
|
||||
image: AttachmentMetadata | DaemonUploadedImageAttachment;
|
||||
client: Pick<DaemonClient, "readFile">;
|
||||
serverId?: string;
|
||||
}): Promise<AttachmentMetadata> {
|
||||
if (input.image.storageType !== "daemon-upload") return input.image;
|
||||
const retained = acquireDaemonUploadedImage({ ...input, image: input.image });
|
||||
try {
|
||||
return await retained.promise;
|
||||
} finally {
|
||||
retained.release();
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,9 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { createAssistantImageAcquisitionCache } from "@/assistant-image/acquisition-cache";
|
||||
import { retainAttachmentForGarbageCollection } from "@/attachments/gc-retention";
|
||||
import { persistAttachmentFromBytes } from "@/attachments/service";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
|
||||
import { acquireDaemonUploadedImage, daemonUploadedImageCacheKey } from "./daemon-uploaded-image";
|
||||
import type { DaemonUploadedImageAttachment } from "@/types/stream";
|
||||
|
||||
const uploadedImageCache = createAssistantImageAcquisitionCache<AttachmentMetadata>({
|
||||
capacity: 200,
|
||||
onRetain: (attachment) => retainAttachmentForGarbageCollection(attachment.id),
|
||||
});
|
||||
|
||||
function buildCacheKey(serverId: string | undefined, image: DaemonUploadedImageAttachment): string {
|
||||
return [serverId ?? "local", image.id, image.path].join("\u0000");
|
||||
}
|
||||
|
||||
function buildLocalAttachmentId(serverId: string | undefined, uploadId: string): string {
|
||||
const safeServer = (serverId ?? "local").replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
const safeUpload = uploadId.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
return `daemon-upload-${safeServer}-${safeUpload}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a daemon-stored uploaded image through `client.readFile` (binary chunked stream),
|
||||
* persists it into the local attachment store, and retains it in a bounded LRU cache so
|
||||
@@ -33,7 +15,8 @@ export function useDaemonUploadedImage(input: {
|
||||
serverId?: string;
|
||||
}): AttachmentMetadata | null {
|
||||
const { image, client, serverId } = input;
|
||||
const cacheKey = buildCacheKey(serverId, image);
|
||||
const { id, path, mimeType, fileName } = image;
|
||||
const cacheKey = daemonUploadedImageCacheKey(serverId, image);
|
||||
const [resolved, setResolved] = useState<{ key: string; metadata: AttachmentMetadata } | null>(
|
||||
null,
|
||||
);
|
||||
@@ -42,20 +25,11 @@ export function useDaemonUploadedImage(input: {
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
const target = resolveFilePreviewReadTarget({ path: image.path });
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
const retained = uploadedImageCache.acquireRetained(cacheKey, async () => {
|
||||
const file = await client.readFile(target.cwd, target.path);
|
||||
return await persistAttachmentFromBytes({
|
||||
id: buildLocalAttachmentId(serverId, image.id),
|
||||
bytes: file.bytes,
|
||||
mimeType: image.mimeType || file.mime,
|
||||
fileName: image.fileName,
|
||||
});
|
||||
const retained = acquireDaemonUploadedImage({
|
||||
client,
|
||||
image: { id, path, mimeType, fileName },
|
||||
serverId,
|
||||
});
|
||||
|
||||
void retained.promise
|
||||
@@ -67,8 +41,8 @@ export function useDaemonUploadedImage(input: {
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn("[attachments] Failed to load uploaded user message image", {
|
||||
id: image.id,
|
||||
path: image.path,
|
||||
id,
|
||||
path,
|
||||
error,
|
||||
});
|
||||
});
|
||||
@@ -77,7 +51,7 @@ export function useDaemonUploadedImage(input: {
|
||||
cancelled = true;
|
||||
retained.release();
|
||||
};
|
||||
}, [cacheKey, client, image.fileName, image.id, image.mimeType, image.path, serverId]);
|
||||
}, [cacheKey, client, fileName, id, mimeType, path, serverId]);
|
||||
|
||||
return resolved?.key === cacheKey ? resolved.metadata : null;
|
||||
}
|
||||
|
||||
@@ -475,12 +475,20 @@ export const UserMessage = memo(function UserMessage({
|
||||
const hasText = message.trim().length > 0;
|
||||
const hasImages = images.length > 0;
|
||||
const hasAttachments = attachments.length > 0;
|
||||
const showTrailingRow = !isPending && hasText && (isCompact || isNative || isHovered);
|
||||
const hasContent = hasText || hasImages || hasAttachments;
|
||||
const showTrailingRow = !isPending && hasContent && (isCompact || isNative || isHovered);
|
||||
const formattedTimestamp = useMemo(
|
||||
() => formatMessageTimestamp(new Date(timestamp)),
|
||||
[timestamp],
|
||||
);
|
||||
const rewindMutation = useRewindAgentMutation({ serverId, agentId, client, messageId });
|
||||
const rewindMutation = useRewindAgentMutation({
|
||||
serverId,
|
||||
agentId,
|
||||
client,
|
||||
messageId,
|
||||
images,
|
||||
attachments,
|
||||
});
|
||||
|
||||
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setIsHovered(false), []);
|
||||
@@ -576,30 +584,30 @@ export const UserMessage = memo(function UserMessage({
|
||||
) : null}
|
||||
</MessagePreview>
|
||||
</View>
|
||||
{hasText ? (
|
||||
<View
|
||||
style={trailingRowStyle}
|
||||
pointerEvents={showTrailingRow ? "auto" : "none"}
|
||||
testID="user-message-trailing-row"
|
||||
>
|
||||
<Text style={userMessageStylesheet.timestampText} testID="user-message-timestamp">
|
||||
{formattedTimestamp}
|
||||
</Text>
|
||||
{capabilities && isRewindableMessage(messageId, message) ? (
|
||||
<RewindMenu
|
||||
capabilities={capabilities}
|
||||
isPending={rewindMutation.isPending}
|
||||
rewoundText={message}
|
||||
onRewind={handleRewind}
|
||||
/>
|
||||
) : null}
|
||||
<View
|
||||
style={trailingRowStyle}
|
||||
pointerEvents={showTrailingRow ? "auto" : "none"}
|
||||
testID="user-message-trailing-row"
|
||||
>
|
||||
<Text style={userMessageStylesheet.timestampText} testID="user-message-timestamp">
|
||||
{formattedTimestamp}
|
||||
</Text>
|
||||
{capabilities && isRewindableMessage(messageId, hasContent) ? (
|
||||
<RewindMenu
|
||||
capabilities={capabilities}
|
||||
isPending={rewindMutation.isPending}
|
||||
rewoundText={message}
|
||||
onRewind={handleRewind}
|
||||
/>
|
||||
) : null}
|
||||
{hasText ? (
|
||||
<TurnCopyButton
|
||||
getContent={getMessageContent}
|
||||
containerStyle={userMessageStylesheet.copyButton}
|
||||
accessibilityLabel={t("message.actions.copyMessage")}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
<AttachmentLightbox source={lightboxSource} onClose={handleLightboxClose} />
|
||||
</View>
|
||||
|
||||
@@ -62,10 +62,13 @@ export function RewindCommandCenterRegistration({
|
||||
agentId,
|
||||
client,
|
||||
messageId: message?.messageId,
|
||||
images: message?.images,
|
||||
attachments: message?.attachments,
|
||||
});
|
||||
const items = useRewindMenuItems(capabilities);
|
||||
const actions = useMemo<CommandCenterContribution[]>(() => {
|
||||
if (!message || !isRewindableMessage(message.messageId, message.text)) return [];
|
||||
if (!message || !isRewindableMessage(message.messageId, message.text.trim().length > 0))
|
||||
return [];
|
||||
return items.map((item, rank) => ({
|
||||
id: `rewind:${item.mode}`,
|
||||
group: "rewind",
|
||||
|
||||
@@ -1,27 +1,10 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { restoreComposerTextIfEmpty } from "./composer-restore";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import type { UploadedFileAttachment } from "@getpaseo/protocol/messages";
|
||||
import { splitComposerAttachmentsForSubmit } from "@/composer/attachments/submit";
|
||||
import { composeRewoundAttachments } from "./composer-restore";
|
||||
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
|
||||
|
||||
describe("restoreComposerTextIfEmpty", () => {
|
||||
test("restores the rewound message when the composer is empty", () => {
|
||||
expect(
|
||||
restoreComposerTextIfEmpty({
|
||||
currentText: "",
|
||||
rewoundText: "message before rewind",
|
||||
}),
|
||||
).toBe("message before rewind");
|
||||
});
|
||||
|
||||
test("preserves an existing composer draft", () => {
|
||||
expect(
|
||||
restoreComposerTextIfEmpty({
|
||||
currentText: "keep this draft",
|
||||
rewoundText: "message before rewind",
|
||||
}),
|
||||
).toBe("keep this draft");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldRestoreComposerForRewindMode", () => {
|
||||
test("restores only conversation-mutating rewind modes", () => {
|
||||
expect(shouldRestoreComposerForRewindMode("conversation")).toBe(true);
|
||||
@@ -29,3 +12,55 @@ describe("shouldRestoreComposerForRewindMode", () => {
|
||||
expect(shouldRestoreComposerForRewindMode("both")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
const image: AttachmentMetadata = {
|
||||
id: "image-1",
|
||||
mimeType: "image/png",
|
||||
storageType: "web-indexeddb",
|
||||
storageKey: "image-1",
|
||||
fileName: "screenshot.png",
|
||||
createdAt: 1,
|
||||
};
|
||||
const file: UploadedFileAttachment = {
|
||||
type: "uploaded_file",
|
||||
id: "file-1",
|
||||
fileName: "notes.txt",
|
||||
mimeType: "text/plain",
|
||||
size: 5,
|
||||
path: "/uploads/notes.txt",
|
||||
};
|
||||
|
||||
describe("composeRewoundAttachments", () => {
|
||||
test("restores images and uploaded files ready for resubmission", () => {
|
||||
const restored = composeRewoundAttachments({
|
||||
text: "Review these",
|
||||
images: [image],
|
||||
attachments: [file],
|
||||
});
|
||||
expect(restored).toEqual([
|
||||
{ kind: "image", metadata: image },
|
||||
{ kind: "file", attachment: file },
|
||||
]);
|
||||
expect(splitComposerAttachmentsForSubmit(restored)).toEqual({
|
||||
images: [image],
|
||||
attachments: [file],
|
||||
});
|
||||
});
|
||||
|
||||
test("restores an image-only message", () => {
|
||||
expect(
|
||||
composeRewoundAttachments({
|
||||
text: "",
|
||||
images: [image],
|
||||
}),
|
||||
).toEqual([{ kind: "image", metadata: image }]);
|
||||
});
|
||||
|
||||
test("keeps text-only messages free of attachments", () => {
|
||||
expect(
|
||||
composeRewoundAttachments({
|
||||
text: "hello",
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,49 +1,51 @@
|
||||
import type { ComposerTextSource } from "@/composer/text-source";
|
||||
import type { AttachmentMetadata, UserComposerAttachment } from "@/attachments/types";
|
||||
import type { AgentInputDraft } from "@/composer/draft/input-draft";
|
||||
import type { UserMessageItem } from "@/types/stream";
|
||||
import { createContext, useCallback, useContext, useMemo, type ReactNode } from "react";
|
||||
|
||||
type RewoundMessage = Pick<UserMessageItem, "text" | "attachments"> & {
|
||||
images?: AttachmentMetadata[];
|
||||
};
|
||||
|
||||
interface RewindComposerRestoreContextValue {
|
||||
completeRewind: (text: string) => void;
|
||||
completeRewind: (message: RewoundMessage) => void;
|
||||
}
|
||||
|
||||
interface RewindComposerRestoreProviderProps {
|
||||
textSource: ComposerTextSource;
|
||||
setText: (text: string) => void;
|
||||
restoreIfEmpty: AgentInputDraft["restoreIfEmpty"];
|
||||
onRewindComplete: (restoredComposerText: boolean) => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const RewindComposerRestoreContext = createContext<RewindComposerRestoreContextValue | null>(null);
|
||||
|
||||
export function restoreComposerTextIfEmpty(input: {
|
||||
currentText: string;
|
||||
rewoundText: string;
|
||||
}): string {
|
||||
if (input.currentText.length > 0) {
|
||||
return input.currentText;
|
||||
export function composeRewoundAttachments(message: RewoundMessage): UserComposerAttachment[] {
|
||||
const attachments: UserComposerAttachment[] = (message.images ?? []).map((metadata) => ({
|
||||
kind: "image",
|
||||
metadata,
|
||||
}));
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
if (attachment.type === "uploaded_file") {
|
||||
attachments.push({ kind: "file", attachment });
|
||||
}
|
||||
}
|
||||
return input.rewoundText;
|
||||
return attachments;
|
||||
}
|
||||
|
||||
export function RewindComposerRestoreProvider({
|
||||
textSource,
|
||||
setText,
|
||||
restoreIfEmpty,
|
||||
onRewindComplete,
|
||||
children,
|
||||
}: RewindComposerRestoreProviderProps) {
|
||||
const completeRewind = useCallback(
|
||||
(rewoundText: string) => {
|
||||
const currentText = textSource.getSnapshot();
|
||||
const nextText = restoreComposerTextIfEmpty({
|
||||
currentText: currentText,
|
||||
rewoundText,
|
||||
(message: RewoundMessage) => {
|
||||
const restored = restoreIfEmpty({
|
||||
text: message.text,
|
||||
attachments: composeRewoundAttachments(message),
|
||||
});
|
||||
const restoredComposerText = nextText !== currentText;
|
||||
if (restoredComposerText) {
|
||||
setText(nextText);
|
||||
}
|
||||
onRewindComplete(restoredComposerText);
|
||||
onRewindComplete(restored && message.text.length > 0);
|
||||
},
|
||||
[onRewindComplete, setText, textSource],
|
||||
[onRewindComplete, restoreIfEmpty],
|
||||
);
|
||||
|
||||
const value = useMemo(() => ({ completeRewind }), [completeRewind]);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { acquireUserMessageImage } from "@/attachments/daemon-uploaded-image";
|
||||
import type { UserMessageItem } from "@/types/stream";
|
||||
import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -16,6 +18,8 @@ interface UseRewindAgentMutationInput {
|
||||
agentId?: string;
|
||||
messageId?: string;
|
||||
client?: DaemonClient | null;
|
||||
images: UserMessageItem["images"];
|
||||
attachments: UserMessageItem["attachments"];
|
||||
}
|
||||
|
||||
interface RewindAgentInput {
|
||||
@@ -38,11 +42,24 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
const isPending = useIsMutating({ mutationKey, exact: true }) > 0;
|
||||
const { mutateAsync } = useMutation({
|
||||
mutationKey,
|
||||
mutationFn: async ({ mode }: RewindAgentInput) => {
|
||||
mutationFn: async ({ mode, rewoundText }: RewindAgentInput) => {
|
||||
if (!input.client || !input.agentId || !input.messageId) {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
const client = input.client;
|
||||
const draft =
|
||||
composerRestore && shouldRestoreComposerForRewindMode(mode)
|
||||
? {
|
||||
text: rewoundText,
|
||||
images: await Promise.all(
|
||||
(input.images ?? []).map((image) =>
|
||||
acquireUserMessageImage({ image, client, serverId: input.serverId }),
|
||||
),
|
||||
),
|
||||
attachments: input.attachments,
|
||||
}
|
||||
: null;
|
||||
await client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
// COMPAT(timelineRewindOperations): added in v0.18.0, remove after 2027-05-25. A daemon with
|
||||
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
|
||||
// and this client has to read it again.
|
||||
@@ -64,12 +81,10 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
...(cursor ? { cursor: { epoch: cursor.epoch, seq: cursor.endSeq } } : {}),
|
||||
});
|
||||
}
|
||||
return draft;
|
||||
},
|
||||
onSuccess: (_data, variables) => {
|
||||
if (!shouldRestoreComposerForRewindMode(variables.mode)) {
|
||||
return;
|
||||
}
|
||||
composerRestore?.completeRewind(variables.rewoundText);
|
||||
onSuccess: (draft) => {
|
||||
if (draft) composerRestore?.completeRewind(draft);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error instanceof Error ? error.message : t("rewind.errors.failed"));
|
||||
|
||||
@@ -22,8 +22,8 @@ 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 isRewindableMessage(messageId: string | undefined, hasContent: boolean): boolean {
|
||||
return Boolean(messageId) && hasContent;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -66,6 +66,7 @@ export interface AgentInputDraft {
|
||||
textSource: ComposerTextSource;
|
||||
editText: (text: string) => void;
|
||||
replaceText: (text: string) => void;
|
||||
restoreIfEmpty: (draft: DraftInput) => boolean;
|
||||
textReplacement: TextReplacement;
|
||||
attachments: UserComposerAttachment[];
|
||||
setAttachments: (updater: AttachmentUpdater) => void;
|
||||
@@ -189,6 +190,16 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
[draftKey, publishTextReplacement, textPublication],
|
||||
);
|
||||
|
||||
const restoreIfEmpty = useCallback(
|
||||
(draft: DraftInput) => {
|
||||
textPublication.flush();
|
||||
if (!useDraftStore.getState().restoreDraftInputIfEmpty({ draftKey, draft })) return false;
|
||||
if (draft.text.length > 0) publishTextReplacement("replace", draft.text);
|
||||
return true;
|
||||
},
|
||||
[draftKey, publishTextReplacement, textPublication],
|
||||
);
|
||||
|
||||
const setAttachments = useCallback(
|
||||
(updater: AttachmentUpdater) => {
|
||||
saveDraft((current) => ({
|
||||
@@ -390,6 +401,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
textSource,
|
||||
editText,
|
||||
replaceText,
|
||||
restoreIfEmpty,
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
|
||||
@@ -1189,6 +1189,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
textSource,
|
||||
editText,
|
||||
replaceText,
|
||||
restoreIfEmpty,
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
@@ -1202,6 +1203,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
textSource,
|
||||
editText,
|
||||
replaceText,
|
||||
restoreIfEmpty,
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
@@ -1214,6 +1216,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
textSource,
|
||||
editText,
|
||||
replaceText,
|
||||
restoreIfEmpty,
|
||||
textReplacement,
|
||||
attachments,
|
||||
setAttachments,
|
||||
@@ -1335,8 +1338,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
|
||||
const content = (
|
||||
<RewindComposerRestoreProvider
|
||||
textSource={agentInputDraft.textSource}
|
||||
setText={agentInputDraft.replaceText}
|
||||
restoreIfEmpty={agentInputDraft.restoreIfEmpty}
|
||||
onRewindComplete={handleRewindComplete}
|
||||
>
|
||||
{hasAgentComposer ? (
|
||||
|
||||
@@ -46,6 +46,7 @@ interface DraftStoreActions {
|
||||
getDraftInput: (draftKey: string) => DraftInput | undefined;
|
||||
hydrateDraftInput: (input: { draftKey: string }) => Promise<DraftInput | undefined>;
|
||||
saveDraftInput: (input: { draftKey: string; draft: DraftInput }) => void;
|
||||
restoreDraftInputIfEmpty: (input: { draftKey: string; draft: DraftInput }) => boolean;
|
||||
/** Saves what `update` makes of the current input; an emptied input abandons the draft. */
|
||||
updateDraftInput: (input: {
|
||||
draftKey: string;
|
||||
@@ -343,6 +344,18 @@ export const useDraftStore = create<DraftStore>()(
|
||||
scheduleAttachmentGc();
|
||||
},
|
||||
|
||||
restoreDraftInputIfEmpty: ({ draftKey, draft }) => {
|
||||
const store = get();
|
||||
const record = store.drafts[draftKey];
|
||||
if (record?.lifecycle === "active") {
|
||||
const current = toDraftInputIfReady(record);
|
||||
if (!current || hasDraftContent(current)) return false;
|
||||
}
|
||||
if (!hasDraftContent(draft)) return false;
|
||||
store.saveDraftInput({ draftKey, draft });
|
||||
return true;
|
||||
},
|
||||
|
||||
updateDraftInput: ({ draftKey, update }) => {
|
||||
const next = update(get().getDraftInput(draftKey) ?? { text: "", attachments: [] });
|
||||
if (hasDraftContent(next)) get().saveDraftInput({ draftKey, draft: next });
|
||||
|
||||
Reference in New Issue
Block a user