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): remember the last assistant action

tianma-if42a2d2da4eb8
diff --git a/apps/ios/EdgeEver/Data/Models/Models.swift b/apps/ios/EdgeEver/Data/Models/Models.swift
index c59cf7ec..2812426e 100644
--- a/apps/ios/EdgeEver/Data/Models/Models.swift
+++ b/apps/ios/EdgeEver/Data/Models/Models.swift
@@ -223,6 +223,14 @@ enum AiPromptResultMode: String, Codable, Sendable {
case both
}
+struct AiAssistantLastActionPreference: Codable, Equatable, Sendable {
+ var action: AiAction
+ var promptId: String?
+ var seedKey: String?
+ var targetLanguage: String?
+ var tone: String?
+}
+
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 549ac4cf..9bb533c6 100644
--- a/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift
+++ b/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift
@@ -25,6 +25,10 @@ final class PreferencesStore {
didSet { defaults.set(listDensity.rawValue, forKey: Keys.density) }
}
+ var aiAssistantLastAction: AiAssistantLastActionPreference? {
+ didSet { persistAiAssistantLastAction() }
+ }
+
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
self.localeCode = defaults.string(forKey: Keys.locale) ?? "system"
@@ -37,6 +41,7 @@ final class PreferencesStore {
} else {
self.listDensity = ListDensity(rawValue: densityRaw) ?? .preview
}
+ self.aiAssistantLastAction = Self.decodeAiAssistantLastAction(defaults.string(forKey: Keys.aiAssistantLastAction))
}
var resolvedLocale: Locale {
@@ -65,10 +70,26 @@ final class PreferencesStore {
isEnglish ? en : zh
}
+ private func persistAiAssistantLastAction() {
+ if let value = aiAssistantLastAction,
+ let data = try? JSONEncoder().encode(value),
+ 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 enum Keys {
static let locale = "edgeever.ios.locale"
static let compression = "edgeever.ios.imageCompression"
static let theme = "edgeever.ios.theme"
static let density = "edgeever.ios.listDensity"
+ static let aiAssistantLastAction = "edgeever.aiAssistant.lastAction"
}
}
diff --git a/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift b/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift
index 93a2e0e5..880a0d9e 100644
--- a/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift
+++ b/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift
@@ -198,8 +198,7 @@ struct AiAssistantSheet: View {
.interactiveDismissDisabled(isApplying)
.onAppear {
guard !didSetLanguageDefault else { return }
- targetLanguage = env.preferences.isEnglish ? .simplifiedChinese : .english
- action = isSelection ? .improveWriting : .summarize
+ applyStoredOrDefaultAction(from: prompts, allowPromptMatch: false)
didSetLanguageDefault = true
}
.onDisappear { streamTask?.cancel() }
@@ -231,6 +230,7 @@ struct AiAssistantSheet: View {
action = prompt.action
output = ""
error = nil
+ persistLastAction()
} label: {
if selectedPromptID == prompt.id {
Label(prompt.name, systemImage: "checkmark")
@@ -259,6 +259,7 @@ struct AiAssistantSheet: View {
targetLanguage = item
output = ""
error = nil
+ persistLastAction()
} label: {
if targetLanguage == item {
Label(languageTitle(item), systemImage: "checkmark")
@@ -277,6 +278,7 @@ struct AiAssistantSheet: View {
tone = item
output = ""
error = nil
+ persistLastAction()
} label: {
if tone == item {
Label(toneTitle(item), systemImage: "checkmark")
@@ -523,6 +525,61 @@ struct AiAssistantSheet: View {
action = nextAction
output = ""
error = nil
+ persistLastAction()
+ }
+
+ private func persistLastAction() {
+ env.preferences.aiAssistantLastAction = AiAssistantLastActionPreference(
+ action: action,
+ promptId: selectedPromptID,
+ seedKey: selectedPrompt?.seedKey,
+ targetLanguage: targetLanguage.rawValue,
+ tone: tone.rawValue
+ )
+ }
+
+ private func applyStoredOrDefaultAction(from loaded: [AiPromptTemplate], allowPromptMatch: Bool) {
+ let stored = env.preferences.aiAssistantLastAction
+ let fallback: AiAction = isSelection ? .improveWriting : .summarize
+ if let stored {
+ if allowPromptMatch, let promptId = stored.promptId, let match = loaded.first(where: { $0.id == promptId }) {
+ selectedPromptID = match.id
+ action = match.action
+ applyStoredParameters(stored)
+ return
+ }
+ if allowPromptMatch, let seedKey = stored.seedKey, let match = loaded.first(where: { $0.seedKey == seedKey }) {
+ selectedPromptID = match.id
+ action = match.action
+ applyStoredParameters(stored)
+ return
+ }
+ if stored.action == .custom || loaded.isEmpty {
+ selectedPromptID = nil
+ action = stored.action
+ applyStoredParameters(stored)
+ return
+ }
+ }
+ if allowPromptMatch, let preferred = loaded.first(where: { $0.seedKey == fallback.rawValue }) ?? loaded.first {
+ selectedPromptID = preferred.id
+ action = preferred.action
+ return
+ }
+ selectedPromptID = nil
+ action = fallback
+ targetLanguage = env.preferences.isEnglish ? .simplifiedChinese : .english
+ }
+
+ private func applyStoredParameters(_ stored: AiAssistantLastActionPreference) {
+ if let language = stored.targetLanguage.flatMap(AssistantTargetLanguage.init(rawValue:)) {
+ targetLanguage = language
+ } else {
+ targetLanguage = env.preferences.isEnglish ? .simplifiedChinese : .english
+ }
+ if let storedTone = stored.tone.flatMap(AssistantTone.init(rawValue:)) {
+ tone = storedTone
+ }
}
@MainActor
@@ -531,11 +588,7 @@ struct AiAssistantSheet: View {
let locale = env.preferences.isEnglish ? "en-US" : "zh-CN"
let loaded = try await env.session.client.listAiPrompts(locale: locale)
prompts = loaded
- let preferredAction: AiAction = isSelection ? .improveWriting : .summarize
- if let preferred = loaded.first(where: { $0.seedKey == preferredAction.rawValue }) ?? loaded.first {
- selectedPromptID = preferred.id
- action = preferred.action
- }
+ applyStoredOrDefaultAction(from: loaded, allowPromptMatch: true)
} catch {
// Keep the built-in action list as an offline/older-server fallback.
}
diff --git a/apps/mobile/src/components/LocalTiptapEditor.tsx b/apps/mobile/src/components/LocalTiptapEditor.tsx
index 7b70a2b6..2ebcd9ca 100644
--- a/apps/mobile/src/components/LocalTiptapEditor.tsx
+++ b/apps/mobile/src/components/LocalTiptapEditor.tsx
@@ -16,10 +16,15 @@ import {
AI_TARGET_LANGUAGES,
AI_TONES,
AI_WHOLE_NOTE_ACTIONS,
+ buildAiAssistantLastActionPreference,
canReplaceAiSource,
createNativeUnsupportedContentExtensions,
docToMarkdown,
+ getDefaultAiAction,
getDefaultAiTargetLanguage,
+ readStoredAiAssistantLastActionPreference,
+ resolveAiAssistantLastAction,
+ writeStoredAiAssistantLastActionPreference,
getAiDocumentFingerprint,
getRichTextAiSelectionContext,
getRichTextAiSelectionReplacement,
@@ -1085,11 +1090,15 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
content: editor.state.doc.slice(from, to).content.toJSON(),
} as EditorDoc, props.baseUrl)).trim();
if (!markdown) return false;
- const preferredAction = wholeNote ? "summarize" : "improve-writing";
- const preferredPrompt = aiPrompts.find((prompt) => prompt.seedKey === preferredAction)
- ?? aiPrompts[0]
- ?? null;
- const initialAction = preferredPrompt?.action ?? preferredAction;
+ const resolved = resolveAiAssistantLastAction({
+ fallbackAction: getDefaultAiAction(!wholeNote),
+ preference: readStoredAiAssistantLastActionPreference(),
+ prompts: aiPrompts,
+ });
+ const preferredPrompt = resolved.selectedPromptId
+ ? aiPrompts.find((prompt) => prompt.id === resolved.selectedPromptId) ?? null
+ : null;
+ const initialAction = preferredPrompt?.action ?? resolved.action;
setAiPanel({
selection: {
from,
@@ -1103,8 +1112,8 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
promptId: preferredPrompt?.id ?? null,
parameterKind: preferredPrompt?.parameterKind ?? fallbackPromptParameterKind(initialAction),
resultMode: preferredPrompt?.resultMode ?? fallbackPromptResultMode(initialAction),
- targetLanguage: getDefaultAiTargetLanguage(props.locale),
- tone: "professional",
+ targetLanguage: resolved.targetLanguage ?? getDefaultAiTargetLanguage(props.locale),
+ tone: resolved.tone ?? "professional",
customInstruction: "",
refineInstruction: "",
output: "",
@@ -1781,11 +1790,28 @@ const MobileSelectionAiPanel = ({
const replaceDisabled = panel.generating || !panel.output || panel.resultMode === "append";
const selectedPrompt = panel.promptId ? prompts.find((prompt) => prompt.id === panel.promptId) ?? null : null;
+ const persistLastAction = (
+ nextAction: AiAction,
+ nextPromptId: string | null,
+ nextTargetLanguage = panel.targetLanguage,
+ 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,
+ }));
+ };
+
const selectPromptOrAction = (value: string) => {
if (value.startsWith(AI_PROMPT_OPTION_PREFIX)) {
const promptId = value.slice(AI_PROMPT_OPTION_PREFIX.length);
const prompt = prompts.find((item) => item.id === promptId);
if (!prompt) return;
+ persistLastAction(prompt.action, prompt.id);
update({
action: prompt.action,
promptId: prompt.id,
@@ -1797,6 +1823,7 @@ const MobileSelectionAiPanel = ({
return;
}
const action = value as AiAction;
+ persistLastAction(action, null);
update({
action,
promptId: null,
@@ -1844,8 +1871,16 @@ const MobileSelectionAiPanel = ({
const choosePickerOption = (value: string) => {
if (picker === "action") selectPromptOrAction(value);
- if (picker === "language") update({ targetLanguage: value as AiTargetLanguage, output: "", error: null });
- if (picker === "tone") update({ tone: value as AiTone, output: "", error: null });
+ if (picker === "language") {
+ const targetLanguage = value as AiTargetLanguage;
+ persistLastAction(panel.action, panel.promptId, targetLanguage);
+ update({ targetLanguage, output: "", error: null });
+ }
+ if (picker === "tone") {
+ const tone = value as AiTone;
+ persistLastAction(panel.action, panel.promptId, panel.targetLanguage, tone);
+ update({ tone, output: "", error: null });
+ }
setPicker(null);
};
diff --git a/apps/mobile/src/components/MobileAiAssistantModal.tsx b/apps/mobile/src/components/MobileAiAssistantModal.tsx
index da261cef..78e2e824 100644
--- a/apps/mobile/src/components/MobileAiAssistantModal.tsx
+++ b/apps/mobile/src/components/MobileAiAssistantModal.tsx
@@ -5,12 +5,15 @@ import {
AI_TARGET_LANGUAGES,
AI_TONES,
AI_WHOLE_NOTE_ACTIONS,
+ buildAiAssistantLastActionPreference,
getDefaultAiTargetLanguage,
promptAllowsAppend,
promptAllowsReplace,
promptNeedsTargetLanguage,
promptNeedsTone,
+ resolveAiAssistantLastAction,
type AiAction,
+ type AiAssistantLastActionPreference,
type AiTargetLanguage,
type AiTone,
type MemoDetail,
@@ -22,6 +25,7 @@ import { Check, ChevronDown, Copy, RefreshCw, Sparkles, Square, X } from "./icon
import { Alert, Pressable, Text, TextInput } from "./LocalizedText";
import { useMobileLocale } from "../lib/mobile-locale";
import { useMobileTheme } from "../lib/mobile-theme";
+import { readMobileAiAssistantLastAction, writeMobileAiAssistantLastAction } from "../lib/preferences";
import { useSession } from "../lib/session";
type AssistantAction = AiAction;
@@ -61,6 +65,9 @@ export const MobileAiAssistantModal = ({
const [applying, setApplying] = useState(false);
const [picker, setPicker] = useState<"action" | "language" | "tone" | null>(null);
const controllerRef = useRef<AbortController | null>(null);
+ const storedPreferenceRef = useRef<AiAssistantLastActionPreference | null>(null);
+ const [sessionReady, setSessionReady] = useState(false);
+ const [initializedForOpen, setInitializedForOpen] = useState(false);
const promptsQuery = useQuery({
queryKey: ["ai-prompts", resolvedLocale],
queryFn: async () => (await client!.listAiPrompts(resolvedLocale)).prompts,
@@ -111,34 +118,47 @@ export const MobileAiAssistantModal = ({
useEffect(() => () => controllerRef.current?.abort(), []);
useEffect(() => {
- if (visible) {
- controllerRef.current?.abort();
- setAction("summarize");
- setSelectedPromptId(null);
- setTargetLanguage(getDefaultAiTargetLanguage(resolvedLocale));
- setTone("professional");
- setCustomInstruction("");
- setRefineInstruction("");
- setOutput("");
- setError(null);
- setGenerating(false);
- setApplying(false);
- setPicker(null);
- } else {
+ if (!visible) {
controllerRef.current?.abort();
setPicker(null);
+ setSessionReady(false);
+ setInitializedForOpen(false);
+ return;
}
- }, [memo.id, resolvedLocale, visible]);
- useEffect(() => {
- setTargetLanguage(getDefaultAiTargetLanguage(resolvedLocale));
- }, [resolvedLocale]);
+ controllerRef.current?.abort();
+ setCustomInstruction("");
+ setRefineInstruction("");
+ setOutput("");
+ setError(null);
+ setGenerating(false);
+ setApplying(false);
+ setPicker(null);
+ setSessionReady(false);
+ setInitializedForOpen(false);
+ let cancelled = false;
+ void readMobileAiAssistantLastAction().then((preference) => {
+ if (cancelled) return;
+ storedPreferenceRef.current = preference;
+ setSessionReady(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [memo.id, visible]);
useEffect(() => {
- if (!visible || selectedPromptId || prompts.length === 0) return;
- const preferred = prompts.find((prompt) => prompt.seedKey === "summarize") ?? prompts[0];
- setSelectedPromptId(preferred.id);
- setAction(preferred.action);
- }, [prompts, selectedPromptId, visible]);
+ if (!visible || !sessionReady || initializedForOpen || promptsQuery.isLoading) return;
+ const resolved = resolveAiAssistantLastAction({
+ fallbackAction: "summarize",
+ preference: storedPreferenceRef.current,
+ prompts,
+ });
+ setSelectedPromptId(resolved.selectedPromptId);
+ setAction(resolved.action);
+ setTargetLanguage(resolved.targetLanguage ?? getDefaultAiTargetLanguage(resolvedLocale));
+ setTone(resolved.tone ?? "professional");
+ setInitializedForOpen(true);
+ }, [initializedForOpen, prompts, promptsQuery.isLoading, resolvedLocale, sessionReady, visible]);
const buildRequest = (source: string, refinement?: string) => {
const base = {
@@ -157,8 +177,25 @@ export const MobileAiAssistantModal = ({
};
};
+ const persistLastAction = (
+ nextAction: AssistantAction,
+ nextPromptId: string | null,
+ nextLanguage = targetLanguage,
+ nextTone = tone,
+ ) => {
+ const prompt = nextPromptId ? prompts.find((item) => item.id === nextPromptId) : null;
+ void writeMobileAiAssistantLastAction(buildAiAssistantLastActionPreference({
+ action: nextAction,
+ promptId: nextPromptId,
+ seedKey: prompt?.seedKey ?? null,
+ targetLanguage: nextLanguage,
+ tone: nextTone,
+ }));
+ };
+
const generate = async (source = memo.contentMarkdown, refinement?: string) => {
if (!client || (!selectedPrompt && action === "custom" && !customInstruction.trim() && !refinement?.trim())) return;
+ if (!refinement?.trim()) persistLastAction(action, selectedPromptId);
controllerRef.current?.abort();
const controller = new AbortController();
controllerRef.current = controller;
@@ -248,14 +285,21 @@ export const MobileAiAssistantModal = ({
controllerRef.current?.abort();
const promptId = value.startsWith(PROMPT_PREFIX) ? value.slice(PROMPT_PREFIX.length) : null;
const prompt = promptId ? prompts.find((item) => item.id === promptId) : null;
- setSelectedPromptId(prompt?.id ?? null);
- setAction(prompt?.action ?? (value as AssistantAction));
+ const nextAction = prompt?.action ?? (value as AssistantAction);
+ const nextPromptId = prompt?.id ?? null;
+ setSelectedPromptId(nextPromptId);
+ setAction(nextAction);
+ persistLastAction(nextAction, nextPromptId);
setOutput("");
setError(null);
} else if (picker === "language") {
- setTargetLanguage(value as TargetLanguage);
+ const nextLanguage = value as TargetLanguage;
+ setTargetLanguage(nextLanguage);
+ persistLastAction(action, selectedPromptId, nextLanguage);
} else if (picker === "tone") {
- setTone(value as Tone);
+ const nextTone = value as Tone;
+ setTone(nextTone);
+ persistLastAction(action, selectedPromptId, targetLanguage, nextTone);
}
setPicker(null);
};
diff --git a/apps/mobile/src/lib/preferences.ts b/apps/mobile/src/lib/preferences.ts
index d25ebc8f..3ddb9bb6 100644
--- a/apps/mobile/src/lib/preferences.ts
+++ b/apps/mobile/src/lib/preferences.ts
@@ -1,4 +1,10 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
+import {
+ AI_ASSISTANT_LAST_ACTION_STORAGE_KEY,
+ parseAiAssistantLastActionPreference,
+ serializeAiAssistantLastActionPreference,
+ type AiAssistantLastActionPreference,
+} from "@edgeever/shared";
const MEMO_LIST_DENSITY_KEY = "edgeever.mobile.memoListDensity";
const IMAGE_COMPRESSION_KEY = "edgeever.mobile.imageCompressionEnabled";
@@ -38,3 +44,17 @@ export const readMobileThemePreference = async (): Promise<MobileThemePreference
export const writeMobileThemePreference = (theme: MobileThemePreference) => AsyncStorage.setItem(THEME_PREFERENCE_KEY, theme);
const isMobileLocalePreference = (value: unknown): value is MobileLocalePreference => value === "system" || value === "zh-CN" || value === "en-US";
+
+export const readMobileAiAssistantLastAction = async (): Promise<AiAssistantLastActionPreference | null> => {
+ try {
+ return parseAiAssistantLastActionPreference(await AsyncStorage.getItem(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY));
+ } catch {
+ return null;
+ }
+};
+
+export const writeMobileAiAssistantLastAction = (preference: AiAssistantLastActionPreference) =>
+ AsyncStorage.setItem(
+ AI_ASSISTANT_LAST_ACTION_STORAGE_KEY,
+ serializeAiAssistantLastActionPreference(preference),
+ ).catch(() => undefined);
diff --git a/apps/web/src/components/dialogs/AiAssistantDialog.tsx b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
index 3e84d0c3..c7fdbe8f 100644
--- a/apps/web/src/components/dialogs/AiAssistantDialog.tsx
+++ b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
@@ -41,6 +41,7 @@ import {
} from "@/lib/ai-attachments";
import {
aiTones,
+ buildAiAssistantLastActionPreference,
buildAiAssistantRequest,
buildAiRefinementInstruction,
getDefaultAiAction,
@@ -49,8 +50,11 @@ import {
promptAllowsReplace,
promptNeedsTargetLanguage,
promptNeedsTone,
+ readStoredAiAssistantLastActionPreference,
resolveAiAssistantComposerInput,
+ resolveAiAssistantLastAction,
targetLanguages,
+ writeStoredAiAssistantLastActionPreference,
type AiAssistantAction,
type AiTone,
type TargetLanguage,
@@ -187,10 +191,6 @@ export const AiAssistantDialog = ({
dragStateRef.current = null;
return;
}
- setAction(defaultAction);
- setSelectedPromptId(null);
- setTargetLanguage(defaultTargetLanguage);
- setTone("professional");
setCustomInstruction("");
setRefinement("");
setOutput("");
@@ -242,18 +242,17 @@ export const AiAssistantDialog = ({
setInitializedForOpen(true);
return;
}
- const preferred = prompts.find((prompt) => prompt.seedKey === defaultAction)
- ?? prompts[0]
- ?? null;
- if (preferred) {
- setSelectedPromptId(preferred.id);
- setAction(preferred.action);
- } else {
- setSelectedPromptId(null);
- setAction("custom");
- }
+ const resolved = resolveAiAssistantLastAction({
+ fallbackAction: defaultAction,
+ preference: readStoredAiAssistantLastActionPreference(),
+ prompts,
+ });
+ setSelectedPromptId(resolved.selectedPromptId);
+ setAction(resolved.action);
+ setTargetLanguage(resolved.targetLanguage ?? defaultTargetLanguage);
+ setTone(resolved.tone ?? "professional");
setInitializedForOpen(true);
- }, [customInstruction, defaultAction, initializedForOpen, open, prompts, promptsQuery.isLoading]);
+ }, [customInstruction, defaultAction, defaultTargetLanguage, initializedForOpen, open, prompts, promptsQuery.isLoading]);
useEffect(() => {
if (!open) return;
@@ -283,11 +282,34 @@ export const AiAssistantDialog = ({
setPromptFeedback(null);
};
+ const persistLastAction = ({
+ nextAction,
+ nextPrompt,
+ nextPromptId,
+ nextTargetLanguage,
+ nextTone,
+ }: {
+ nextAction: AiAssistantAction;
+ nextPrompt?: { seedKey: typeof prompts[number]["seedKey"] } | null;
+ nextPromptId: string | null;
+ nextTargetLanguage?: TargetLanguage;
+ nextTone?: AiTone;
+ }) => {
+ writeStoredAiAssistantLastActionPreference(buildAiAssistantLastActionPreference({
+ action: nextAction,
+ promptId: nextPromptId,
+ seedKey: nextPrompt?.seedKey ?? null,
+ targetLanguage: nextTargetLanguage ?? targetLanguage,
+ tone: nextTone ?? tone,
+ }));
+ };
+
const handleActionChange = (value: string) => {
customInstructionEditedRef.current = false;
if (value === FREEFORM_VALUE) {
setAction("custom");
setSelectedPromptId(null);
+ persistLastAction({ nextAction: "custom", nextPrompt: null, nextPromptId: null });
clearResult();
return;
}
@@ -297,6 +319,11 @@ export const AiAssistantDialog = ({
const prompt = prompts.find((item) => item.id === promptId);
setSelectedPromptId(promptId);
setAction(prompt?.action ?? "custom");
+ persistLastAction({
+ nextAction: prompt?.action ?? "custom",
+ nextPrompt: prompt ?? null,
+ nextPromptId: promptId,
+ });
clearResult();
};
@@ -370,6 +397,11 @@ export const AiAssistantDialog = ({
return;
}
+ persistLastAction({
+ nextAction: effectiveActionKey,
+ nextPrompt: selectedPrompt,
+ nextPromptId: selectedPromptId,
+ });
const composerInput = resolveAiAssistantComposerInput({
composerText: currentInstruction,
isFreeformCustom,
@@ -479,6 +511,11 @@ export const AiAssistantDialog = ({
);
setSelectedPromptId(prompt.id);
setAction(prompt.action);
+ persistLastAction({
+ nextAction: prompt.action,
+ nextPrompt: prompt,
+ nextPromptId: prompt.id,
+ });
customInstructionEditedRef.current = false;
setSaveDialogOpen(false);
setSaveName("");
@@ -694,7 +731,14 @@ export const AiAssistantDialog = ({
<div className="order-2 grid gap-1.5">
<span className="text-sm font-medium text-slate-700">{t("aiAssistant.targetLanguage")}</span>
<Select value={targetLanguage} onValueChange={(value) => {
- setTargetLanguage(value as TargetLanguage);
+ const nextTargetLanguage = value as TargetLanguage;
+ setTargetLanguage(nextTargetLanguage);
+ persistLastAction({
+ nextAction: action,
+ nextPrompt: selectedPrompt,
+ nextPromptId: selectedPromptId,
+ nextTargetLanguage,
+ });
clearResult();
}}>
<SelectTrigger aria-label={t("aiAssistant.targetLanguage")} className="h-10">
@@ -718,7 +762,14 @@ export const AiAssistantDialog = ({
<div className="order-2 grid gap-1.5">
<span className="text-sm font-medium text-slate-700">{t("aiAssistant.tone")}</span>
<Select value={tone} onValueChange={(value) => {
- setTone(value as AiTone);
+ const nextTone = value as AiTone;
+ setTone(nextTone);
+ persistLastAction({
+ nextAction: action,
+ nextPrompt: selectedPrompt,
+ nextPromptId: selectedPromptId,
+ nextTone,
+ });
clearResult();
}}>
<SelectTrigger aria-label={t("aiAssistant.tone")} className="h-10"><SelectValue /></SelectTrigger>
diff --git a/apps/web/src/lib/ai-assistant.ts b/apps/web/src/lib/ai-assistant.ts
index eb48dc80..5ef38967 100644
--- a/apps/web/src/lib/ai-assistant.ts
+++ b/apps/web/src/lib/ai-assistant.ts
@@ -9,6 +9,10 @@ import {
getDefaultAiAction,
getDefaultAiTargetLanguage,
parseDefaultAiPromptKey,
+ buildAiAssistantLastActionPreference,
+ readStoredAiAssistantLastActionPreference,
+ resolveAiAssistantLastAction,
+ writeStoredAiAssistantLastActionPreference,
promptAllowsAppend,
promptAllowsReplace,
promptNeedsTargetLanguage,
@@ -34,6 +38,7 @@ export const getDefaultTargetLanguage = getDefaultAiTargetLanguage;
export {
actionNeedsTargetLanguage,
actionNeedsTone,
+ buildAiAssistantLastActionPreference,
canReplaceAiSource,
getDefaultAiAction,
parseDefaultAiPromptKey,
@@ -41,6 +46,9 @@ export {
promptAllowsReplace,
promptNeedsTargetLanguage,
promptNeedsTone,
+ readStoredAiAssistantLastActionPreference,
+ resolveAiAssistantLastAction,
+ writeStoredAiAssistantLastActionPreference,
};
export const resolveAiAssistantComposerInput = ({
diff --git a/packages/shared/src/ai-assistant.test.mjs b/packages/shared/src/ai-assistant.test.mjs
new file mode 100644
index 00000000..955781bf
--- /dev/null
+++ b/packages/shared/src/ai-assistant.test.mjs
@@ -0,0 +1,136 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ AI_ASSISTANT_LAST_ACTION_STORAGE_KEY,
+ buildAiAssistantLastActionPreference,
+ getDefaultAiAction,
+ parseAiAssistantLastActionPreference,
+ readStoredAiAssistantLastActionPreference,
+ resolveAiAssistantLastAction,
+ serializeAiAssistantLastActionPreference,
+ writeStoredAiAssistantLastActionPreference,
+} from "./ai-assistant.ts";
+
+const prompts = [
+ { id: "ws_aiprompt_summarize", action: "summarize", seedKey: "summarize" },
+ { id: "ws_aiprompt_translate", action: "translate", seedKey: "translate" },
+ { id: "ws_custom_weekly", action: "custom", seedKey: null },
+];
+
+const originalWindow = globalThis.window;
+const originalLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
+
+afterEach(() => {
+ globalThis.window = originalWindow;
+ if (originalLocalStorage) {
+ Object.defineProperty(globalThis, "localStorage", originalLocalStorage);
+ } else {
+ delete globalThis.localStorage;
+ }
+});
+
+describe("AI assistant last processing action", () => {
+ test("keeps summarize and polish only as first-time fallbacks", () => {
+ expect(getDefaultAiAction(false)).toBe("summarize");
+ expect(getDefaultAiAction(true)).toBe("improve-writing");
+ });
+
+ test("restores a remembered prompt by id, then seed, then custom", () => {
+ expect(resolveAiAssistantLastAction({
+ fallbackAction: "summarize",
+ preference: {
+ action: "custom",
+ promptId: "ws_custom_weekly",
+ seedKey: null,
+ },
+ prompts,
+ })).toEqual({
+ action: "custom",
+ selectedPromptId: "ws_custom_weekly",
+ });
+
+ expect(resolveAiAssistantLastAction({
+ fallbackAction: "summarize",
+ preference: {
+ action: "translate",
+ promptId: "deleted-prompt",
+ seedKey: "translate",
+ targetLanguage: "ja",
+ },
+ prompts,
+ })).toEqual({
+ action: "translate",
+ selectedPromptId: "ws_aiprompt_translate",
+ targetLanguage: "ja",
+ });
+
+ expect(resolveAiAssistantLastAction({
+ fallbackAction: "summarize",
+ preference: {
+ action: "custom",
+ promptId: "deleted-custom",
+ seedKey: null,
+ },
+ prompts,
+ })).toEqual({
+ action: "custom",
+ selectedPromptId: null,
+ });
+ });
+
+ test("falls back to the scope default when nothing has been remembered", () => {
+ expect(resolveAiAssistantLastAction({
+ fallbackAction: "summarize",
+ preference: null,
+ prompts,
+ })).toEqual({
+ action: "summarize",
+ selectedPromptId: "ws_aiprompt_summarize",
+ });
+ expect(resolveAiAssistantLastAction({
+ fallbackAction: "improve-writing",
+ preference: null,
+ prompts: [
+ { id: "ws_aiprompt_summarize", action: "summarize", seedKey: "summarize" },
+ { id: "ws_aiprompt_improve", action: "improve-writing", seedKey: "improve-writing" },
+ ],
+ })).toEqual({
+ action: "improve-writing",
+ selectedPromptId: "ws_aiprompt_improve",
+ });
+ });
+
+ test("ignores malformed stored preferences", () => {
+ expect(parseAiAssistantLastActionPreference(null)).toBe(null);
+ expect(parseAiAssistantLastActionPreference("{")).toBe(null);
+ expect(parseAiAssistantLastActionPreference(JSON.stringify({ promptId: "x" }))).toBe(null);
+ expect(parseAiAssistantLastActionPreference(JSON.stringify({
+ action: "not-an-action",
+ promptId: "x",
+ seedKey: "summarize",
+ }))).toBe(null);
+ });
+
+ test("round-trips a preference through local storage", () => {
+ 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",
+ targetLanguage: "en",
+ tone: "friendly",
+ });
+ writeStoredAiAssistantLastActionPreference(preference);
+ expect(values.get(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY)).toBe(
+ serializeAiAssistantLastActionPreference(preference),
+ );
+ expect(readStoredAiAssistantLastActionPreference()).toEqual(preference);
+ });
+});
diff --git a/packages/shared/src/ai-assistant.ts b/packages/shared/src/ai-assistant.ts
index 83e0160d..57dab6de 100644
--- a/packages/shared/src/ai-assistant.ts
+++ b/packages/shared/src/ai-assistant.ts
@@ -89,6 +89,149 @@ export const getDefaultAiAction = (hasSelection: boolean): AiAction =>
export const getDefaultAiTargetLanguage = (locale: string | undefined): AiTargetLanguage =>
locale?.toLowerCase().startsWith("zh") ? "en" : "zh-CN";
+export const AI_ASSISTANT_LAST_ACTION_STORAGE_KEY = "edgeever.aiAssistant.lastAction";
+
+export type AiPromptSeedAction = Exclude<AiAction, "custom">;
+
+export type AiAssistantLastActionPreference = {
+ action: AiAction;
+ promptId: string | null;
+ seedKey: AiPromptSeedAction | null;
+ targetLanguage?: AiTargetLanguage;
+ tone?: AiTone;
+};
+
+export type AiAssistantPromptOption = {
+ id: string;
+ action: AiAction;
+ seedKey?: AiPromptSeedAction | null;
+};
+
+const isAiAction = (value: unknown): value is AiAction =>
+ typeof value === "string" && (AI_ACTIONS as readonly string[]).includes(value);
+
+const isAiPromptSeedAction = (value: unknown): value is AiPromptSeedAction =>
+ isAiAction(value) && value !== "custom";
+
+const isAiTargetLanguage = (value: unknown): value is AiTargetLanguage =>
+ typeof value === "string" && (AI_TARGET_LANGUAGES as readonly string[]).includes(value);
+
+const isAiTone = (value: unknown): value is AiTone =>
+ typeof value === "string" && (AI_TONES as readonly string[]).includes(value);
+
+const getLocalStorage = (): Storage | null => {
+ try {
+ return (globalThis as { localStorage?: Storage }).localStorage ?? null;
+ } catch {
+ return null;
+ }
+};
+
+export const parseAiAssistantLastActionPreference = (
+ raw: string | null | undefined,
+): AiAssistantLastActionPreference | null => {
+ if (!raw) return null;
+ try {
+ const parsed = JSON.parse(raw) 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 } : {}),
+ };
+ } catch {
+ return null;
+ }
+};
+
+export const serializeAiAssistantLastActionPreference = (
+ preference: AiAssistantLastActionPreference,
+) => JSON.stringify({
+ action: preference.action,
+ promptId: preference.promptId,
+ seedKey: preference.seedKey,
+ ...(preference.targetLanguage ? { targetLanguage: preference.targetLanguage } : {}),
+ ...(preference.tone ? { tone: preference.tone } : {}),
+});
+
+export const buildAiAssistantLastActionPreference = ({
+ action,
+ promptId,
+ seedKey,
+ targetLanguage,
+ tone,
+}: {
+ action: AiAction;
+ promptId?: string | null;
+ seedKey?: AiPromptSeedAction | null;
+ targetLanguage?: AiTargetLanguage;
+ tone?: AiTone;
+}): AiAssistantLastActionPreference => ({
+ action,
+ promptId: promptId ?? null,
+ seedKey: seedKey ?? null,
+ ...(targetLanguage ? { targetLanguage } : {}),
+ ...(tone ? { tone } : {}),
+});
+
+export const resolveAiAssistantLastAction = ({
+ fallbackAction,
+ preference,
+ prompts,
+}: {
+ fallbackAction: AiAction;
+ preference: AiAssistantLastActionPreference | null;
+ prompts: readonly AiAssistantPromptOption[];
+}): {
+ action: AiAction;
+ selectedPromptId: string | null;
+ targetLanguage?: AiTargetLanguage;
+ tone?: AiTone;
+} => {
+ const extras = {
+ ...(preference?.targetLanguage ? { targetLanguage: preference.targetLanguage } : {}),
+ ...(preference?.tone ? { tone: preference.tone } : {}),
+ };
+
+ if (preference) {
+ if (preference.promptId) {
+ const byId = prompts.find((prompt) => prompt.id === preference.promptId);
+ if (byId) return { action: byId.action, selectedPromptId: byId.id, ...extras };
+ }
+ if (preference.seedKey) {
+ const bySeed = prompts.find((prompt) => prompt.seedKey === preference.seedKey);
+ if (bySeed) return { action: bySeed.action, selectedPromptId: bySeed.id, ...extras };
+ }
+ if (preference.action === "custom" || prompts.length === 0) {
+ return { action: preference.action, selectedPromptId: null, ...extras };
+ }
+ }
+
+ const fallbackPrompt = prompts.find((prompt) => prompt.seedKey === fallbackAction) ?? prompts[0] ?? null;
+ if (fallbackPrompt) {
+ return { action: fallbackPrompt.action, selectedPromptId: fallbackPrompt.id };
+ }
+ return { action: fallbackAction, selectedPromptId: null };
+};
+
+export const readStoredAiAssistantLastActionPreference = (): AiAssistantLastActionPreference | null =>
+ parseAiAssistantLastActionPreference(getLocalStorage()?.getItem(AI_ASSISTANT_LAST_ACTION_STORAGE_KEY));
+
+export const writeStoredAiAssistantLastActionPreference = (
+ preference: AiAssistantLastActionPreference,
+) => {
+ try {
+ getLocalStorage()?.setItem(
+ AI_ASSISTANT_LAST_ACTION_STORAGE_KEY,
+ serializeAiAssistantLastActionPreference(preference),
+ );
+ } catch {
+ // Private mode / blocked storage — keep the in-session selection only.
+ }
+};
+
export const canReplaceAiSource = (action: AiAction) => !NON_REPLACEABLE_AI_ACTIONS.includes(action);
/** Actions that need an extra picker (language / tone) in the assistant UI. */
diff --git a/tests/e2e/ai-custom-prompts.spec.ts b/tests/e2e/ai-custom-prompts.spec.ts
index a3fad130..ada88dcf 100644
--- a/tests/e2e/ai-custom-prompts.spec.ts
+++ b/tests/e2e/ai-custom-prompts.spec.ts
@@ -746,4 +746,20 @@ test.describe("AI custom prompts", () => {
await expect(dialog).toBeHidden();
await expect(page.locator(".ProseMirror[contenteditable='true']")).toContainText("进展顺利");
});
+
+ test("remembers the last processing action when the assistant is reopened", async ({ page }) => {
+ const memo = await createMemo(page, `e2e-ai-last-action-${Date.now()}`, "记住上次处理方式。");
+ 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 selectAction(dialog, "翻译");
+ await expect(dialog.getByRole("combobox", { name: "处理方式" })).toHaveText("翻译");
+ await dialog.getByRole("button", { name: "关闭", exact: true }).click();
+ await expect(dialog).toBeHidden();
+
+ await page.getByRole("button", { name: "打开 AI 写作助手", exact: true }).click();
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByRole("combobox", { name: "处理方式" })).toHaveText("翻译");
+ });
});
diff --git a/tests/mobile-ai-assistant.test.ts b/tests/mobile-ai-assistant.test.ts
index 2fb3f8f1..4a0a4045 100644
--- a/tests/mobile-ai-assistant.test.ts
+++ b/tests/mobile-ai-assistant.test.ts
@@ -41,6 +41,14 @@ describe("native mobile AI note assistant", () => {
});
test("streams AI output from the shared workspace configuration on both clients", () => {
+ expect(androidAssistantSource).toContain("resolveAiAssistantLastAction");
+ expect(androidAssistantSource).toContain("readMobileAiAssistantLastAction");
+ expect(androidEditorSource).toContain("readStoredAiAssistantLastActionPreference");
+ expect(androidEditorSource).toContain("resolveAiAssistantLastAction");
+ expect(iosAssistantSource).toContain("aiAssistantLastAction");
+ expect(iosAssistantSource).toContain("applyStoredOrDefaultAction");
+ expect(readSource("../apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift")).toContain("edgeever.aiAssistant.lastAction");
+
expect(androidAssistantSource).toContain("client!.listAiPrompts(resolvedLocale)");
expect(androidAssistantSource).toContain("client.streamAiGeneration(");
expect(androidAssistantSource).toContain("promptId: selectedPrompt.id");