Skip to content

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

feat(ai): open the assistant from selection or the whole note

tianma-if31ae9c975cb0
diff --git a/apps/ios/EdgeEver/Data/Models/Models.swift b/apps/ios/EdgeEver/Data/Models/Models.swift
index 2812426e..f85a7acb 100644
--- a/apps/ios/EdgeEver/Data/Models/Models.swift
+++ b/apps/ios/EdgeEver/Data/Models/Models.swift
@@ -231,6 +231,11 @@ struct AiAssistantLastActionPreference: Codable, Equatable, Sendable {
var tone: String?
}
+struct AiAssistantLastActionStore: Codable, Equatable, Sendable {
+ var selected: AiAssistantLastActionPreference? = nil
+ var wholeNote: AiAssistantLastActionPreference? = nil
+}
+
struct AiPromptTemplate: Codable, Equatable, Sendable, Identifiable {
var id: String
var origin: String
diff --git a/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift b/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift
index 9bb533c6..5b2991f8 100644
--- a/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift
+++ b/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift
@@ -25,7 +25,7 @@ final class PreferencesStore {
didSet { defaults.set(listDensity.rawValue, forKey: Keys.density) }
}
- var aiAssistantLastAction: AiAssistantLastActionPreference? {
+ var aiAssistantLastActionStore: AiAssistantLastActionStore {
didSet { persistAiAssistantLastAction() }
}
@@ -41,7 +41,7 @@ final class PreferencesStore {
} else {
self.listDensity = ListDensity(rawValue: densityRaw) ?? .preview
}
- self.aiAssistantLastAction = Self.decodeAiAssistantLastAction(defaults.string(forKey: Keys.aiAssistantLastAction))
+ self.aiAssistantLastActionStore = Self.decodeAiAssistantLastActionStore(defaults.string(forKey: Keys.aiAssistantLastAction))
}
var resolvedLocale: Locale {
@@ -70,19 +70,34 @@ final class PreferencesStore {
isEnglish ? en : zh
}
+ func lastAiAssistantAction(isSelection: Bool) -> AiAssistantLastActionPreference? {
+ isSelection ? aiAssistantLastActionStore.selected : aiAssistantLastActionStore.wholeNote
+ }
+
+ func setLastAiAssistantAction(_ preference: AiAssistantLastActionPreference, isSelection: Bool) {
+ if isSelection {
+ aiAssistantLastActionStore.selected = preference
+ } else {
+ aiAssistantLastActionStore.wholeNote = preference
+ }
+ }
+
private func persistAiAssistantLastAction() {
- if let value = aiAssistantLastAction,
- let data = try? JSONEncoder().encode(value),
+ if let data = try? JSONEncoder().encode(aiAssistantLastActionStore),
let raw = String(data: data, encoding: .utf8) {
defaults.set(raw, forKey: Keys.aiAssistantLastAction)
- } else {
- defaults.removeObject(forKey: Keys.aiAssistantLastAction)
}
}
- private static func decodeAiAssistantLastAction(_ raw: String?) -> AiAssistantLastActionPreference? {
- guard let raw, let data = raw.data(using: .utf8) else { return nil }
- return try? JSONDecoder().decode(AiAssistantLastActionPreference.self, from: data)
+ private static func decodeAiAssistantLastActionStore(_ raw: String?) -> AiAssistantLastActionStore {
+ guard let raw, let data = raw.data(using: .utf8) else { return AiAssistantLastActionStore() }
+ if let store = try? JSONDecoder().decode(AiAssistantLastActionStore.self, from: data) {
+ return store
+ }
+ if let legacy = try? JSONDecoder().decode(AiAssistantLastActionPreference.self, from: data) {
+ return AiAssistantLastActionStore(wholeNote: legacy)
+ }
+ return AiAssistantLastActionStore()
}
private enum Keys {
diff --git a/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift b/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift
index 880a0d9e..9ab425d7 100644
--- a/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift
+++ b/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift
@@ -529,18 +529,21 @@ struct AiAssistantSheet: View {
}
private func persistLastAction() {
- env.preferences.aiAssistantLastAction = AiAssistantLastActionPreference(
- action: action,
- promptId: selectedPromptID,
- seedKey: selectedPrompt?.seedKey,
- targetLanguage: targetLanguage.rawValue,
- tone: tone.rawValue
+ env.preferences.setLastAiAssistantAction(
+ AiAssistantLastActionPreference(
+ action: action,
+ promptId: selectedPromptID,
+ seedKey: selectedPrompt?.seedKey,
+ targetLanguage: targetLanguage.rawValue,
+ tone: tone.rawValue
+ ),
+ isSelection: isSelection
)
}
private func applyStoredOrDefaultAction(from loaded: [AiPromptTemplate], allowPromptMatch: Bool) {
- let stored = env.preferences.aiAssistantLastAction
- let fallback: AiAction = isSelection ? .improveWriting : .summarize
+ let stored = env.preferences.lastAiAssistantAction(isSelection: isSelection)
+ let fallback: AiAction = isSelection ? .improveWriting : .custom
if let stored {
if allowPromptMatch, let promptId = stored.promptId, let match = loaded.first(where: { $0.id == promptId }) {
selectedPromptID = match.id
@@ -561,6 +564,12 @@ struct AiAssistantSheet: View {
return
}
}
+ if fallback == .custom {
+ selectedPromptID = nil
+ action = .custom
+ targetLanguage = env.preferences.isEnglish ? .simplifiedChinese : .english
+ return
+ }
if allowPromptMatch, let preferred = loaded.first(where: { $0.seedKey == fallback.rawValue }) ?? loaded.first {
selectedPromptID = preferred.id
action = preferred.action
diff --git a/apps/mobile/src/components/LocalTiptapEditor.tsx b/apps/mobile/src/components/LocalTiptapEditor.tsx
index 2ebcd9ca..46a3046b 100644
--- a/apps/mobile/src/components/LocalTiptapEditor.tsx
+++ b/apps/mobile/src/components/LocalTiptapEditor.tsx
@@ -1092,7 +1092,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
if (!markdown) return false;
const resolved = resolveAiAssistantLastAction({
fallbackAction: getDefaultAiAction(!wholeNote),
- preference: readStoredAiAssistantLastActionPreference(),
+ preference: readStoredAiAssistantLastActionPreference(wholeNote ? "wholeNote" : "selected"),
prompts: aiPrompts,
});
const preferredPrompt = resolved.selectedPromptId
@@ -1797,13 +1797,16 @@ const MobileSelectionAiPanel = ({
nextTone = panel.tone,
) => {
const prompt = nextPromptId ? prompts.find((item) => item.id === nextPromptId) : null;
- writeStoredAiAssistantLastActionPreference(buildAiAssistantLastActionPreference({
- action: nextAction,
- promptId: nextPromptId,
- seedKey: prompt?.seedKey ?? null,
- targetLanguage: nextTargetLanguage,
- tone: nextTone,
- }));
+ writeStoredAiAssistantLastActionPreference(
+ panel.selection.wholeNote ? "wholeNote" : "selected",
+ buildAiAssistantLastActionPreference({
+ action: nextAction,
+ promptId: nextPromptId,
+ seedKey: prompt?.seedKey ?? null,
+ targetLanguage: nextTargetLanguage,
+ tone: nextTone,
+ }),
+ );
};
const selectPromptOrAction = (value: string) => {
diff --git a/apps/mobile/src/components/MobileAiAssistantModal.tsx b/apps/mobile/src/components/MobileAiAssistantModal.tsx
index 78e2e824..d55e26c7 100644
--- a/apps/mobile/src/components/MobileAiAssistantModal.tsx
+++ b/apps/mobile/src/components/MobileAiAssistantModal.tsx
@@ -6,6 +6,7 @@ import {
AI_TONES,
AI_WHOLE_NOTE_ACTIONS,
buildAiAssistantLastActionPreference,
+ getDefaultAiAction,
getDefaultAiTargetLanguage,
promptAllowsAppend,
promptAllowsReplace,
@@ -136,7 +137,7 @@ export const MobileAiAssistantModal = ({
setSessionReady(false);
setInitializedForOpen(false);
let cancelled = false;
- void readMobileAiAssistantLastAction().then((preference) => {
+ void readMobileAiAssistantLastAction("wholeNote").then((preference) => {
if (cancelled) return;
storedPreferenceRef.current = preference;
setSessionReady(true);
@@ -149,7 +150,7 @@ export const MobileAiAssistantModal = ({
useEffect(() => {
if (!visible || !sessionReady || initializedForOpen || promptsQuery.isLoading) return;
const resolved = resolveAiAssistantLastAction({
- fallbackAction: "summarize",
+ fallbackAction: getDefaultAiAction(false),
preference: storedPreferenceRef.current,
prompts,
});
@@ -184,7 +185,7 @@ export const MobileAiAssistantModal = ({
nextTone = tone,
) => {
const prompt = nextPromptId ? prompts.find((item) => item.id === nextPromptId) : null;
- void writeMobileAiAssistantLastAction(buildAiAssistantLastActionPreference({
+ void writeMobileAiAssistantLastAction("wholeNote", buildAiAssistantLastActionPreference({
action: nextAction,
promptId: nextPromptId,
seedKey: prompt?.seedKey ?? null,
diff --git a/apps/mobile/src/lib/preferences.ts b/apps/mobile/src/lib/preferences.ts
index 3ddb9bb6..58ef39b8 100644
--- a/apps/mobile/src/lib/preferences.ts
+++ b/apps/mobile/src/lib/preferences.ts
@@ -1,9 +1,10 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import {
AI_ASSISTANT_LAST_ACTION_STORAGE_KEY,
- parseAiAssistantLastActionPreference,
- serializeAiAssistantLastActionPreference,
+ parseAiAssistantLastActionStore,
+ serializeAiAssistantLastActionStore,
type AiAssistantLastActionPreference,
+ type AiAssistantLastActionScope,
} from "@edgeever/shared";
const MEMO_LIST_DENSITY_KEY = "edgeever.mobile.memoListDensity";
@@ -45,16 +46,26 @@ export const writeMobileThemePreference = (theme: MobileThemePreference) => Asyn
const isMobileLocalePreference = (value: unknown): value is MobileLocalePreference => value === "system" || value === "zh-CN" || value === "en-US";
-export const readMobileAiAssistantLastAction = async (): Promise<AiAssistantLastActionPreference | null> => {
+export const readMobileAiAssistantLastAction = async (
+ scope: AiAssistantLastActionScope,
+): Promise<AiAssistantLastActionPreference | null> => {
try {
- return parseAiAssistantLastActionPreference(await AsyncStorage.getItem(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY));
+ return parseAiAssistantLastActionStore(await AsyncStorage.getItem(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY))[scope] ?? null;
} catch {
return null;
}
};
-export const writeMobileAiAssistantLastAction = (preference: AiAssistantLastActionPreference) =>
- AsyncStorage.setItem(
- AI_ASSISTANT_LAST_ACTION_STORAGE_KEY,
- serializeAiAssistantLastActionPreference(preference),
- ).catch(() => undefined);
+export const writeMobileAiAssistantLastAction = (
+ scope: AiAssistantLastActionScope,
+ preference: AiAssistantLastActionPreference,
+) =>
+ AsyncStorage.getItem(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY)
+ .then((raw) => {
+ const current = parseAiAssistantLastActionStore(raw);
+ return AsyncStorage.setItem(
+ AI_ASSISTANT_LAST_ACTION_STORAGE_KEY,
+ serializeAiAssistantLastActionStore({ ...current, [scope]: preference }),
+ );
+ })
+ .catch(() => undefined);
diff --git a/apps/web/src/components/dialogs/AiAssistantDialog.tsx b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
index c7fdbe8f..f0f3d410 100644
--- a/apps/web/src/components/dialogs/AiAssistantDialog.tsx
+++ b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
@@ -44,6 +44,7 @@ import {
buildAiAssistantLastActionPreference,
buildAiAssistantRequest,
buildAiRefinementInstruction,
+ getAiAssistantLastActionScope,
getDefaultAiAction,
getDefaultTargetLanguage,
promptAllowsAppend,
@@ -71,6 +72,7 @@ const FREEFORM_VALUE = "custom";
const PROMPT_VALUE_PREFIX = "prompt:";
const AI_ASSISTANT_LAYER_SELECTOR = '[data-edgeever-ai-assistant-layer="true"]';
const AI_ASSISTANT_VIEWPORT_GAP = 12;
+const AI_ASSISTANT_SELECT_TRIGGER_CLASSNAME = "h-10 w-full min-w-0 shadow-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-500/15 focus:ring-offset-0 data-[state=open]:border-emerald-400 data-[state=open]:ring-2 data-[state=open]:ring-emerald-500/15";
const getViewportSize = () => ({
height: typeof window === "undefined" ? 768 : window.innerHeight,
@@ -116,7 +118,9 @@ export const AiAssistantDialog = ({
const { t, i18n } = useTranslation();
const queryClient = useQueryClient();
const hasSelection = Boolean(selectionMarkdown?.trim());
+ const lastActionScope = getAiAssistantLastActionScope(hasSelection);
const sourceMarkdown = hasSelection ? selectionMarkdown!.trim() : contentMarkdown;
+ const noteHasContent = Boolean(contentMarkdown.trim());
const defaultTargetLanguage = getDefaultTargetLanguage(i18n.resolvedLanguage);
const defaultAction = getDefaultAiAction(hasSelection);
const [action, setAction] = useState<AiAssistantAction>(defaultAction);
@@ -244,7 +248,7 @@ export const AiAssistantDialog = ({
}
const resolved = resolveAiAssistantLastAction({
fallbackAction: defaultAction,
- preference: readStoredAiAssistantLastActionPreference(),
+ preference: readStoredAiAssistantLastActionPreference(lastActionScope),
prompts,
});
setSelectedPromptId(resolved.selectedPromptId);
@@ -252,7 +256,7 @@ export const AiAssistantDialog = ({
setTargetLanguage(resolved.targetLanguage ?? defaultTargetLanguage);
setTone(resolved.tone ?? "professional");
setInitializedForOpen(true);
- }, [customInstruction, defaultAction, defaultTargetLanguage, initializedForOpen, open, prompts, promptsQuery.isLoading]);
+ }, [customInstruction, defaultAction, defaultTargetLanguage, initializedForOpen, lastActionScope, open, prompts, promptsQuery.isLoading]);
useEffect(() => {
if (!open) return;
@@ -295,7 +299,7 @@ export const AiAssistantDialog = ({
nextTargetLanguage?: TargetLanguage;
nextTone?: AiTone;
}) => {
- writeStoredAiAssistantLastActionPreference(buildAiAssistantLastActionPreference({
+ writeStoredAiAssistantLastActionPreference(lastActionScope, buildAiAssistantLastActionPreference({
action: nextAction,
promptId: nextPromptId,
seedKey: nextPrompt?.seedKey ?? null,
@@ -404,6 +408,7 @@ export const AiAssistantDialog = ({
});
const composerInput = resolveAiAssistantComposerInput({
composerText: currentInstruction,
+ hasSelection,
isFreeformCustom,
noteContentMarkdown: sourceMarkdown,
noteTitle: title,
@@ -532,7 +537,9 @@ export const AiAssistantDialog = ({
: null;
const isFreeformCustom = !selectedPromptId && action === "custom";
- const usesComposerAsSource = !isFreeformCustom && Boolean(customInstruction.trim());
+ const showInstructionComposer = isFreeformCustom;
+ const showSourceComposer = !isFreeformCustom && !hasSelection && !noteHasContent;
+ const usesComposerAsSource = showSourceComposer && Boolean(customInstruction.trim());
const canSaveAsPrompt = isFreeformCustom && customInstruction.trim().length > 0;
const generateDisabled = isGenerating
|| isReadingAttachments;
@@ -657,7 +664,46 @@ export const AiAssistantDialog = ({
{selectionMarkdown}
</p>
) : null}
- <div className="order-3 grid gap-2">
+ {showInstructionComposer || showSourceComposer ? (
+ <div className="grid gap-2">
+ <label className="grid gap-1.5 text-sm font-medium text-slate-700">
+ {t(showInstructionComposer
+ ? (hasSelection ? "aiAssistant.customInstructionSelected" : "aiAssistant.customInstruction")
+ : "aiAssistant.inputContent")}
+ <textarea
+ ref={instructionRef}
+ className="min-h-24 resize-y rounded-md border border-slate-200 bg-card 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) => {
+ handleComposerChange(event.target.value);
+ }}
+ onCompositionEnd={(event) => {
+ handleComposerChange(event.currentTarget.value);
+ }}
+ onKeyDown={(event) => {
+ if (
+ event.key !== "Enter"
+ || event.shiftKey
+ || event.nativeEvent.isComposing
+ || isGenerating
+ || isReadingAttachments
+ ) {
+ return;
+ }
+ event.preventDefault();
+ void generate();
+ }}
+ placeholder={t(showInstructionComposer
+ ? (hasSelection
+ ? "aiAssistant.customInstructionSelectedPlaceholder"
+ : "aiAssistant.customInstructionPlaceholder")
+ : "aiAssistant.inputContentEmptyPlaceholder")}
+ maxLength={2_000}
+ />
+ </label>
+ </div>
+ ) : null}
+ <div className="grid gap-2">
<div className="flex items-center justify-between gap-3">
<span className="text-sm font-medium text-slate-700">{t("aiAssistant.actionLabel")}</span>
{onOpenPromptLibrary ? (
@@ -676,7 +722,7 @@ export const AiAssistantDialog = ({
</div>
<div className="grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-[minmax(0,1fr)_auto]">
<Select value={selectValue} onValueChange={handleActionChange}>
- <SelectTrigger aria-label={t("aiAssistant.actionLabel")} className="h-10 w-full min-w-0">
+ <SelectTrigger aria-label={t("aiAssistant.actionLabel")} className={AI_ASSISTANT_SELECT_TRIGGER_CLASSNAME}>
<SelectValue placeholder={t("aiAssistant.actionLabel")} />
</SelectTrigger>
<SelectContent
@@ -704,8 +750,11 @@ export const AiAssistantDialog = ({
<div className="grid min-w-0 grid-cols-2 gap-2 sm:grid-cols-[8rem_7rem]">
<Button
type="button"
- variant={!selectedPromptId && action === "custom" ? "solid" : "outline"}
- className="h-10 min-w-0 w-full gap-1 whitespace-nowrap px-3 text-xs font-normal text-slate-600"
+ variant="outline"
+ className={cn(
+ "h-10 min-w-0 w-full gap-1.5 whitespace-nowrap px-3 text-sm font-medium",
+ isFreeformCustom && "border-emerald-200 bg-emerald-50 text-emerald-800 hover:bg-emerald-100 hover:text-emerald-900",
+ )}
onClick={() => handleActionChange(FREEFORM_VALUE)}
>
<PenLine className="h-3.5 w-3.5 shrink-0" />
@@ -728,7 +777,7 @@ export const AiAssistantDialog = ({
</div>
</div>
{promptNeedsTargetLanguage(effectiveParameterKind) ? (
- <div className="order-2 grid gap-1.5">
+ <div className="grid gap-1.5">
<span className="text-sm font-medium text-slate-700">{t("aiAssistant.targetLanguage")}</span>
<Select value={targetLanguage} onValueChange={(value) => {
const nextTargetLanguage = value as TargetLanguage;
@@ -741,7 +790,7 @@ export const AiAssistantDialog = ({
});
clearResult();
}}>
- <SelectTrigger aria-label={t("aiAssistant.targetLanguage")} className="h-10">
+ <SelectTrigger aria-label={t("aiAssistant.targetLanguage")} className={AI_ASSISTANT_SELECT_TRIGGER_CLASSNAME}>
<SelectValue />
</SelectTrigger>
<SelectContent
@@ -759,7 +808,7 @@ export const AiAssistantDialog = ({
</div>
) : null}
{promptNeedsTone(effectiveParameterKind) ? (
- <div className="order-2 grid gap-1.5">
+ <div className="grid gap-1.5">
<span className="text-sm font-medium text-slate-700">{t("aiAssistant.tone")}</span>
<Select value={tone} onValueChange={(value) => {
const nextTone = value as AiTone;
@@ -772,7 +821,7 @@ export const AiAssistantDialog = ({
});
clearResult();
}}>
- <SelectTrigger aria-label={t("aiAssistant.tone")} className="h-10"><SelectValue /></SelectTrigger>
+ <SelectTrigger aria-label={t("aiAssistant.tone")} className={AI_ASSISTANT_SELECT_TRIGGER_CLASSNAME}><SelectValue /></SelectTrigger>
<SelectContent
className="z-[80] max-h-[min(20rem,var(--radix-select-content-available-height))]"
collisionBoundary={panelElement}
@@ -785,38 +834,7 @@ export const AiAssistantDialog = ({
</Select>
</div>
) : null}
- <div className="order-1 grid gap-2">
- <label className="grid gap-1.5 text-sm font-medium text-slate-700">
- {t(isFreeformCustom ? "aiAssistant.customInstruction" : "aiAssistant.inputContent")}
- <textarea
- ref={instructionRef}
- className="min-h-24 resize-y rounded-md border border-slate-200 bg-card 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) => {
- handleComposerChange(event.target.value);
- }}
- onCompositionEnd={(event) => {
- handleComposerChange(event.currentTarget.value);
- }}
- onKeyDown={(event) => {
- if (
- event.key !== "Enter"
- || event.shiftKey
- || event.nativeEvent.isComposing
- || isGenerating
- || isReadingAttachments
- ) {
- return;
- }
- event.preventDefault();
- void generate();
- }}
- placeholder={t(isFreeformCustom
- ? "aiAssistant.customInstructionPlaceholder"
- : "aiAssistant.inputContentPlaceholder")}
- maxLength={2_000}
- />
- </label>
+ <div className="grid gap-2">
<div className="flex flex-wrap gap-2">
<input
ref={attachmentInputRef}
@@ -883,7 +901,7 @@ export const AiAssistantDialog = ({
{promptFeedback ? <p className="text-xs font-medium text-emerald-700">{promptFeedback}</p> : null}
{promptErrorMessage ? <p className="text-xs font-medium text-rose-600" role="alert">{promptErrorMessage}</p> : null}
</div>
- <div className="order-4 grid gap-1.5">
+ <div className="grid gap-1.5">
<div className="flex items-center justify-between gap-3">
<span className="text-sm font-medium text-slate-700">{t("aiAssistant.result")}</span>
{isGenerating ? (
@@ -912,7 +930,7 @@ export const AiAssistantDialog = ({
</div>
</div>
{output && !isGenerating ? (
- <div className="order-4 grid gap-1.5 rounded-lg border border-slate-200 bg-card p-3">
+ <div className="grid gap-1.5 rounded-lg border border-slate-200 bg-card p-3">
<span className="text-sm font-medium text-slate-700">{t("aiAssistant.refine")}</span>
<div className="flex flex-col gap-2 sm:flex-row">
<input
diff --git a/apps/web/src/lib/ai-assistant.test.mjs b/apps/web/src/lib/ai-assistant.test.mjs
index 186b1ce8..3516f3cb 100644
--- a/apps/web/src/lib/ai-assistant.test.mjs
+++ b/apps/web/src/lib/ai-assistant.test.mjs
@@ -12,7 +12,7 @@ import {
describe("AI assistant interaction model", () => {
test("chooses a useful default from the current scope and locale", () => {
expect(getDefaultAiAction(true)).toBe("improve-writing");
- expect(getDefaultAiAction(false)).toBe("summarize");
+ expect(getDefaultAiAction(false)).toBe("custom");
expect(getDefaultTargetLanguage("zh-CN")).toBe("en");
expect(getDefaultTargetLanguage("en-US")).toBe("zh-CN");
});
@@ -99,18 +99,41 @@ describe("AI assistant interaction model", () => {
});
});
- test("uses retained composer text as the source for a selected processing action", () => {
+ test("uses retained composer text as the source only when the note is empty", () => {
expect(resolveAiAssistantComposerInput({
composerText: "写一首诗",
isFreeformCustom: false,
- noteContentMarkdown: "整篇笔记不应被翻译",
- noteTitle: "现有笔记",
+ noteContentMarkdown: "",
+ noteTitle: "",
})).toEqual({
contentMarkdown: "写一首诗",
customInstruction: "",
title: "",
usesComposerAsSource: true,
});
+ expect(resolveAiAssistantComposerInput({
+ composerText: "写一首诗",
+ isFreeformCustom: false,
+ noteContentMarkdown: "整篇笔记不应被翻译",
+ noteTitle: "现有笔记",
+ })).toEqual({
+ contentMarkdown: "整篇笔记不应被翻译",
+ customInstruction: "",
+ title: "现有笔记",
+ usesComposerAsSource: false,
+ });
+ expect(resolveAiAssistantComposerInput({
+ composerText: "这段不应覆盖选区",
+ hasSelection: true,
+ isFreeformCustom: false,
+ noteContentMarkdown: "选中的句子",
+ noteTitle: "现有笔记",
+ })).toEqual({
+ contentMarkdown: "选中的句子",
+ customInstruction: "",
+ title: "现有笔记",
+ usesComposerAsSource: false,
+ });
expect(resolveAiAssistantComposerInput({
composerText: "",
isFreeformCustom: false,
diff --git a/apps/web/src/lib/ai-assistant.ts b/apps/web/src/lib/ai-assistant.ts
index 5ef38967..3b5f8aac 100644
--- a/apps/web/src/lib/ai-assistant.ts
+++ b/apps/web/src/lib/ai-assistant.ts
@@ -6,6 +6,7 @@ import {
actionNeedsTargetLanguage,
actionNeedsTone,
canReplaceAiSource,
+ getAiAssistantLastActionScope,
getDefaultAiAction,
getDefaultAiTargetLanguage,
parseDefaultAiPromptKey,
@@ -40,6 +41,7 @@ export {
actionNeedsTone,
buildAiAssistantLastActionPreference,
canReplaceAiSource,
+ getAiAssistantLastActionScope,
getDefaultAiAction,
parseDefaultAiPromptKey,
promptAllowsAppend,
@@ -53,16 +55,21 @@ export {
export const resolveAiAssistantComposerInput = ({
composerText,
+ hasSelection,
isFreeformCustom,
noteContentMarkdown,
noteTitle,
}: {
composerText: string;
+ hasSelection?: boolean;
isFreeformCustom: boolean;
noteContentMarkdown: string;
noteTitle: string;
}) => {
- const usesComposerAsSource = !isFreeformCustom && Boolean(composerText.trim());
+ const usesComposerAsSource = !isFreeformCustom
+ && !hasSelection
+ && !noteContentMarkdown.trim()
+ && Boolean(composerText.trim());
return {
contentMarkdown: usesComposerAsSource ? composerText : noteContentMarkdown,
customInstruction: isFreeformCustom ? composerText : "",
diff --git a/packages/shared/src/ai-assistant.test.mjs b/packages/shared/src/ai-assistant.test.mjs
index 955781bf..8ab91324 100644
--- a/packages/shared/src/ai-assistant.test.mjs
+++ b/packages/shared/src/ai-assistant.test.mjs
@@ -29,8 +29,8 @@ afterEach(() => {
});
describe("AI assistant last processing action", () => {
- test("keeps summarize and polish only as first-time fallbacks", () => {
- expect(getDefaultAiAction(false)).toBe("summarize");
+ test("defaults to a custom instruction without a selection, and polish with one", () => {
+ expect(getDefaultAiAction(false)).toBe("custom");
expect(getDefaultAiAction(true)).toBe("improve-writing");
});
@@ -79,12 +79,12 @@ describe("AI assistant last processing action", () => {
test("falls back to the scope default when nothing has been remembered", () => {
expect(resolveAiAssistantLastAction({
- fallbackAction: "summarize",
+ fallbackAction: "custom",
preference: null,
prompts,
})).toEqual({
- action: "summarize",
- selectedPromptId: "ws_aiprompt_summarize",
+ action: "custom",
+ selectedPromptId: null,
});
expect(resolveAiAssistantLastAction({
fallbackAction: "improve-writing",
@@ -127,10 +127,36 @@ describe("AI assistant last processing action", () => {
targetLanguage: "en",
tone: "friendly",
});
- writeStoredAiAssistantLastActionPreference(preference);
- expect(values.get(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY)).toBe(
- serializeAiAssistantLastActionPreference(preference),
- );
- expect(readStoredAiAssistantLastActionPreference()).toEqual(preference);
+ writeStoredAiAssistantLastActionPreference("wholeNote", preference);
+ expect(readStoredAiAssistantLastActionPreference("wholeNote")).toEqual(preference);
+ expect(readStoredAiAssistantLastActionPreference("selected")).toBe(null);
+
+ const selected = buildAiAssistantLastActionPreference({
+ action: "improve-writing",
+ promptId: "ws_aiprompt_improve",
+ seedKey: "improve-writing",
+ });
+ writeStoredAiAssistantLastActionPreference("selected", selected);
+ expect(readStoredAiAssistantLastActionPreference("selected")).toEqual(selected);
+ expect(readStoredAiAssistantLastActionPreference("wholeNote")).toEqual(preference);
+ });
+
+ test("keeps a legacy single preference as the whole-note memory only", () => {
+ const values = new Map();
+ Object.defineProperty(globalThis, "localStorage", {
+ configurable: true,
+ value: {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ },
+ });
+ const preference = buildAiAssistantLastActionPreference({
+ action: "translate",
+ promptId: "ws_aiprompt_translate",
+ seedKey: "translate",
+ });
+ values.set(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY, serializeAiAssistantLastActionPreference(preference));
+ expect(readStoredAiAssistantLastActionPreference("wholeNote")).toEqual(preference);
+ expect(readStoredAiAssistantLastActionPreference("selected")).toBe(null);
});
});
diff --git a/packages/shared/src/ai-assistant.ts b/packages/shared/src/ai-assistant.ts
index 57dab6de..f2b362b2 100644
--- a/packages/shared/src/ai-assistant.ts
+++ b/packages/shared/src/ai-assistant.ts
@@ -84,7 +84,7 @@ const NON_REPLACEABLE_AI_ACTIONS: readonly AiAction[] = [
];
export const getDefaultAiAction = (hasSelection: boolean): AiAction =>
- hasSelection ? "improve-writing" : "summarize";
+ hasSelection ? "improve-writing" : "custom";
export const getDefaultAiTargetLanguage = (locale: string | undefined): AiTargetLanguage =>
locale?.toLowerCase().startsWith("zh") ? "en" : "zh-CN";
@@ -93,6 +93,8 @@ export const AI_ASSISTANT_LAST_ACTION_STORAGE_KEY = "edgeever.aiAssistant.lastAc
export type AiPromptSeedAction = Exclude<AiAction, "custom">;
+export type AiAssistantLastActionScope = "selected" | "wholeNote";
+
export type AiAssistantLastActionPreference = {
action: AiAction;
promptId: string | null;
@@ -101,6 +103,14 @@ export type AiAssistantLastActionPreference = {
tone?: AiTone;
};
+export type AiAssistantLastActionStore = {
+ selected?: AiAssistantLastActionPreference;
+ wholeNote?: AiAssistantLastActionPreference;
+};
+
+export const getAiAssistantLastActionScope = (hasSelection: boolean): AiAssistantLastActionScope =>
+ hasSelection ? "selected" : "wholeNote";
+
export type AiAssistantPromptOption = {
id: string;
action: AiAction;
@@ -127,22 +137,50 @@ const getLocalStorage = (): Storage | null => {
}
};
+const parseAiAssistantLastActionPreferenceObject = (
+ value: unknown,
+): AiAssistantLastActionPreference | null => {
+ if (!value || typeof value !== "object") return null;
+ const parsed = value as Record<string, unknown>;
+ if (!isAiAction(parsed.action)) return null;
+ return {
+ action: parsed.action,
+ promptId: typeof parsed.promptId === "string" ? parsed.promptId : null,
+ seedKey: isAiPromptSeedAction(parsed.seedKey) ? parsed.seedKey : null,
+ ...(isAiTargetLanguage(parsed.targetLanguage) ? { targetLanguage: parsed.targetLanguage } : {}),
+ ...(isAiTone(parsed.tone) ? { tone: parsed.tone } : {}),
+ };
+};
+
export const parseAiAssistantLastActionPreference = (
raw: string | null | undefined,
): AiAssistantLastActionPreference | null => {
if (!raw) return null;
+ try {
+ return parseAiAssistantLastActionPreferenceObject(JSON.parse(raw));
+ } catch {
+ return null;
+ }
+};
+
+export const parseAiAssistantLastActionStore = (
+ raw: string | null | undefined,
+): AiAssistantLastActionStore => {
+ if (!raw) return {};
try {
const parsed = JSON.parse(raw) as Record<string, unknown>;
- if (!isAiAction(parsed.action)) return null;
+ const legacy = parseAiAssistantLastActionPreferenceObject(parsed);
+ if (legacy) return { wholeNote: legacy };
return {
- action: parsed.action,
- promptId: typeof parsed.promptId === "string" ? parsed.promptId : null,
- seedKey: isAiPromptSeedAction(parsed.seedKey) ? parsed.seedKey : null,
- ...(isAiTargetLanguage(parsed.targetLanguage) ? { targetLanguage: parsed.targetLanguage } : {}),
- ...(isAiTone(parsed.tone) ? { tone: parsed.tone } : {}),
+ ...(parseAiAssistantLastActionPreferenceObject(parsed.selected)
+ ? { selected: parseAiAssistantLastActionPreferenceObject(parsed.selected)! }
+ : {}),
+ ...(parseAiAssistantLastActionPreferenceObject(parsed.wholeNote)
+ ? { wholeNote: parseAiAssistantLastActionPreferenceObject(parsed.wholeNote)! }
+ : {}),
};
} catch {
- return null;
+ return {};
}
};
@@ -156,6 +194,12 @@ export const serializeAiAssistantLastActionPreference = (
...(preference.tone ? { tone: preference.tone } : {}),
});
+export const serializeAiAssistantLastActionStore = (store: AiAssistantLastActionStore) =>
+ JSON.stringify({
+ ...(store.selected ? { selected: JSON.parse(serializeAiAssistantLastActionPreference(store.selected)) } : {}),
+ ...(store.wholeNote ? { wholeNote: JSON.parse(serializeAiAssistantLastActionPreference(store.wholeNote)) } : {}),
+ });
+
export const buildAiAssistantLastActionPreference = ({
action,
promptId,
@@ -209,6 +253,9 @@ export const resolveAiAssistantLastAction = ({
}
}
+ if (fallbackAction === "custom") {
+ return { action: "custom", selectedPromptId: null };
+ }
const fallbackPrompt = prompts.find((prompt) => prompt.seedKey === fallbackAction) ?? prompts[0] ?? null;
if (fallbackPrompt) {
return { action: fallbackPrompt.action, selectedPromptId: fallbackPrompt.id };
@@ -216,16 +263,21 @@ export const resolveAiAssistantLastAction = ({
return { action: fallbackAction, selectedPromptId: null };
};
-export const readStoredAiAssistantLastActionPreference = (): AiAssistantLastActionPreference | null =>
- parseAiAssistantLastActionPreference(getLocalStorage()?.getItem(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY));
+export const readStoredAiAssistantLastActionPreference = (
+ scope: AiAssistantLastActionScope,
+): AiAssistantLastActionPreference | null =>
+ parseAiAssistantLastActionStore(getLocalStorage()?.getItem(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY))[scope] ?? null;
export const writeStoredAiAssistantLastActionPreference = (
+ scope: AiAssistantLastActionScope,
preference: AiAssistantLastActionPreference,
) => {
try {
- getLocalStorage()?.setItem(
+ const storage = getLocalStorage();
+ const current = parseAiAssistantLastActionStore(storage?.getItem(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY));
+ storage?.setItem(
AI_ASSISTANT_LAST_ACTION_STORAGE_KEY,
- serializeAiAssistantLastActionPreference(preference),
+ serializeAiAssistantLastActionStore({ ...current, [scope]: preference }),
);
} catch {
// Private mode / blocked storage — keep the in-session selection only.
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 45f89183..cff03838 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -1008,9 +1008,12 @@ export const enUS = {
},
customInstruction: "Tell AI what to do",
customInstructionPlaceholder: "For example: Rewrite this as a concise, friendly email and preserve every date.",
+ customInstructionSelected: "Tell AI what to do with this selection",
+ customInstructionSelectedPlaceholder: "For example: Make it more conversational, keep the terms, and do not change the structure.",
customInstructionRequired: "Enter an instruction for AI.",
inputContent: "Content to process",
inputContentPlaceholder: "Enter content, or leave blank to process the whole note.",
+ inputContentEmptyPlaceholder: "Type or paste the content to process.",
inputScope: "Input content",
addAttachment: "Add files",
attachments: "Attached files",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 3ede294c..0e22c6b3 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -1008,9 +1008,12 @@ export const zhCN = {
},
customInstruction: "告诉 AI 你想怎么处理",
customInstructionPlaceholder: "例如:改写成一封简洁、友好的邮件,并保留所有日期。",
+ customInstructionSelected: "告诉 AI 你想怎么处理这段",
+ customInstructionSelectedPlaceholder: "例如:改得更口语、保留术语、不要改结构。",
customInstructionRequired: "请输入你希望 AI 执行的指令。",
inputContent: "输入要处理的内容",
inputContentPlaceholder: "输入内容;留空则处理当前整篇笔记。",
+ inputContentEmptyPlaceholder: "输入或粘贴要处理的内容。",
inputScope: "输入内容",
addAttachment: "添加文件",
attachments: "已添加文件",
diff --git a/tests/e2e/ai-custom-prompts.spec.ts b/tests/e2e/ai-custom-prompts.spec.ts
index ada88dcf..809e074c 100644
--- a/tests/e2e/ai-custom-prompts.spec.ts
+++ b/tests/e2e/ai-custom-prompts.spec.ts
@@ -303,11 +303,10 @@ test.describe("AI custom prompts", () => {
await expect(assistant).toBeVisible();
await assistant.getByRole("button", { name: "生成", exact: true }).click();
const result = assistant.getByTestId("ai-assistant-result");
- await expect(result.getByRole("alert")).toHaveText("当前处理方式需要笔记内容。请先输入内容,或改用自定义指令从空白开始生成。");
+ await expect(result.getByRole("alert")).toHaveText("请输入你希望 AI 执行的指令。");
await expect(result).not.toContainText("生成结果将显示在这里。");
await expect(assistant).not.toContainText("contentMarkdown");
- await assistant.getByRole("button", { name: "自定义指令", exact: true }).click();
const instruction = assistant.getByRole("textbox", { name: "告诉 AI 你想怎么处理" });
await instruction.fill("写一首诗");
await selectAction(assistant, "翻译");
@@ -659,6 +658,7 @@ test.describe("AI custom prompts", () => {
await page.getByRole("button", { name: "打开 AI 写作助手", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "AI 笔记助手" });
+ await selectAction(dialog, "总结");
await dialog.getByRole("button", { name: "生成", exact: true }).click();
await expect(dialog.getByText("AI 插入段落", { exact: true })).toBeVisible();
const copyButton = dialog.getByRole("button", { name: "复制结果", exact: true });
@@ -752,7 +752,7 @@ test.describe("AI custom prompts", () => {
await ensureAuthenticatedPage(page);
await page.evaluate(() => window.localStorage.removeItem("edgeever.aiAssistant.lastAction"));
const dialog = await openMemoAssistant(page, memo.id, notebookName);
- await expect(dialog.getByRole("combobox", { name: "处理方式" })).toHaveText("总结");
+ await expect(dialog.getByRole("combobox", { name: "处理方式" })).toHaveText("自定义指令");
await selectAction(dialog, "翻译");
await expect(dialog.getByRole("combobox", { name: "处理方式" })).toHaveText("翻译");
await dialog.getByRole("button", { name: "关闭", exact: true }).click();
diff --git a/tests/mobile-ai-assistant.test.ts b/tests/mobile-ai-assistant.test.ts
index 4a0a4045..c1566f91 100644
--- a/tests/mobile-ai-assistant.test.ts
+++ b/tests/mobile-ai-assistant.test.ts
@@ -45,7 +45,7 @@ describe("native mobile AI note assistant", () => {
expect(androidAssistantSource).toContain("readMobileAiAssistantLastAction");
expect(androidEditorSource).toContain("readStoredAiAssistantLastActionPreference");
expect(androidEditorSource).toContain("resolveAiAssistantLastAction");
- expect(iosAssistantSource).toContain("aiAssistantLastAction");
+ expect(iosAssistantSource).toContain("lastAiAssistantAction");
expect(iosAssistantSource).toContain("applyStoredOrDefaultAction");
expect(readSource("../apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift")).toContain("edgeever.aiAssistant.lastAction");