Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(web): preserve AI refinement context

tianma-if110c238373af
diff --git a/apps/web/src/components/dialogs/AiAssistantDialog.tsx b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
index 50209378..c9a7d186 100644
--- a/apps/web/src/components/dialogs/AiAssistantDialog.tsx
+++ b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
@@ -42,6 +42,7 @@ import {
import {
aiTones,
buildAiAssistantRequest,
+ buildAiRefinementInstruction,
getDefaultAiAction,
getDefaultTargetLanguage,
promptAllowsAppend,
@@ -143,7 +144,10 @@ export const AiAssistantDialog = ({
const attachmentInputRef = useRef<HTMLInputElement | null>(null);
const attachmentReadIdRef = useRef(0);
const customInstructionEditedRef = useRef(false);
- const lastRequestRef = useRef<Parameters<typeof api.streamAiGeneration>[0] | null>(null);
+ const lastRequestRef = useRef<{
+ preserveOutput: boolean;
+ request: Parameters<typeof api.streamAiGeneration>[0];
+ } | null>(null);
const assignPanelRef = useCallback((node: HTMLElement | null) => {
panelRef.current = node;
setPanelElement(node);
@@ -292,22 +296,33 @@ export const AiAssistantDialog = ({
clearResult();
};
- const runGeneration = async (request: Parameters<typeof api.streamAiGeneration>[0]) => {
+ const runGeneration = async (
+ request: Parameters<typeof api.streamAiGeneration>[0],
+ { preserveOutput = false }: { preserveOutput?: boolean } = {},
+ ) => {
controllerRef.current?.abort();
const controller = new AbortController();
controllerRef.current = controller;
- lastRequestRef.current = request;
- setOutput("");
+ lastRequestRef.current = { preserveOutput, request };
+ if (!preserveOutput) setOutput("");
setError(null);
setCopied(false);
setIsGenerating(true);
+ let receivedOutput = false;
try {
await api.streamAiGeneration(
request,
{
signal: controller.signal,
onEvent: (event) => {
- if (event.type === "text-delta") setOutput((current) => current + event.text);
+ if (event.type === "text-delta") {
+ if (preserveOutput && !receivedOutput) {
+ receivedOutput = true;
+ setOutput(event.text);
+ } else {
+ setOutput((current) => current + event.text);
+ }
+ }
if (event.type === "error") setError(event.message);
},
},
@@ -388,17 +403,33 @@ export const AiAssistantDialog = ({
const refine = () => {
const instruction = refinement.trim();
if (!output || !instruction) return;
- setRefinement("");
+ const refinementTargetLanguage = promptNeedsTargetLanguage(effectiveParameterKind)
+ ? targetLanguage
+ : undefined;
+ const refinementTone = promptNeedsTone(effectiveParameterKind) ? tone : undefined;
return runGeneration({
action: "custom",
- title,
+ title: "",
contentMarkdown: output,
- instruction,
- });
+ instruction: buildAiRefinementInstruction({
+ originalAction: effectiveActionKey,
+ originalInstruction: selectedPrompt?.instruction
+ ?? (isFreeformCustom ? customInstruction : undefined),
+ refinement: instruction,
+ targetLanguage: refinementTargetLanguage,
+ tone: refinementTone,
+ }),
+ targetLanguage: refinementTargetLanguage,
+ tone: refinementTone,
+ }, { preserveOutput: true });
};
const retry = () => {
- if (lastRequestRef.current) return runGeneration(lastRequestRef.current);
+ if (lastRequestRef.current) {
+ return runGeneration(lastRequestRef.current.request, {
+ preserveOutput: lastRequestRef.current.preserveOutput,
+ });
+ }
return generate();
};
@@ -824,7 +855,7 @@ export const AiAssistantDialog = ({
onChange={(event) => setRefinement(event.target.value)}
aria-label={t("aiAssistant.refine")}
onKeyDown={(event) => {
- if (event.key === "Enter" && !event.nativeEvent.isComposing && refinement.trim()) {
+ if (event.key === "Enter" && !event.nativeEvent.isComposing && !isGenerating && refinement.trim()) {
event.preventDefault();
void refine();
}
@@ -832,7 +863,7 @@ export const AiAssistantDialog = ({
placeholder={t("aiAssistant.refinePlaceholder")}
maxLength={2_000}
/>
- <Button type="button" variant="outline" disabled={!refinement.trim()} onClick={() => void refine()}>{t("aiAssistant.refineAction")}</Button>
+ <Button type="button" variant="outline" disabled={isGenerating || !refinement.trim()} onClick={() => void refine()}>{t("aiAssistant.refineAction")}</Button>
</div>
</div>
) : null}
diff --git a/apps/web/src/lib/ai-assistant.test.mjs b/apps/web/src/lib/ai-assistant.test.mjs
index a7d66768..186b1ce8 100644
--- a/apps/web/src/lib/ai-assistant.test.mjs
+++ b/apps/web/src/lib/ai-assistant.test.mjs
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import {
buildAiAssistantRequest,
+ buildAiRefinementInstruction,
canReplaceAiSource,
getDefaultAiAction,
getDefaultTargetLanguage,
@@ -123,6 +124,62 @@ describe("AI assistant interaction model", () => {
});
});
+ test("keeps translation refinements in the selected target language", () => {
+ expect(buildAiRefinementInstruction({
+ originalAction: "translate",
+ originalInstruction: "Translate the complete note into the selected language.",
+ refinement: "更自然",
+ targetLanguage: "en",
+ })).toBe([
+ "Revise only the supplied current result according to the follow-up request.",
+ "Continue the original processing task instead of starting a different task. Preserve the result's language, purpose, factual meaning, and useful formatting unless the follow-up explicitly requests a change.",
+ "Original processing action:\ntranslate",
+ "Original processing instruction:\nTranslate the complete note into the selected language.",
+ "Keep the entire revised result in the target language: en. Do not translate it back to the language used by the follow-up request.",
+ "Follow-up request:\n更自然",
+ ].join("\n\n"));
+ });
+
+ test("keeps every processing action and its original instruction during refinement", () => {
+ const actions = [
+ "summarize",
+ "extract-key-points",
+ "extract-todos",
+ "rewrite-proofread",
+ "improve-writing",
+ "fix-spelling-grammar",
+ "make-shorter",
+ "make-longer",
+ "simplify-language",
+ "continue-writing",
+ "custom",
+ ];
+
+ for (const originalAction of actions) {
+ const instruction = buildAiRefinementInstruction({
+ originalAction,
+ originalInstruction: `Original instruction for ${originalAction}`,
+ refinement: "再简洁一点",
+ });
+ expect(instruction).toContain(`Original processing action:\n${originalAction}`);
+ expect(instruction).toContain(`Original processing instruction:\nOriginal instruction for ${originalAction}`);
+ expect(instruction).toContain("Follow-up request:\n再简洁一点");
+ }
+ });
+
+ test("keeps the selected tone while refining tone changes", () => {
+ const instruction = buildAiRefinementInstruction({
+ originalAction: "change-tone",
+ originalInstruction: "Rewrite the content in the selected tone.",
+ refinement: "再短一点",
+ tone: "friendly",
+ });
+
+ expect(instruction).toContain("Original processing action:\nchange-tone");
+ expect(instruction).toContain("Keep the revised result in the requested tone: friendly.");
+ expect(instruction).toContain("Follow-up request:\n再短一点");
+ });
+
test("keeps extractive output additive while allowing rewritten content to replace its source", () => {
expect(canReplaceAiSource("summarize")).toBe(false);
expect(canReplaceAiSource("continue-writing")).toBe(false);
diff --git a/apps/web/src/lib/ai-assistant.ts b/apps/web/src/lib/ai-assistant.ts
index 7260bb79..eb48dc80 100644
--- a/apps/web/src/lib/ai-assistant.ts
+++ b/apps/web/src/lib/ai-assistant.ts
@@ -63,6 +63,32 @@ export const resolveAiAssistantComposerInput = ({
};
};
+export const buildAiRefinementInstruction = ({
+ originalAction,
+ originalInstruction,
+ refinement,
+ targetLanguage,
+ tone,
+}: {
+ originalAction: AiAction;
+ originalInstruction?: string;
+ refinement: string;
+ targetLanguage?: AiTargetLanguage;
+ tone?: AiTone;
+}) => [
+ "Revise only the supplied current result according to the follow-up request.",
+ "Continue the original processing task instead of starting a different task. Preserve the result's language, purpose, factual meaning, and useful formatting unless the follow-up explicitly requests a change.",
+ `Original processing action:\n${originalAction}`,
+ originalInstruction?.trim()
+ ? `Original processing instruction:\n${originalInstruction.trim()}`
+ : undefined,
+ targetLanguage
+ ? `Keep the entire revised result in the target language: ${targetLanguage}. Do not translate it back to the language used by the follow-up request.`
+ : undefined,
+ tone ? `Keep the revised result in the requested tone: ${tone}.` : undefined,
+ `Follow-up request:\n${refinement}`,
+].filter(Boolean).join("\n\n");
+
export const buildAiAssistantRequest = ({
action,
contentMarkdown,
diff --git a/tests/e2e/ai-custom-prompts.spec.ts b/tests/e2e/ai-custom-prompts.spec.ts
index 9e4c9a05..686e45e4 100644
--- a/tests/e2e/ai-custom-prompts.spec.ts
+++ b/tests/e2e/ai-custom-prompts.spec.ts
@@ -215,8 +215,23 @@ test.describe("AI custom prompts", () => {
let customRequest: Record<string, unknown> | null = null;
let translatedRequest: Record<string, unknown> | null = null;
+ let refinedRequest: Record<string, unknown> | null = null;
await page.route("**/api/v1/ai/generate", async (route) => {
const body = route.request().postDataJSON() as Record<string, unknown>;
+ if (body.action === "custom" && body.contentMarkdown === "Write a poem.") {
+ refinedRequest = body;
+ await route.fulfill({
+ status: 200,
+ contentType: "text/event-stream; charset=utf-8",
+ body: [
+ `data: ${JSON.stringify({ type: "start" })}`,
+ `data: ${JSON.stringify({ type: "text-delta", text: "Compose a poem." })}`,
+ `data: ${JSON.stringify({ type: "finish", finishReason: "stop" })}`,
+ "",
+ ].join("\n\n"),
+ });
+ return;
+ }
if (body.action === "translate") {
translatedRequest = body;
await route.fulfill({
@@ -281,6 +296,22 @@ test.describe("AI custom prompts", () => {
});
expect(translatedRequest).not.toHaveProperty("instruction");
+ const refinement = assistant.getByRole("textbox", { name: "继续调整" });
+ await refinement.fill("更自然");
+ await assistant.getByRole("button", { name: "调整", exact: true }).click();
+ await expect(result).toHaveText("Compose a poem.");
+ await expect(refinement).toHaveValue("更自然");
+ expect(refinedRequest).toMatchObject({
+ action: "custom",
+ title: "",
+ contentMarkdown: "Write a poem.",
+ targetLanguage: "en",
+ });
+ expect(refinedRequest?.instruction).toContain("Keep the entire revised result in the target language: en.");
+ expect(refinedRequest?.instruction).toContain("Original processing action:\ntranslate");
+ expect(refinedRequest?.instruction).toContain("Original processing instruction:");
+ expect(refinedRequest?.instruction).toContain("Follow-up request:\n更自然");
+
await assistant.getByRole("button", { name: "清除结果", exact: true }).click();
await assistant.getByRole("button", { name: "自定义指令", exact: true }).click();
await expect(instruction).toHaveValue("写一首诗");