Skip to content

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

feat: add native mobile AI note assistant

tianma-if3661cc3367d8
diff --git a/apps/ios/EdgeEver.xcodeproj/project.pbxproj b/apps/ios/EdgeEver.xcodeproj/project.pbxproj
index 37f02957..6df728fa 100644
--- a/apps/ios/EdgeEver.xcodeproj/project.pbxproj
+++ b/apps/ios/EdgeEver.xcodeproj/project.pbxproj
@@ -8,6 +8,7 @@
/* Begin PBXBuildFile section */
039594C5BEE4844FBB131C7F /* APIClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6F510BF90B418266F363EBD /* APIClient.swift */; };
+ B2B2B2B2B2B2B2B2B2B2B2B2 /* AiAssistantSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1A1A1A1A1A1A1A1A1A1A1A1 /* AiAssistantSheet.swift */; };
0614453E8E9EC13B212B5A2F /* NotebookPickerSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3328D871910187ED827B6CE /* NotebookPickerSheet.swift */; };
06D2661CAB0ADED27F322649 /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = D87A8CED8498AE654EF8CD1F /* Localizable.xcstrings */; };
08A3D4F0E80ACE44E36AD87D /* MemoCreateCommit.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBC0AD00435CCEFD7934201C /* MemoCreateCommit.swift */; };
@@ -119,6 +120,7 @@
/* Begin PBXFileReference section */
033565CE2E96EC2D23105188 /* ListActionsSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListActionsSheet.swift; sourceTree = "<group>"; };
+ A1A1A1A1A1A1A1A1A1A1A1A1 /* AiAssistantSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AiAssistantSheet.swift; sourceTree = "<group>"; };
0531FC6AA81DAF0A55B42362 /* AppDatabase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
12236E3A2F318CDEB17B80CB /* SyncProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncProtocol.swift; sourceTree = "<group>"; };
12DCA98C14CC6F28C22C41A1 /* TipTapWebView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TipTapWebView.swift; sourceTree = "<group>"; };
@@ -402,6 +404,7 @@
AE31B21B9B3513CC73436E46 /* Workspace */ = {
isa = PBXGroup;
children = (
+ A1A1A1A1A1A1A1A1A1A1A1A1 /* AiAssistantSheet.swift */,
BA6E24432E3A724DB34CFEB5 /* AccountPasswordPanel.swift */,
73FA569C71080B6F9989AA03 /* ApiTokensView.swift */,
776B0012B526A65B99921B4B /* ConflictResolutionView.swift */,
@@ -650,6 +653,7 @@
buildActionMask = 2147483647;
files = (
039594C5BEE4844FBB131C7F /* APIClient.swift in Sources */,
+ B2B2B2B2B2B2B2B2B2B2B2B2 /* AiAssistantSheet.swift in Sources */,
564B7A4D6CD3C8140286F881 /* AccountPasswordPanel.swift in Sources */,
12F0F0D1E937AA88C33222FF /* ApiTokensView.swift in Sources */,
35DF4BD1617191AB0B95CC4A /* AppDatabase.swift in Sources */,
diff --git a/apps/ios/EdgeEver/Data/Models/Models.swift b/apps/ios/EdgeEver/Data/Models/Models.swift
index 3ddac2e9..6a49cd64 100644
--- a/apps/ios/EdgeEver/Data/Models/Models.swift
+++ b/apps/ios/EdgeEver/Data/Models/Models.swift
@@ -125,6 +125,35 @@ struct MemoEditSession: Codable, Equatable, Sendable {
var expiresAt: String
}
+// MARK: - AI note processing
+
+enum AiAction: String, Codable, CaseIterable, Sendable, Identifiable {
+ case summarize
+ case extractKeyPoints = "extract-key-points"
+ case extractTodos = "extract-todos"
+ case rewriteProofread = "rewrite-proofread"
+ case translate
+
+ var id: String { rawValue }
+}
+
+struct AiGenerateInput: Encodable, Sendable {
+ var action: AiAction
+ var title: String
+ var contentMarkdown: String
+ var targetLanguage: String?
+}
+
+struct AiStreamEvent: Decodable, Sendable {
+ var type: String
+ var text: String?
+ var code: String?
+ var message: String?
+ var finishReason: String?
+ var inputTokens: Int?
+ var outputTokens: Int?
+}
+
struct Resource: Codable, Equatable, Sendable, Identifiable {
var id: String
var memoId: String
diff --git a/apps/ios/EdgeEver/Data/Network/APIClient.swift b/apps/ios/EdgeEver/Data/Network/APIClient.swift
index 473b55b1..55d0590e 100644
--- a/apps/ios/EdgeEver/Data/Network/APIClient.swift
+++ b/apps/ios/EdgeEver/Data/Network/APIClient.swift
@@ -185,6 +185,64 @@ actor APIClient {
return response.editSession
}
+ // MARK: - AI note processing
+
+ func streamAiGeneration(_ input: AiGenerateInput) -> AsyncThrowingStream<AiStreamEvent, Error> {
+ var request = URLRequest(url: makeURL(path: "/api/v1/ai/generate"))
+ request.httpMethod = "POST"
+ request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ if let token {
+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ }
+ let encodedBody: Data
+ do {
+ encodedBody = try EdgeEverJSON.encoder.encode(input)
+ } catch {
+ return AsyncThrowingStream { continuation in continuation.finish(throwing: error) }
+ }
+ request.httpBody = encodedBody
+ let streamRequest = request
+ let session = self.session
+ let unauthorized = onUnauthorized
+
+ return AsyncThrowingStream { continuation in
+ let task = Task {
+ do {
+ let (bytes, response) = try await session.bytes(for: streamRequest)
+ guard let http = response as? HTTPURLResponse else {
+ throw APIError(status: -1, code: nil, message: "Invalid response")
+ }
+ if http.statusCode == 401 {
+ unauthorized?()
+ }
+ guard (200 ..< 300).contains(http.statusCode) else {
+ var data = Data()
+ for try await byte in bytes { data.append(byte) }
+ let message = Self.parseErrorMessage(data: data)
+ ?? HTTPURLResponse.localizedString(forStatusCode: http.statusCode)
+ throw APIError(
+ status: http.statusCode,
+ code: Self.parseErrorCode(data: data),
+ message: message
+ )
+ }
+ for try await line in bytes.lines {
+ try Task.checkCancellation()
+ guard line.hasPrefix("data: ") else { continue }
+ let payload = String(line.dropFirst(6))
+ guard let data = payload.data(using: .utf8) else { continue }
+ continuation.yield(try EdgeEverJSON.decoder.decode(AiStreamEvent.self, from: data))
+ }
+ continuation.finish()
+ } catch {
+ continuation.finish(throwing: error)
+ }
+ }
+ continuation.onTermination = { _ in task.cancel() }
+ }
+ }
+
// MARK: - Templates
func listTemplates() async throws -> [MemoTemplate] {
diff --git a/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift b/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift
new file mode 100644
index 00000000..2d19e995
--- /dev/null
+++ b/apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift
@@ -0,0 +1,245 @@
+import SwiftUI
+import UIKit
+
+enum AiDraftApplyMode: Sendable {
+ case append
+ case replace
+}
+
+struct AiAssistantSheet: View {
+ @Environment(AppEnvironment.self) private var env
+ @Environment(\.dismiss) private var dismiss
+
+ let memo: MemoDetail
+ let onApply: (String, AiDraftApplyMode) async throws -> Void
+
+ @State private var action: AiAction = .summarize
+ @State private var targetLanguage = ""
+ @State private var output = ""
+ @State private var error: String?
+ @State private var isGenerating = false
+ @State private var isApplying = false
+ @State private var streamTask: Task<Void, Never>?
+
+ var body: some View {
+ NavigationStack {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 18) {
+ Text(env.preferences.t(
+ "AI 输出会先作为草稿展示,确认后才会修改笔记。",
+ en: "AI output remains a draft until you choose to apply it."
+ ))
+ .font(.system(size: 13))
+ .foregroundStyle(AppTheme.muted)
+
+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 118), spacing: 8)], spacing: 8) {
+ ForEach(AiAction.allCases) { item in
+ Button {
+ action = item
+ } label: {
+ Text(actionTitle(item))
+ .font(.system(size: 13, weight: .semibold))
+ .frame(maxWidth: .infinity, minHeight: 38)
+ .foregroundStyle(action == item ? AppTheme.accent : AppTheme.body)
+ .background(action == item ? AppTheme.accent.opacity(0.1) : AppTheme.card)
+ .clipShape(RoundedRectangle(cornerRadius: 9, style: .continuous))
+ .overlay {
+ RoundedRectangle(cornerRadius: 9, style: .continuous)
+ .stroke(action == item ? AppTheme.accent : AppTheme.cardBorder, lineWidth: 1)
+ }
+ }
+ .buttonStyle(.plain)
+ }
+ }
+
+ if action == .translate {
+ VStack(alignment: .leading, spacing: 7) {
+ Text(env.preferences.t("目标语言", en: "Target language"))
+ .font(.system(size: 13, weight: .bold))
+ TextField(
+ env.preferences.t("例如:英语、日语", en: "For example: English, Japanese"),
+ text: $targetLanguage
+ )
+ .textInputAutocapitalization(.never)
+ .padding(.horizontal, 12)
+ .frame(height: 44)
+ .background(AppTheme.card)
+ .clipShape(RoundedRectangle(cornerRadius: 9, style: .continuous))
+ .overlay {
+ RoundedRectangle(cornerRadius: 9, style: .continuous)
+ .stroke(AppTheme.cardBorder, lineWidth: 1)
+ }
+ }
+ }
+
+ HStack {
+ Text(env.preferences.t("AI 草稿", en: "AI draft"))
+ .font(.system(size: 13, weight: .bold))
+ Spacer()
+ if isGenerating {
+ ProgressView()
+ .controlSize(.small)
+ Text(env.preferences.t("生成中…", en: "Generating…"))
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(AppTheme.accent)
+ }
+ }
+
+ Text(output.isEmpty
+ ? env.preferences.t("生成的草稿会显示在这里。", en: "The generated draft will appear here.")
+ : output)
+ .font(.system(size: 15))
+ .foregroundStyle(output.isEmpty ? AppTheme.muted : AppTheme.body)
+ .frame(maxWidth: .infinity, minHeight: 230, alignment: .topLeading)
+ .padding(14)
+ .background(AppTheme.card)
+ .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
+ .overlay {
+ RoundedRectangle(cornerRadius: 10, style: .continuous)
+ .stroke(AppTheme.cardBorder, lineWidth: 1)
+ }
+ .textSelection(.enabled)
+
+ if let error, !error.isEmpty {
+ Text(error)
+ .font(.system(size: 13))
+ .foregroundStyle(AppTheme.dangerStrong)
+ }
+ }
+ .padding(16)
+ }
+ .background(AppTheme.background)
+ .navigationTitle(env.preferences.t("AI 笔记助手", en: "AI note assistant"))
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button(env.preferences.t("关闭", en: "Close")) { dismiss() }
+ .disabled(isApplying)
+ }
+ }
+ .safeAreaInset(edge: .bottom) {
+ footer
+ }
+ }
+ .interactiveDismissDisabled(isApplying)
+ .onDisappear { streamTask?.cancel() }
+ }
+
+ private var footer: some View {
+ VStack(spacing: 10) {
+ HStack(spacing: 8) {
+ secondaryButton(env.preferences.t("复制", en: "Copy"), systemImage: "doc.on.doc") {
+ UIPasteboard.general.string = output
+ }
+ secondaryButton(env.preferences.t("追加", en: "Append"), systemImage: "text.append") {
+ apply(.append)
+ }
+ secondaryButton(env.preferences.t("替换", en: "Replace"), systemImage: "arrow.triangle.2.circlepath") {
+ apply(.replace)
+ }
+ }
+ if isGenerating {
+ Button {
+ streamTask?.cancel()
+ } label: {
+ Label(env.preferences.t("停止", en: "Stop"), systemImage: "stop.fill")
+ .font(.system(size: 15, weight: .bold))
+ .frame(maxWidth: .infinity, minHeight: 44)
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(AppTheme.accent)
+ } else {
+ Button {
+ generate()
+ } label: {
+ Text(env.preferences.t("生成", en: "Generate"))
+ .font(.system(size: 15, weight: .bold))
+ .frame(maxWidth: .infinity, minHeight: 44)
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(AppTheme.accent)
+ .disabled(isApplying || (action == .translate && targetLanguage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty))
+ }
+ }
+ .padding(.horizontal, 12)
+ .padding(.top, 10)
+ .padding(.bottom, 6)
+ .background(.regularMaterial)
+ .overlay(alignment: .top) { Rectangle().fill(AppTheme.cardBorder).frame(height: 1) }
+ }
+
+ private func secondaryButton(_ title: String, systemImage: String, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ Label(title, systemImage: systemImage)
+ .font(.system(size: 13, weight: .semibold))
+ .frame(maxWidth: .infinity, minHeight: 40)
+ }
+ .buttonStyle(.bordered)
+ .tint(AppTheme.body)
+ .disabled(output.isEmpty || isGenerating || isApplying)
+ }
+
+ private func actionTitle(_ action: AiAction) -> String {
+ switch action {
+ case .summarize: env.preferences.t("总结", en: "Summarize")
+ case .extractKeyPoints: env.preferences.t("提炼要点", en: "Key points")
+ case .extractTodos: env.preferences.t("提取待办", en: "Extract tasks")
+ case .rewriteProofread: env.preferences.t("改写与校对", en: "Rewrite & proofread")
+ case .translate: env.preferences.t("翻译", en: "Translate")
+ }
+ }
+
+ private func generate() {
+ streamTask?.cancel()
+ output = ""
+ error = nil
+ isGenerating = true
+ let input = AiGenerateInput(
+ action: action,
+ title: memo.title?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "",
+ contentMarkdown: memo.contentMarkdown,
+ targetLanguage: action == .translate
+ ? targetLanguage.trimmingCharacters(in: .whitespacesAndNewlines)
+ : nil
+ )
+ streamTask = Task {
+ do {
+ let stream = await env.session.client.streamAiGeneration(input)
+ for try await event in stream {
+ try Task.checkCancellation()
+ switch event.type {
+ case "text-delta": output += event.text ?? ""
+ case "error": error = event.message ?? env.preferences.t("AI 生成失败。", en: "AI generation failed.")
+ default: break
+ }
+ }
+ } catch is CancellationError {
+ // User stopped generation.
+ } catch let apiError as APIError where apiError.code == "ai_not_configured" {
+ error = env.preferences.t(
+ "请先在 Web 或桌面端的“AI 集成”中配置模型。",
+ en: "Configure a model in AI Integrations on the web or desktop app first."
+ )
+ } catch {
+ self.error = error.localizedDescription
+ }
+ isGenerating = false
+ streamTask = nil
+ }
+ }
+
+ private func apply(_ mode: AiDraftApplyMode) {
+ guard !output.isEmpty, !isApplying else { return }
+ isApplying = true
+ error = nil
+ Task {
+ do {
+ try await onApply(output, mode)
+ dismiss()
+ } catch {
+ self.error = error.localizedDescription
+ isApplying = false
+ }
+ }
+ }
+}
diff --git a/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift b/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift
index 11abfc36..6c9081eb 100644
--- a/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift
+++ b/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift
@@ -26,6 +26,7 @@ struct MemoDetailView: View {
@State private var showDeleteConfirm = false
@State private var showMoreMenu = false
@State private var showNoteIdCopied = false
+ @State private var showAiAssistant = false
@State private var resourceTarget: ResourceTarget?
@State private var imagePreview: (source: String, alt: String)?
/// TipTap EditorBundle is ~4MB; keep native text visible until first setContent finishes.
@@ -104,6 +105,13 @@ struct MemoDetailView: View {
memoSharePayload = nil
}
}
+ .sheet(isPresented: $showAiAssistant) {
+ if let memo {
+ AiAssistantSheet(memo: memo) { draft, mode in
+ try await applyAiDraft(draft, mode: mode, to: memo)
+ }
+ }
+ }
.fullScreenCover(isPresented: Binding(
get: { imagePreview != nil },
set: { if !$0 { imagePreview = nil } }
@@ -133,6 +141,11 @@ struct MemoDetailView: View {
) {
if let memo {
Button(env.preferences.t("编辑", en: "Edit")) { onEdit(memo.id) }
+ if !memo.isDeleted && !isTemporaryMemoId(memo.id) {
+ Button(env.preferences.t("AI 笔记助手", en: "AI note assistant")) {
+ showAiAssistant = true
+ }
+ }
Button(
memo.isPinned
? env.preferences.t("取消置顶", en: "Unpin")
@@ -727,6 +740,57 @@ struct MemoDetailView: View {
}
}
+ private func applyAiDraft(
+ _ draft: String,
+ mode: AiDraftApplyMode,
+ to sourceMemo: MemoDetail
+ ) async throws {
+ guard let scope = env.session.dataScope else {
+ throw APIError(
+ status: -1,
+ code: "session_unavailable",
+ message: env.preferences.t("登录状态已失效,请重新登录。", en: "Your session has expired. Sign in again.")
+ )
+ }
+ let normalizedDraft = draft.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !normalizedDraft.isEmpty else { return }
+ let currentContent = sourceMemo.contentMarkdown.trimmingCharacters(in: .whitespacesAndNewlines)
+ let contentMarkdown = mode == .append && !currentContent.isEmpty
+ ? "\(currentContent)\n\n\(normalizedDraft)"
+ : normalizedDraft
+
+ let editSession = try await env.session.client.createMemoEditSession(memoId: sourceMemo.id)
+ guard
+ editSession.baseRevision == sourceMemo.revision,
+ editSession.baseContentHash == sourceMemo.contentHash
+ else {
+ throw APIError(
+ status: 409,
+ code: "revision_conflict",
+ message: env.preferences.t(
+ "笔记已在其他设备更新,请刷新后重新生成。",
+ en: "This note changed on another device. Refresh it and generate again."
+ )
+ )
+ }
+
+ let updated = try await env.session.client.updateMemo(
+ id: sourceMemo.id,
+ expectedRevision: sourceMemo.revision,
+ expectedContentHash: sourceMemo.contentHash,
+ editSessionId: editSession.id,
+ notebookId: nil,
+ title: nil,
+ isPinned: nil,
+ contentMarkdown: contentMarkdown,
+ contentJson: nil,
+ tags: nil
+ )
+ try env.mirror.upsertMemo(scope: scope, memo: updated)
+ memo = updated
+ refreshSyncStatus()
+ }
+
private func shareMemo(_ memo: MemoDetail) async {
do {
let share = try await env.session.client.createMemoShare(memoId: memo.id)
diff --git a/apps/mobile/src/components/MobileAiAssistantModal.tsx b/apps/mobile/src/components/MobileAiAssistantModal.tsx
new file mode 100644
index 00000000..2940c56b
--- /dev/null
+++ b/apps/mobile/src/components/MobileAiAssistantModal.tsx
@@ -0,0 +1,227 @@
+import { useEffect, useRef, useState } from "react";
+import { ApiRequestError } from "@edgeever/client";
+import type { AiAction, MemoDetail } from "@edgeever/shared";
+import * as Clipboard from "expo-clipboard";
+import { Modal, Pressable, ScrollView, StyleSheet, TextInput, View } from "react-native";
+import { SafeAreaView } from "react-native-safe-area-context";
+import { Copy, Sparkles, Square, X } from "./icons";
+import { Alert, Text } from "./LocalizedText";
+import { useMobileLocale } from "../lib/mobile-locale";
+import { useMobileTheme } from "../lib/mobile-theme";
+import { useSession } from "../lib/session";
+
+const actions: AiAction[] = [
+ "summarize",
+ "extract-key-points",
+ "extract-todos",
+ "rewrite-proofread",
+ "translate",
+];
+
+export const MobileAiAssistantModal = ({
+ memo,
+ onApply,
+ onClose,
+ visible,
+}: {
+ memo: MemoDetail;
+ onApply: (draft: string, mode: "append" | "replace") => Promise<void>;
+ onClose: () => void;
+ visible: boolean;
+}) => {
+ const { client } = useSession();
+ const { resolvedLocale } = useMobileLocale();
+ const { resolvedTheme } = useMobileTheme();
+ const dark = resolvedTheme === "dark";
+ const [action, setAction] = useState<AiAction>("summarize");
+ const [targetLanguage, setTargetLanguage] = useState("");
+ const [output, setOutput] = useState("");
+ const [error, setError] = useState<string | null>(null);
+ const [generating, setGenerating] = useState(false);
+ const [applying, setApplying] = useState(false);
+ const controllerRef = useRef<AbortController | null>(null);
+ const tr = (zh: string, en: string) => resolvedLocale === "en-US" ? en : zh;
+
+ useEffect(() => () => controllerRef.current?.abort(), []);
+ useEffect(() => {
+ if (!visible) controllerRef.current?.abort();
+ }, [visible]);
+
+ const labels: Record<AiAction, string> = {
+ summarize: tr("总结", "Summarize"),
+ "extract-key-points": tr("提炼要点", "Key points"),
+ "extract-todos": tr("提取待办", "Extract tasks"),
+ "rewrite-proofread": tr("改写与校对", "Rewrite & proofread"),
+ translate: tr("翻译", "Translate"),
+ };
+
+ const generate = async () => {
+ if (!client || (action === "translate" && !targetLanguage.trim())) return;
+ controllerRef.current?.abort();
+ const controller = new AbortController();
+ controllerRef.current = controller;
+ setOutput("");
+ setError(null);
+ setGenerating(true);
+ try {
+ await client.streamAiGeneration(
+ {
+ action,
+ title: memo.title?.trim() ?? "",
+ contentMarkdown: memo.contentMarkdown,
+ ...(action === "translate" ? { targetLanguage: targetLanguage.trim() } : {}),
+ },
+ {
+ signal: controller.signal,
+ onEvent: (event) => {
+ if (event.type === "text-delta") setOutput((current) => current + event.text);
+ if (event.type === "error") setError(event.message);
+ },
+ }
+ );
+ } catch (caught) {
+ if (controller.signal.aborted) return;
+ setError(
+ caught instanceof ApiRequestError && caught.code === "ai_not_configured"
+ ? tr("请先在 Web 或桌面端的“AI 集成”中配置模型。", "Configure a model in AI Integrations on the web or desktop app first.")
+ : caught instanceof Error ? caught.message : tr("AI 生成失败。", "AI generation failed.")
+ );
+ } finally {
+ if (controllerRef.current === controller) {
+ controllerRef.current = null;
+ setGenerating(false);
+ }
+ }
+ };
+
+ const apply = async (mode: "append" | "replace") => {
+ if (!output || applying) return;
+ setApplying(true);
+ setError(null);
+ try {
+ await onApply(output, mode);
+ Alert.alert(tr("已更新笔记", "Note updated"));
+ onClose();
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : tr("更新笔记失败。", "Could not update the note."));
+ } finally {
+ setApplying(false);
+ }
+ };
+
+ const surface = dark ? "#111c18" : "#ffffff";
+ const mutedSurface = dark ? "#17251f" : "#f8fafc";
+ const border = dark ? "#33453d" : "#dbe4df";
+ const foreground = dark ? "#e2e8f0" : "#0f172a";
+ const muted = dark ? "#94a3b8" : "#64748b";
+
+ return (
+ <Modal animationType="slide" onRequestClose={onClose} presentationStyle="pageSheet" visible={visible}>
+ <SafeAreaView style={[styles.safeArea, { backgroundColor: surface }]}>
+ <View style={[styles.header, { borderBottomColor: border }]}>
+ <View style={styles.titleRow}>
+ <Sparkles color="#16A06E" size={20} />
+ <Text style={[styles.title, { color: foreground }]}>{tr("AI 笔记助手", "AI note assistant")}</Text>
+ </View>
+ <Pressable accessibilityLabel={tr("关闭", "Close")} accessibilityRole="button" onPress={onClose} style={styles.iconButton}>
+ <X color={muted} size={22} />
+ </Pressable>
+ </View>
+ <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
+ <Text style={[styles.description, { color: muted }]}>
+ {tr("AI 输出会先作为草稿展示,确认后才会修改笔记。", "AI output remains a draft until you choose to apply it.")}
+ </Text>
+ <View style={styles.actions}>
+ {actions.map((item) => (
+ <Pressable
+ key={item}
+ onPress={() => setAction(item)}
+ style={[
+ styles.actionChip,
+ { borderColor: action === item ? "#16A06E" : border, backgroundColor: action === item ? (dark ? "#073f2f" : "#e8f7f0") : surface },
+ ]}
+ >
+ <Text style={[styles.actionText, { color: action === item ? (dark ? "#5ee2ad" : "#087a51") : foreground }]}>{labels[item]}</Text>
+ </Pressable>
+ ))}
+ </View>
+ {action === "translate" ? (
+ <View style={styles.field}>
+ <Text style={[styles.fieldLabel, { color: foreground }]}>{tr("目标语言", "Target language")}</Text>
+ <TextInput
+ maxLength={80}
+ onChangeText={setTargetLanguage}
+ placeholder={tr("例如:英语、日语", "For example: English, Japanese")}
+ placeholderTextColor={muted}
+ style={[styles.input, { borderColor: border, color: foreground, backgroundColor: surface }]}
+ value={targetLanguage}
+ />
+ </View>
+ ) : null}
+ <View style={styles.resultHeader}>
+ <Text style={[styles.fieldLabel, { color: foreground }]}>{tr("AI 草稿", "AI draft")}</Text>
+ {generating ? <Text style={styles.streaming}>{tr("生成中…", "Generating…")}</Text> : null}
+ </View>
+ <View style={[styles.result, { borderColor: border, backgroundColor: mutedSurface }]}>
+ <Text selectable style={[styles.resultText, { color: output ? foreground : muted }]}>
+ {output || tr("生成的草稿会显示在这里。", "The generated draft will appear here.")}
+ </Text>
+ </View>
+ {error ? <Text style={styles.error}>{error}</Text> : null}
+ </ScrollView>
+ <View style={[styles.footer, { borderTopColor: border, backgroundColor: surface }]}>
+ <View style={styles.footerRow}>
+ <Pressable disabled={!output || generating} onPress={() => void Clipboard.setStringAsync(output)} style={[styles.secondaryButton, { borderColor: border }, (!output || generating) && styles.disabled]}>
+ <Copy color={foreground} size={16} />
+ <Text style={[styles.secondaryText, { color: foreground }]}>{tr("复制", "Copy")}</Text>
+ </Pressable>
+ <Pressable disabled={!output || generating || applying} onPress={() => void apply("append")} style={[styles.secondaryButton, { borderColor: border }, (!output || generating || applying) && styles.disabled]}>
+ <Text style={[styles.secondaryText, { color: foreground }]}>{tr("追加", "Append")}</Text>
+ </Pressable>
+ <Pressable disabled={!output || generating || applying} onPress={() => void apply("replace")} style={[styles.secondaryButton, { borderColor: border }, (!output || generating || applying) && styles.disabled]}>
+ <Text style={[styles.secondaryText, { color: foreground }]}>{tr("替换", "Replace")}</Text>
+ </Pressable>
+ </View>
+ {generating ? (
+ <Pressable onPress={() => controllerRef.current?.abort()} style={styles.primaryButton}>
+ <Square color="#ffffff" size={14} />
+ <Text style={styles.primaryText}>{tr("停止", "Stop")}</Text>
+ </Pressable>
+ ) : (
+ <Pressable disabled={applying || (action === "translate" && !targetLanguage.trim())} onPress={() => void generate()} style={[styles.primaryButton, (applying || (action === "translate" && !targetLanguage.trim())) && styles.disabled]}>
+ <Text style={styles.primaryText}>{tr("生成", "Generate")}</Text>
+ </Pressable>
+ )}
+ </View>
+ </SafeAreaView>
+ </Modal>
+ );
+};
+
+const styles = StyleSheet.create({
+ safeArea: { flex: 1 },
+ header: { minHeight: 54, paddingHorizontal: 16, flexDirection: "row", alignItems: "center", justifyContent: "space-between", borderBottomWidth: StyleSheet.hairlineWidth },
+ titleRow: { flexDirection: "row", alignItems: "center", gap: 8 },
+ title: { fontSize: 17, fontWeight: "700" },
+ iconButton: { width: 40, height: 40, alignItems: "center", justifyContent: "center" },
+ content: { padding: 16, gap: 16 },
+ description: { fontSize: 13, lineHeight: 19 },
+ actions: { flexDirection: "row", flexWrap: "wrap", gap: 8 },
+ actionChip: { minHeight: 38, paddingHorizontal: 12, borderRadius: 9, borderWidth: 1, alignItems: "center", justifyContent: "center" },
+ actionText: { fontSize: 13, fontWeight: "600" },
+ field: { gap: 7 },
+ fieldLabel: { fontSize: 13, fontWeight: "700" },
+ input: { height: 44, borderWidth: 1, borderRadius: 9, paddingHorizontal: 12, fontSize: 15 },
+ resultHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" },
+ streaming: { color: "#087a51", fontSize: 12, fontWeight: "600" },
+ result: { minHeight: 220, borderWidth: 1, borderRadius: 10, padding: 14 },
+ resultText: { fontSize: 15, lineHeight: 23 },
+ error: { color: "#be123c", fontSize: 13, lineHeight: 19 },
+ footer: { padding: 12, gap: 10, borderTopWidth: StyleSheet.hairlineWidth },
+ footerRow: { flexDirection: "row", gap: 8 },
+ secondaryButton: { minHeight: 40, flex: 1, flexDirection: "row", gap: 6, borderWidth: 1, borderRadius: 9, alignItems: "center", justifyContent: "center" },
+ secondaryText: { fontSize: 13, fontWeight: "600" },
+ primaryButton: { height: 44, borderRadius: 9, backgroundColor: "#16A06E", flexDirection: "row", gap: 7, alignItems: "center", justifyContent: "center" },
+ primaryText: { color: "#ffffff", fontSize: 15, fontWeight: "700" },
+ disabled: { opacity: 0.45 },
+});
diff --git a/apps/mobile/src/components/icons.tsx b/apps/mobile/src/components/icons.tsx
index cf4a2a2b..d60486f4 100644
--- a/apps/mobile/src/components/icons.tsx
+++ b/apps/mobile/src/components/icons.tsx
@@ -72,6 +72,7 @@ export const Share2 = createIcon("share-2");
export const ShieldCheck = createIcon("shield");
export const SlidersHorizontal = createIcon("sliders");
export const Sparkles = createIcon("star");
+export const Square = createIcon("square");
export const Sun = createIcon("sun");
export const Tag = createIcon("tag");
export const Trash2 = createIcon("trash-2");
diff --git a/apps/mobile/src/lib/mobile-locale.tsx b/apps/mobile/src/lib/mobile-locale.tsx
index fd6c86f8..7c996200 100644
--- a/apps/mobile/src/lib/mobile-locale.tsx
+++ b/apps/mobile/src/lib/mobile-locale.tsx
@@ -31,6 +31,7 @@ const mobileOnlyTranslations = new Map<string, string>([
["输入关键词开始搜索", "Enter a keyword to search"],
["搜索本机同步缓存,结果会即时显示", "Search the local synced cache with instant results"],
["笔记操作", "Note actions"],
+ ["AI 笔记助手", "AI note assistant"],
["版本历史", "Version history"],
["分享笔记", "Share note"],
["复制笔记 ID", "Copy note ID"],
diff --git a/apps/mobile/src/lib/session.tsx b/apps/mobile/src/lib/session.tsx
index 7de8cb99..692c7e9a 100644
--- a/apps/mobile/src/lib/session.tsx
+++ b/apps/mobile/src/lib/session.tsx
@@ -1,6 +1,7 @@
import { createEdgeEverClient } from "@edgeever/client";
import type { AuthUser } from "@edgeever/shared";
import { useQueryClient } from "@tanstack/react-query";
+import { fetch as expoFetch } from "expo/fetch";
import * as SecureStore from "expo-secure-store";
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
@@ -68,6 +69,7 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
return createEdgeEverClient({
baseUrl: session.baseUrl,
token: session.token,
+ fetch: expoFetch as typeof fetch,
onUnauthorized: () => {
queryClient.clear();
setSession(null);
diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
index 175e5190..63a1035b 100644
--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
@@ -5,9 +5,10 @@ import { Image as RNImage, Platform, StyleSheet, View, type ImageStyle, type Sty
import { Modal } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import { SvgXml } from "react-native-svg";
-import { ActivityIndicator, ChevronDown, ChevronLeft, ChevronRight, Copy, History, MoreHorizontal, Pencil, RotateCcw, Search, Share2, Tag, Trash2, X } from "../components/icons";
+import { ActivityIndicator, ChevronDown, ChevronLeft, ChevronRight, Copy, History, MoreHorizontal, Pencil, RotateCcw, Search, Share2, Sparkles, Tag, Trash2, X } from "../components/icons";
import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";
import LocalTiptapEditor, { type LocalTiptapEditorRef } from "../components/LocalTiptapEditor";
+import { MobileAiAssistantModal } from "../components/MobileAiAssistantModal";
import { MobileResourceActions } from "../components/MobileResourceActions";
import { SAFE_DOM_WEBVIEW_PROPS } from "../lib/mobile-dom";
import { safeDomCall } from "../lib/safe-dom-call";
@@ -300,6 +301,7 @@ export const MemoDetailModal = ({
memo,
notebookName,
onAdoptCloudVersion,
+ onApplyAiDraft,
onClose,
onCopyLocalDraft,
onDelete,
@@ -323,6 +325,7 @@ export const MemoDetailModal = ({
memo: MemoDetail | null;
notebookName: string;
onAdoptCloudVersion: (memo: MemoDetail) => void;
+ onApplyAiDraft: (memo: MemoDetail, draft: string, mode: "append" | "replace") => Promise<void>;
onClose: () => void;
onCopyLocalDraft: (memo: MemoDetail) => void;
onDelete: (memo: MemoDetail) => void;
@@ -343,6 +346,7 @@ export const MemoDetailModal = ({
const { resolvedLocale } = useMobileLocale();
const safeAreaInsets = useSafeAreaInsets();
const [actionsOpen, setActionsOpen] = useState(false);
+ const [aiAssistantOpen, setAiAssistantOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [searchMatchCount, setSearchMatchCount] = useState(0);
@@ -776,6 +780,13 @@ export const MemoDetailModal = ({
<Pressable style={styles.actionSheet}>
<View style={styles.actionSheetHandle} />
<Text style={styles.actionSheetTitle}>笔记操作</Text>
+ {!memo.isDeleted ? (
+ <DetailActionSheetItem
+ icon={<Sparkles color="#16A06E" size={18} />}
+ label="AI 笔记助手"
+ onPress={() => closeActionsAndRun(() => setAiAssistantOpen(true))}
+ />
+ ) : null}
<DetailActionSheetItem
disabled={!canCopyMemoId}
icon={<Copy color="#0f172a" size={18} />}
@@ -797,6 +808,14 @@ export const MemoDetailModal = ({
</Pressable>
</Modal>
) : null}
+ {memo && !memo.isDeleted ? (
+ <MobileAiAssistantModal
+ memo={memo}
+ onApply={(draft, mode) => onApplyAiDraft(memo, draft, mode)}
+ onClose={() => setAiAssistantOpen(false)}
+ visible={aiAssistantOpen}
+ />
+ ) : null}
<Modal animationType="fade" onRequestClose={() => setImagePreview(null)} transparent visible={Boolean(imagePreview)}>
<View style={resourceImageStyles.previewBackdrop}>
{imagePreview ? (
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index e3eacf65..07899d41 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -917,6 +917,20 @@ export const WorkspaceScreen = ({
},
});
+ const applyAiDraftToMemo = async (memo: MemoDetail, draft: string, mode: "append" | "replace") => {
+ const normalizedDraft = draft.trim();
+ const contentMarkdown = mode === "append"
+ ? [memo.contentMarkdown.trimEnd(), normalizedDraft].filter(Boolean).join("\n\n")
+ : normalizedDraft;
+ await localUpdateMemoMutation.mutateAsync({
+ memo,
+ payload: {
+ contentMarkdown,
+ contentJson: markdownToDoc(contentMarkdown),
+ },
+ });
+ };
+
const deleteMemoMutation = useMutation({
mutationFn: async ({ memo, permanent }: { memo: MemoDetail; permanent: boolean }) => {
await deleteMobileMemos({
@@ -1271,6 +1285,7 @@ export const WorkspaceScreen = ({
onOpenRevisions={setRevisionMemo}
onRenameResource={handleRenameResource}
onAdoptCloudVersion={(memo) => void handleAdoptCloudVersion(memo)}
+ onApplyAiDraft={applyAiDraftToMemo}
onCopyLocalDraft={(memo) => void handleCopyConflictDraft(memo)}
onResolveSyncConflict={handleMemoSyncConflict}
onRetrySync={() => {
diff --git a/tests/mobile-ai-assistant.test.ts b/tests/mobile-ai-assistant.test.ts
new file mode 100644
index 00000000..4bce3b9c
--- /dev/null
+++ b/tests/mobile-ai-assistant.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+
+const readSource = (path: string) => readFileSync(new URL(path, import.meta.url), "utf8");
+
+const androidAssistantSource = readSource("../apps/mobile/src/components/MobileAiAssistantModal.tsx");
+const androidDetailSource = readSource("../apps/mobile/src/screens/WorkspaceMemoDetail.tsx");
+const androidWorkspaceSource = readSource("../apps/mobile/src/screens/WorkspaceScreen.tsx");
+const androidSessionSource = readSource("../apps/mobile/src/lib/session.tsx");
+const iosAssistantSource = readSource("../apps/ios/EdgeEver/Features/Workspace/AiAssistantSheet.swift");
+const iosDetailSource = readSource("../apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift");
+const iosApiSource = readSource("../apps/ios/EdgeEver/Data/Network/APIClient.swift");
+
+describe("native mobile AI note assistant", () => {
+ test("exposes all five first-version actions on Android and iOS", () => {
+ for (const action of [
+ "summarize",
+ "extract-key-points",
+ "extract-todos",
+ "rewrite-proofread",
+ "translate",
+ ]) {
+ expect(androidAssistantSource).toContain(`"${action}"`);
+ }
+
+ for (const action of [
+ "case summarize",
+ 'case extractKeyPoints = "extract-key-points"',
+ 'case extractTodos = "extract-todos"',
+ 'case rewriteProofread = "rewrite-proofread"',
+ "case translate",
+ ]) {
+ expect(readSource("../apps/ios/EdgeEver/Data/Models/Models.swift")).toContain(action);
+ }
+ });
+
+ test("streams AI output from the shared workspace configuration on both clients", () => {
+ expect(androidAssistantSource).toContain("client.streamAiGeneration(");
+ expect(androidSessionSource).toContain("fetch: expoFetch as typeof fetch");
+ expect(iosAssistantSource).toContain("client.streamAiGeneration(input)");
+ expect(iosApiSource).toContain('makeURL(path: "/api/v1/ai/generate")');
+ expect(iosApiSource).toContain("for try await line in bytes.lines");
+ });
+
+ test("keeps AI output as a draft until append or replace is confirmed", () => {
+ expect(androidAssistantSource).toContain('apply("append")');
+ expect(androidAssistantSource).toContain('apply("replace")');
+ expect(androidWorkspaceSource).toContain("localUpdateMemoMutation.mutateAsync");
+ expect(androidWorkspaceSource).toContain("contentJson: markdownToDoc(contentMarkdown)");
+
+ expect(iosAssistantSource).toContain("apply(.append)");
+ expect(iosAssistantSource).toContain("apply(.replace)");
+ expect(iosDetailSource).toContain("createMemoEditSession(memoId: sourceMemo.id)");
+ expect(iosDetailSource).toContain("expectedRevision: sourceMemo.revision");
+ expect(iosDetailSource).toContain("expectedContentHash: sourceMemo.contentHash");
+ });
+
+ test("keeps the assistant reachable from each native note action menu", () => {
+ expect(androidDetailSource).toContain('label="AI 笔记助手"');
+ expect(androidDetailSource).toContain("<MobileAiAssistantModal");
+ expect(iosDetailSource).toContain('env.preferences.t("AI 笔记助手", en: "AI note assistant")');
+ expect(iosDetailSource).toContain("AiAssistantSheet(memo: memo)");
+ });
+});