Skip to content

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

fix(ai): keep custom generation available during init (#236)

tianma-if03a9444c92f7
diff --git a/apps/web/src/components/dialogs/AiAssistantDialog.tsx b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
index b3ef3244..3b233887 100644
--- a/apps/web/src/components/dialogs/AiAssistantDialog.tsx
+++ b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
@@ -117,6 +117,7 @@ export const AiAssistantDialog = ({
const instructionRef = useRef<HTMLTextAreaElement | null>(null);
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 assignPanelRef = useCallback((node: HTMLElement | null) => {
panelRef.current = node;
@@ -168,12 +169,15 @@ export const AiAssistantDialog = ({
setAttachmentError(null);
setIsReadingAttachments(false);
setInitializedForOpen(false);
+ customInstructionEditedRef.current = false;
lastRequestRef.current = null;
}, [defaultAction, defaultTargetLanguage, hasSelection, open]);
useEffect(() => {
if (!open || initializedForOpen || promptsQuery.isLoading) return;
- if (customInstruction.trim()) {
+ if (customInstructionEditedRef.current || customInstruction.trim()) {
+ setSelectedPromptId(null);
+ setAction("custom");
setInitializedForOpen(true);
return;
}
@@ -220,6 +224,7 @@ export const AiAssistantDialog = ({
};
const handleActionChange = (value: string) => {
+ customInstructionEditedRef.current = false;
if (value === FREEFORM_VALUE) {
setAction("custom");
setSelectedPromptId(null);
@@ -270,18 +275,27 @@ export const AiAssistantDialog = ({
}
};
- const generate = () => runGeneration(buildAiAssistantRequest({
- action: effectiveActionKey,
- contentMarkdown: sourceMarkdown,
- customInstruction,
- locale: i18n.resolvedLanguage,
- parameterKind: selectedPrompt ? effectiveParameterKind : undefined,
- promptId: selectedPrompt?.id,
- targetLanguage,
- title,
- tone,
- attachments: attachments.map(({ byteLength: _byteLength, ...attachment }) => attachment),
- }));
+ const generate = () => {
+ const currentInstruction = instructionRef.current?.value ?? customInstruction;
+ if (!selectedPrompt && effectiveActionKey === "custom" && !currentInstruction.trim()) {
+ setError(t("aiAssistant.customInstructionRequired"));
+ instructionRef.current?.focus();
+ return;
+ }
+
+ return runGeneration(buildAiAssistantRequest({
+ action: effectiveActionKey,
+ contentMarkdown: sourceMarkdown,
+ customInstruction: currentInstruction,
+ locale: i18n.resolvedLanguage,
+ parameterKind: selectedPrompt ? effectiveParameterKind : undefined,
+ promptId: selectedPrompt?.id,
+ targetLanguage,
+ title,
+ tone,
+ attachments: attachments.map(({ byteLength: _byteLength, ...attachment }) => attachment),
+ }));
+ };
const addAttachments = async (files: File[]) => {
if (!files.length) return;
@@ -366,11 +380,7 @@ export const AiAssistantDialog = ({
const isFreeformCustom = !selectedPromptId && action === "custom";
const canSaveAsPrompt = isFreeformCustom && customInstruction.trim().length > 0;
const generateDisabled = isGenerating
- || isReadingAttachments
- || (isFreeformCustom && !customInstruction.trim())
- || (!isFreeformCustom && !selectedPromptId)
- || (promptNeedsTargetLanguage(effectiveParameterKind) && !targetLanguage)
- || (promptNeedsTone(effectiveParameterKind) && !tone);
+ || isReadingAttachments;
const panelStyle = useMemo<CSSProperties>(() => {
const viewportWidth = typeof window === "undefined" ? 1024 : window.innerWidth;
@@ -538,13 +548,19 @@ export const AiAssistantDialog = ({
className="min-h-24 resize-y rounded-md border border-slate-200 bg-white px-3 py-2 text-sm font-normal text-slate-900 outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-500/15"
value={customInstruction}
onChange={(event) => {
- if (selectedPromptId) {
- setSelectedPromptId(null);
- setAction("custom");
- }
+ customInstructionEditedRef.current = true;
+ setSelectedPromptId(null);
+ setAction("custom");
setCustomInstruction(event.target.value);
clearResult();
}}
+ onCompositionEnd={(event) => {
+ customInstructionEditedRef.current = true;
+ setSelectedPromptId(null);
+ setAction("custom");
+ setCustomInstruction(event.currentTarget.value);
+ clearResult();
+ }}
placeholder={t("aiAssistant.customInstructionPlaceholder")}
maxLength={2_000}
/>
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 9834f71d..93c9d49d 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -517,6 +517,7 @@ export const enUS = {
},
customInstruction: "Tell AI what to do",
customInstructionPlaceholder: "For example: Rewrite this as a concise, friendly email and preserve every date.",
+ customInstructionRequired: "Enter an instruction for AI.",
addAttachment: "Add files",
attachments: "Attached files",
removeAttachment: "Remove {{name}}",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 9b3a0343..097114bd 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -517,6 +517,7 @@ export const zhCN = {
},
customInstruction: "告诉 AI 你想怎么处理",
customInstructionPlaceholder: "例如:改写成一封简洁、友好的邮件,并保留所有日期。",
+ customInstructionRequired: "请输入你希望 AI 执行的指令。",
addAttachment: "添加文件",
attachments: "已添加文件",
removeAttachment: "移除 {{name}}",
diff --git a/tests/e2e/ai-custom-prompts.spec.ts b/tests/e2e/ai-custom-prompts.spec.ts
index d7726313..da815cf2 100644
--- a/tests/e2e/ai-custom-prompts.spec.ts
+++ b/tests/e2e/ai-custom-prompts.spec.ts
@@ -23,8 +23,13 @@ const ensureAuthenticatedPage = async (page: Page) => {
await expect(page.getByRole("button", { name: "个人中心", exact: true })).toBeVisible({ timeout: 20_000 });
};
-const mockAiGeneration = async (page: Page, replacement: string) => {
+const mockAiGeneration = async (
+ page: Page,
+ replacement: string,
+ onRequest?: (body: Record<string, unknown>) => void,
+) => {
await page.route("**/api/v1/ai/generate", async (route) => {
+ onRequest?.(route.request().postDataJSON() as Record<string, unknown>);
await route.fulfill({
status: 200,
contentType: "text/event-stream; charset=utf-8",
@@ -316,6 +321,35 @@ test.describe("AI custom prompts", () => {
});
});
+ test("keeps a Chinese custom instruction usable while prompts initialize", async ({ page }) => {
+ const memo = await createMemo(page, `e2e-ai-ime-${Date.now()}`, "中文输入状态测试");
+ let submittedBody: Record<string, unknown> | null = null;
+ await page.route("**/api/v1/ai/prompts*", async (route) => {
+ await new Promise((resolve) => setTimeout(resolve, 800));
+ await route.continue();
+ });
+ await mockAiGeneration(page, "宋词结果", (body) => {
+ submittedBody = body;
+ });
+ await ensureAuthenticatedPage(page);
+ await page.getByRole("button", { name: new RegExp(notebookName) }).click();
+ await page.locator(`[data-memo-id="${memo.id}"]`).locator("button").first().click();
+ await page.getByRole("button", { name: "打开 AI 写作助手", exact: true }).click();
+
+ const dialog = page.getByRole("dialog", { name: "AI 笔记助手" });
+ const textarea = dialog.locator("textarea");
+ await textarea.fill("写个宋词");
+ const generateButton = dialog.getByRole("button", { name: "生成", exact: true });
+ await expect(generateButton).toBeEnabled();
+ await generateButton.click();
+
+ await expect(dialog.getByText("宋词结果", { exact: true })).toBeVisible();
+ expect(submittedBody).toMatchObject({
+ action: "custom",
+ instruction: "写个宋词",
+ });
+ });
+
test("creates prompts in settings and lists them in the assistant action menu", async ({ page, request }) => {
const promptName = `e2e-设置指令-${Date.now()}`;
const instruction = "把笔记提炼成三条要点,使用 Markdown 列表。";