Skip to content

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

feat(api): seed example notebooks on new instances

tianma-if1ec44c00cd20
diff --git a/apps/api/src/auth-service.ts b/apps/api/src/auth-service.ts
index 1ea8f08c..565f6f4d 100644
--- a/apps/api/src/auth-service.ts
+++ b/apps/api/src/auth-service.ts
@@ -20,6 +20,7 @@ import { apiError } from "./http-errors";
import type { DatabaseAdapter } from "./storage-contract";
import type { InstanceUserRow } from "./user-routes";
import { ensureUserWorkspace } from "./workspace-provisioning";
+import { ensureWorkspaceExampleSeed } from "./workspace-example-seed";
type SessionRow = {
id: string;
@@ -285,6 +286,10 @@ const authenticateBearerToken = async (c: AppContext, touch: boolean): Promise<A
).bind(now, row.id, cutoff).run();
}
+ await ensureWorkspaceExampleSeed(c.env, row.workspace_id).catch((error) => {
+ console.error("EdgeEver example seed failed", error);
+ });
+
return {
kind: "agent",
actorType: "agent",
@@ -335,6 +340,10 @@ const authenticateSessionToken = async (c: AppContext, token: string, touch: boo
? { workspaceId: row.workspace_id, role: row.role }
: await ensureUserWorkspace(c.env.storage.db, row.user_id, row.username, c.req.header("accept-language"));
+ await ensureWorkspaceExampleSeed(c.env, workspace.workspaceId).catch((error) => {
+ console.error("EdgeEver example seed failed", error);
+ });
+
return {
kind: "user",
actorType: "user",
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 74c1c62f..da866dbc 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -127,6 +127,7 @@ import {
deleteStoredObjects,
getActiveObjectStorageConfig,
} from "./object-storage";
+import { ensureWorkspaceExampleSeed } from "./workspace-example-seed";
import {
DEFAULT_WORKSPACE_ID,
ensureUserWorkspace,
@@ -305,6 +306,9 @@ app.use("/api/v1/*", async (c, next) => {
workspaceId: DEFAULT_WORKSPACE_ID,
role: "owner",
});
+ await ensureWorkspaceExampleSeed(c.env, DEFAULT_WORKSPACE_ID).catch((error) => {
+ console.error("EdgeEver example seed failed", error);
+ });
await next();
return;
}
diff --git a/apps/api/src/user-routes.test.mjs b/apps/api/src/user-routes.test.mjs
index 9809f975..c2c1723f 100644
--- a/apps/api/src/user-routes.test.mjs
+++ b/apps/api/src/user-routes.test.mjs
@@ -504,11 +504,30 @@ describe("instance user management with a real database", () => {
expect(response.status).toBe(200);
const usage = await response.json();
- expect(usage.summary).toEqual({ totalCount: 3, totalBytes: 1320, imageCount: 2, attachmentCount: 1 });
+ // The owner's first authenticated request also writes the installation example files.
+ const seeded = instance.sqlite.query(
+ `SELECT COUNT(*) AS totalCount,
+ COALESCE(SUM(byte_size), 0) AS totalBytes,
+ COALESCE(SUM(CASE WHEN kind = 'image' THEN 1 ELSE 0 END), 0) AS imageCount,
+ COALESCE(SUM(CASE WHEN kind = 'attachment' THEN 1 ELSE 0 END), 0) AS attachmentCount
+ FROM resources
+ WHERE is_deleted = 0 AND object_key LIKE 'examples/%'`,
+ ).get();
+ expect(usage.summary).toEqual({
+ totalCount: 3 + seeded.totalCount,
+ totalBytes: 1320 + seeded.totalBytes,
+ imageCount: 2 + seeded.imageCount,
+ attachmentCount: 1 + seeded.attachmentCount,
+ });
const byUser = Object.fromEntries(usage.users.map((entry) => [entry.userId, entry.summary]));
expect(byUser).toEqual({
[member.id]: { totalCount: 2, totalBytes: 320, imageCount: 1, attachmentCount: 1 },
- usr_owner: { totalCount: 1, totalBytes: 1000, imageCount: 1, attachmentCount: 0 },
+ usr_owner: {
+ totalCount: 1 + seeded.totalCount,
+ totalBytes: 1000 + seeded.totalBytes,
+ imageCount: 1 + seeded.imageCount,
+ attachmentCount: seeded.attachmentCount,
+ },
});
});
});
diff --git a/apps/api/src/user-routes.ts b/apps/api/src/user-routes.ts
index b1214795..be6f7272 100644
--- a/apps/api/src/user-routes.ts
+++ b/apps/api/src/user-routes.ts
@@ -10,6 +10,7 @@ import { badRequest, conflict, forbidden, notFound, unauthorized } from "./http-
import { requireOwner } from "./request-auth";
import { mapResourceStorageSummary, type ResourceStatsRow } from "./resource-service";
import type { DatabaseAdapter } from "./storage-contract";
+import { markWorkspaceExampleSeedPendingStatement } from "./workspace-example-seed";
import {
createDefaultNotebookRows,
markWorkspaceSeedLocalizationPendingStatement,
@@ -139,6 +140,7 @@ export const registerUserRoutes = (
VALUES (?, ?, NULL, ?, ?, 'notebook', ?, ?, ?, ?)`,
).bind(notebook.id, workspaceId, notebook.name, notebook.slug, notebook.color, notebook.sortOrder, now, now)),
markWorkspaceSeedLocalizationPendingStatement(context.env.storage.db, workspaceId, now),
+ markWorkspaceExampleSeedPendingStatement(context.env.storage.db, workspaceId, now),
auditStatement(context.env.storage.db, "user", context.get("auth").actorId, "user.create", "user", userId, {
username: input.username,
}),
diff --git a/apps/api/src/workspace-example-seed.test.mjs b/apps/api/src/workspace-example-seed.test.mjs
new file mode 100644
index 00000000..fcd93ef6
--- /dev/null
+++ b/apps/api/src/workspace-example-seed.test.mjs
@@ -0,0 +1,203 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { Database } from "bun:sqlite";
+import { globSync, readFileSync } from "node:fs";
+import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";
+import { ensureUserWorkspace } from "./workspace-provisioning.ts";
+import {
+ ensureWorkspaceExampleSeed,
+ omitInstanceUnavailableExampleTips,
+} from "./workspace-example-seed.ts";
+
+const MIGRATION = "0079_workspace_example_seeds.sql";
+const migrationFiles = globSync("migrations/*.sql").sort();
+const opened = [];
+afterEach(() => opened.splice(0).forEach((sqlite) => sqlite.close()));
+
+const migrate = (sqlite, filter = () => true) => {
+ for (const file of migrationFiles.filter(filter)) sqlite.exec(readFileSync(file, "utf8"));
+};
+
+const openDatabase = () => {
+ const sqlite = new Database(":memory:");
+ opened.push(sqlite);
+ const puts = [];
+ const { db } = createSelfHostedStorageAdapter(sqlite, "/tmp/edgeever-example-seed-unused");
+ const env = {
+ storage: {
+ db,
+ resources: {
+ put: async (key) => {
+ puts.push(key);
+ },
+ },
+ },
+ };
+ return { sqlite, env, puts };
+};
+
+const freshInstallation = () => {
+ const database = openDatabase();
+ migrate(database.sqlite);
+ return database;
+};
+
+const upgradedInstallation = (prepare) => {
+ const database = openDatabase();
+ migrate(database.sqlite, (file) => file < `migrations/${MIGRATION}`);
+ prepare(database.sqlite);
+ migrate(database.sqlite, (file) => file >= `migrations/${MIGRATION}`);
+ return database;
+};
+
+const addUser = (sqlite, id, username = id) => sqlite
+ .query("INSERT INTO users (id, username, password_hash, display_name) VALUES (?, ?, 'unused', ?)")
+ .run(id, username, username);
+
+const pending = (sqlite) => sqlite
+ .query("SELECT workspace_id FROM workspace_example_seeds ORDER BY workspace_id")
+ .all()
+ .map((row) => row.workspace_id);
+
+const exampleCounts = (sqlite, workspaceId = "ws_default") => Object.fromEntries(
+ sqlite.query(
+ `SELECT n.slug, COUNT(m.id) AS count
+ FROM notebooks n
+ LEFT JOIN memos m ON m.notebook_id = n.id AND m.is_deleted = 0
+ WHERE n.workspace_id = ? AND n.slug IN ('demo-features', 'feature-demos')
+ GROUP BY n.slug
+ ORDER BY n.slug`,
+ ).all(workspaceId).map((row) => [row.slug, row.count]),
+);
+
+const overviewMarkdown = (sqlite, memoId = "memo_demo_overview") => sqlite
+ .query("SELECT content_markdown FROM memo_contents WHERE memo_id = ?")
+ .get(memoId)?.content_markdown ?? "";
+
+describe("workspace example seed", () => {
+ test("drops the demo-only reset tip from copied notes", () => {
+ const source = [
+ "> 7. 点击 **“分享为卡片”**,挑选一款你心仪的社交海报风格并导出;",
+ "> 8. 随时在侧边栏或设置中点击 **“恢复 Demo 数据”**,一键重置演示工作区。",
+ "> 8. Click **\"Reset Demo Data\"** in settings or the sidebar anytime to restore the demo workspace.",
+ ].join("\n");
+
+ expect(omitInstanceUnavailableExampleTips(source)).toBe(
+ "> 7. 点击 **“分享为卡片”**,挑选一款你心仪的社交海报风格并导出;",
+ );
+ });
+
+ test("gives a fresh installation both example notebooks and leaves the welcome note", async () => {
+ const { sqlite, env, puts } = freshInstallation();
+ expect(pending(sqlite)).toEqual(["ws_default"]);
+
+ await ensureWorkspaceExampleSeed(env, "ws_default");
+
+ expect(pending(sqlite)).toEqual([]);
+ expect(exampleCounts(sqlite)).toEqual({ "demo-features": 7, "feature-demos": 7 });
+ expect(sqlite.query("SELECT id FROM memos WHERE id = 'memo_welcome'").get()).toEqual({ id: "memo_welcome" });
+ expect(sqlite.query("SELECT parent_id FROM notebooks WHERE id = 'nb_demo_features'").get())
+ .toEqual({ parent_id: "nb_projects" });
+ expect(overviewMarkdown(sqlite)).toContain("/api/v1/resources/res_demo_logo/blob");
+ expect(overviewMarkdown(sqlite)).not.toContain("恢复 Demo 数据");
+ expect(overviewMarkdown(sqlite, "memo_demo_overview_en")).not.toContain("Reset Demo Data");
+ expect(sqlite.query("SELECT COUNT(*) AS count FROM resources WHERE id = 'res_demo_logo'").get()).toEqual({ count: 1 });
+ expect(puts.some((key) => key.includes("res_demo_logo"))).toBe(true);
+
+ const memoCount = sqlite.query("SELECT COUNT(*) AS count FROM memos").get().count;
+ await ensureWorkspaceExampleSeed(env, "ws_default");
+ expect(sqlite.query("SELECT COUNT(*) AS count FROM memos").get().count).toBe(memoCount);
+ });
+
+ test("still seeds a welcome note that was only localized", async () => {
+ const { sqlite, env } = freshInstallation();
+ addUser(sqlite, "usr_owner", "admin");
+ await ensureUserWorkspace(env.storage.db, "usr_owner", "admin", "pl");
+
+ await ensureWorkspaceExampleSeed(env, "ws_default");
+
+ expect(sqlite.query("SELECT title FROM memos WHERE id = 'memo_welcome'").get()).toEqual({ title: "Witaj w EdgeEver" });
+ expect(exampleCounts(sqlite)).toEqual({ "demo-features": 7, "feature-demos": 7 });
+ });
+
+ test("does not backfill an installation that already has another note", async () => {
+ const { sqlite, env } = upgradedInstallation((existing) => {
+ existing.query(
+ `INSERT INTO memos (id, notebook_id, title, created_by, updated_by)
+ VALUES ('memo_user', 'nb_inbox', '自己的笔记', 'usr_owner', 'usr_owner')`,
+ ).run();
+ });
+
+ expect(pending(sqlite)).toEqual([]);
+ await ensureWorkspaceExampleSeed(env, "ws_default");
+ expect(exampleCounts(sqlite)).toEqual({});
+ });
+
+ test("does not backfill a welcome note the user has edited", async () => {
+ const { sqlite, env } = upgradedInstallation((existing) => {
+ existing.query("UPDATE memos SET updated_by = 'usr_owner' WHERE id = 'memo_welcome'").run();
+ });
+
+ expect(pending(sqlite)).toEqual([]);
+ await ensureWorkspaceExampleSeed(env, "ws_default");
+ expect(exampleCounts(sqlite)).toEqual({});
+ });
+
+ test("drops a pending seed when the welcome body no longer matches a system translation", async () => {
+ const { sqlite, env } = freshInstallation();
+ sqlite.query("UPDATE memo_contents SET content_hash = 'edited' WHERE memo_id = 'memo_welcome'").run();
+
+ await ensureWorkspaceExampleSeed(env, "ws_default");
+
+ expect(pending(sqlite)).toEqual([]);
+ expect(exampleCounts(sqlite)).toEqual({});
+ });
+
+ test("gives a newly created workspace its own copy with distinct ids", async () => {
+ const { sqlite, env } = freshInstallation();
+ addUser(sqlite, "usr_owner", "admin");
+ addUser(sqlite, "usr_writer", "writer");
+ await ensureUserWorkspace(env.storage.db, "usr_owner", "admin", "zh-CN");
+ const workspace = await ensureUserWorkspace(env.storage.db, "usr_writer", "writer", "ja");
+ expect(pending(sqlite)).toContain(workspace.workspaceId);
+
+ await ensureWorkspaceExampleSeed(env, workspace.workspaceId);
+
+ expect(pending(sqlite)).not.toContain(workspace.workspaceId);
+ expect(exampleCounts(sqlite, workspace.workspaceId)).toEqual({ "demo-features": 7, "feature-demos": 7 });
+ const notebook = sqlite.query(
+ "SELECT id, parent_id FROM notebooks WHERE workspace_id = ? AND slug = 'demo-features'",
+ ).get(workspace.workspaceId);
+ expect(notebook.id).toBe(`${workspace.workspaceId}_nb_demo_features`);
+ expect(notebook.parent_id).toBe(`${workspace.workspaceId}_projects`);
+ const markdown = sqlite.query(
+ `SELECT c.content_markdown
+ FROM memo_contents c
+ INNER JOIN memos m ON m.id = c.memo_id
+ WHERE m.workspace_id = ? AND m.title LIKE '欢迎使用 EdgeEver%'`,
+ ).get(workspace.workspaceId).content_markdown;
+ expect(markdown).toContain(`/api/v1/resources/${workspace.workspaceId}_res_demo_logo/blob`);
+ expect(markdown).not.toContain("/api/v1/resources/res_demo_logo/blob");
+ expect(sqlite.query("SELECT id FROM memos WHERE id = 'memo_demo_overview'").get()).toBeNull();
+ });
+
+ test("waits to seed until object storage can store the example files", async () => {
+ const { sqlite, env } = freshInstallation();
+ env.storage.resources = {};
+
+ await ensureWorkspaceExampleSeed(env, "ws_default");
+
+ expect(pending(sqlite)).toEqual(["ws_default"]);
+ expect(exampleCounts(sqlite)).toEqual({});
+ });
+
+ test("leaves the catalog to demo mode", async () => {
+ const { sqlite, env } = freshInstallation();
+ env.EDGE_EVER_DEMO_MODE = "true";
+
+ await ensureWorkspaceExampleSeed(env, "ws_default");
+
+ expect(pending(sqlite)).toEqual([]);
+ expect(exampleCounts(sqlite)).toEqual({});
+ expect(sqlite.query("SELECT COUNT(*) AS count FROM memos").get()).toEqual({ count: 1 });
+ });
+});
diff --git a/apps/api/src/workspace-example-seed.ts b/apps/api/src/workspace-example-seed.ts
new file mode 100644
index 00000000..d5a415a9
--- /dev/null
+++ b/apps/api/src/workspace-example-seed.ts
@@ -0,0 +1,283 @@
+import {
+ createExcerpt,
+ docToText,
+ markdownToDoc,
+ normalizeTags,
+} from "@edgeever/shared";
+import {
+ WELCOME_MEMO_REPAIRED_CONTENT_HASH,
+ WELCOME_MEMO_SEED_CONTENT_HASH,
+ WELCOME_MEMO_TRANSLATIONS,
+ buildWelcomeMemoContent,
+} from "@edgeever/shared/default-workspace-seeds";
+import { supportedLocales, type SupportedLocale } from "@edgeever/shared/i18n/locales";
+import type { Bindings } from "./api-context";
+import {
+ decodeDemoAttachment,
+ DEMO_SEED_ATTACHMENT_RESOURCES,
+ DEMO_SEED_MEMOS,
+ DEMO_SEED_REVISIONS,
+} from "./demo-seed-data";
+import { isDemoModeEnabled } from "./demo-mode";
+import { isoNow } from "./entity-utils";
+import { sha256, sha256Bytes } from "./hash-utils";
+import { upsertMemoSearchDocumentStatement } from "./memo-search-index";
+import type { DatabaseAdapter, PreparedStatementAdapter } from "./storage-contract";
+
+const EXAMPLE_NOTEBOOKS = [
+ { id: "nb_demo_features", slug: "demo-features", name: "功能演示", sortOrder: 21 },
+ { id: "nb_demo_features_en", slug: "feature-demos", name: "Feature Demos", sortOrder: 22 },
+] as const;
+
+const WELCOME_MEMO_ID = "memo_welcome";
+const DEFAULT_WORKSPACE_ID = "ws_default";
+const DEFAULT_BUCKET_NAME = "edgeever-resources";
+
+// The public demo tells visitors to reset the shared workspace. A personal
+// instance has no such action, so that tip is left out of the copied notes.
+export const omitInstanceUnavailableExampleTips = (markdown: string) => markdown
+ .split("\n")
+ .filter((line) => !line.includes("恢复 Demo 数据") && !line.includes("Reset Demo Data"))
+ .join("\n");
+
+export const markWorkspaceExampleSeedPendingStatement = (
+ db: DatabaseAdapter,
+ workspaceId: string,
+ now = isoNow(),
+): PreparedStatementAdapter => db.prepare(
+ `INSERT OR IGNORE INTO workspace_example_seeds (workspace_id, created_at) VALUES (?, ?)`,
+).bind(workspaceId, now);
+
+const knownWelcomeContentHashes = async () => {
+ const hashes = new Set<string>([
+ WELCOME_MEMO_SEED_CONTENT_HASH,
+ WELCOME_MEMO_REPAIRED_CONTENT_HASH,
+ ]);
+ for (const locale of supportedLocales) {
+ const welcome = buildWelcomeMemoContent(locale);
+ hashes.add(await sha256(welcome.contentMarkdown + welcome.contentJson));
+ }
+ return hashes;
+};
+
+const knownWelcomeTitles = new Set(
+ (Object.keys(WELCOME_MEMO_TRANSLATIONS) as SupportedLocale[])
+ .map((locale) => WELCOME_MEMO_TRANSLATIONS[locale].title),
+);
+
+type WelcomeRow = {
+ id: string;
+ is_deleted: number;
+ created_by: string;
+ updated_by: string;
+ title: string | null;
+ content_hash: string | null;
+};
+
+const workspaceStillWantsExamples = async (
+ db: DatabaseAdapter,
+ workspaceId: string,
+) => {
+ const memos = (await db.prepare(
+ `SELECT m.id, m.is_deleted, m.created_by, m.updated_by, m.title, c.content_hash
+ FROM memos m
+ LEFT JOIN memo_contents c ON c.memo_id = m.id
+ WHERE m.workspace_id = ?`,
+ ).bind(workspaceId).all<WelcomeRow>()).results;
+
+ if (memos.length === 0) return true;
+
+ const welcomeHashes = await knownWelcomeContentHashes();
+ return memos.length === 1
+ && memos[0].id === WELCOME_MEMO_ID
+ && memos[0].is_deleted === 0
+ && memos[0].created_by === "system"
+ && memos[0].updated_by === "system"
+ && knownWelcomeTitles.has(memos[0].title ?? "")
+ && welcomeHashes.has(memos[0].content_hash ?? "");
+};
+
+const clearPending = (db: DatabaseAdapter, workspaceId: string) => db.prepare(
+ `DELETE FROM workspace_example_seeds WHERE workspace_id = ?`,
+).bind(workspaceId).run();
+
+const idsAreFree = async (db: DatabaseAdapter, table: string, ids: string[]) => {
+ if (ids.length === 0) return true;
+ const row = await db.prepare(
+ `SELECT id FROM ${table} WHERE id IN (${ids.map(() => "?").join(", ")}) LIMIT 1`,
+ ).bind(...ids).first<{ id: string }>();
+ return !row;
+};
+
+const applyImageWidths = (nodes: Array<{ type?: string; attrs?: Record<string, unknown>; content?: unknown[] }>) => {
+ for (const node of nodes) {
+ if (node.type === "image") {
+ node.attrs = { ...node.attrs, width: 35 };
+ }
+ if (Array.isArray(node.content)) {
+ applyImageWidths(node.content as Array<{ type?: string; attrs?: Record<string, unknown>; content?: unknown[] }>);
+ }
+ }
+};
+
+const resourceBytes = (resource: (typeof DEMO_SEED_ATTACHMENT_RESOURCES)[number]) => {
+ if ("svg" in resource) return new TextEncoder().encode(resource.svg);
+ return decodeDemoAttachment(resource);
+};
+
+export const ensureWorkspaceExampleSeed = async (env: Bindings, workspaceId: string) => {
+ const db = env.storage.db;
+ const pending = await db.prepare(
+ `SELECT workspace_id FROM workspace_example_seeds WHERE workspace_id = ?`,
+ ).bind(workspaceId).first<{ workspace_id: string }>();
+ if (!pending) return;
+
+ const demoOwnsTheCatalog = isDemoModeEnabled(env.EDGE_EVER_DEMO_MODE)
+ || isDemoModeEnabled(env.EDGE_EVER_LOCAL_DEMO_SEED);
+ if (demoOwnsTheCatalog || !await workspaceStillWantsExamples(db, workspaceId)) {
+ await clearPending(db, workspaceId);
+ return;
+ }
+
+ if (typeof env.storage.resources?.put !== "function") return;
+
+ const projects = await db.prepare(
+ `SELECT id FROM notebooks
+ WHERE workspace_id = ? AND is_deleted = 0 AND parent_id IS NULL
+ AND (slug = 'work-projects' OR id = 'nb_projects' OR id = ?)
+ LIMIT 1`,
+ ).bind(workspaceId, `${workspaceId}_projects`).first<{ id: string }>();
+ if (!projects) {
+ await clearPending(db, workspaceId);
+ return;
+ }
+
+ const canonicalNotebookIds = EXAMPLE_NOTEBOOKS.map((notebook) => notebook.id);
+ const canonicalMemoIds = DEMO_SEED_MEMOS.map((memo) => memo.id);
+ const canonicalRevisionIds = DEMO_SEED_REVISIONS.map((revision) => revision.id);
+ const canonicalResourceIds = DEMO_SEED_ATTACHMENT_RESOURCES.map((resource) => resource.id);
+ // The installation workspace keeps the ids the clients already open. Every
+ // later workspace gets its own ids so the two copies can exist together.
+ const useCanonicalIds = workspaceId === DEFAULT_WORKSPACE_ID
+ && await idsAreFree(db, "notebooks", canonicalNotebookIds)
+ && await idsAreFree(db, "memos", canonicalMemoIds)
+ && await idsAreFree(db, "memo_revisions", canonicalRevisionIds)
+ && await idsAreFree(db, "resources", canonicalResourceIds);
+ const mapId = (id: string) => useCanonicalIds ? id : `${workspaceId}_${id}`;
+ const rewriteResourceLinks = (markdown: string) => {
+ if (useCanonicalIds) return markdown;
+ return canonicalResourceIds.reduce(
+ (current, id) => current.replaceAll(`/api/v1/resources/${id}/`, `/api/v1/resources/${mapId(id)}/`),
+ markdown,
+ );
+ };
+
+ const now = isoNow();
+ const statements: PreparedStatementAdapter[] = [];
+ for (const notebook of EXAMPLE_NOTEBOOKS) {
+ statements.push(db.prepare(
+ `INSERT OR IGNORE INTO notebooks (
+ id, workspace_id, parent_id, name, slug, icon, color, sort_order, is_deleted, created_at, updated_at, deleted_at
+ ) VALUES (?, ?, ?, ?, ?, 'notebook', NULL, ?, 0, ?, ?, NULL)`,
+ ).bind(mapId(notebook.id), workspaceId, projects.id, notebook.name, notebook.slug, notebook.sortOrder, now, now));
+ }
+
+ for (const memo of DEMO_SEED_MEMOS) {
+ const markdown = rewriteResourceLinks(omitInstanceUnavailableExampleTips(memo.markdown));
+ const contentJson = markdownToDoc(markdown);
+ if (Array.isArray(contentJson.content)) applyImageWidths(contentJson.content);
+ const contentText = docToText(contentJson);
+ const contentHash = await sha256(markdown + JSON.stringify(contentJson));
+ const tags = normalizeTags(memo.tags);
+ statements.push(
+ db.prepare(
+ `INSERT OR IGNORE INTO memos (
+ id, workspace_id, notebook_id, title, excerpt, tags_json, is_pinned,
+ is_archived, is_deleted, created_by, updated_by, created_at, updated_at, deleted_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 0, 0, 'system', 'system', ?, ?, NULL)`,
+ ).bind(
+ mapId(memo.id),
+ workspaceId,
+ mapId(memo.notebookId),
+ memo.title,
+ createExcerpt(contentText),
+ JSON.stringify(tags),
+ memo.isPinned ? 1 : 0,
+ now,
+ now,
+ ),
+ db.prepare(
+ `INSERT OR IGNORE INTO memo_contents (
+ memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, 0, ?, ?)`,
+ ).bind(mapId(memo.id), JSON.stringify(contentJson), markdown, contentText, contentHash, now, now),
+ upsertMemoSearchDocumentStatement(db, mapId(memo.id), memo.title, contentText, tags.join(" ")),
+ );
+ }
+
+ for (const revision of DEMO_SEED_REVISIONS) {
+ const markdown = rewriteResourceLinks(omitInstanceUnavailableExampleTips(revision.markdown));
+ const contentJson = markdownToDoc(markdown);
+ const contentHash = await sha256(markdown + JSON.stringify(contentJson));
+ statements.push(db.prepare(
+ `INSERT OR IGNORE INTO memo_revisions (
+ id, memo_id, revision, title, content_json, content_markdown, content_hash, created_by, created_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 'system', ?)`,
+ ).bind(
+ mapId(revision.id),
+ mapId(revision.memoId),
+ revision.revision,
+ revision.title,
+ JSON.stringify(contentJson),
+ markdown,
+ contentHash,
+ now,
+ ));
+ }
+
+ const bucketName = env.EDGE_EVER_R2_BUCKET_NAME?.trim() || DEFAULT_BUCKET_NAME;
+ for (const resource of DEMO_SEED_ATTACHMENT_RESOURCES) {
+ const bytes = resourceBytes(resource);
+ const extension = "svg" in resource ? "svg" : resource.filename.split(".").pop() || "bin";
+ const resourceId = mapId(resource.id);
+ const objectKey = `examples/${workspaceId}/${resourceId}.${extension}`;
+ await env.storage.resources.put(objectKey, bytes, {
+ httpMetadata: {
+ contentType: resource.mimeType,
+ cacheControl: "private, max-age=3600",
+ },
+ customMetadata: {
+ memoId: mapId(resource.memoId),
+ resourceId,
+ filename: resource.filename,
+ instanceExample: "true",
+ },
+ });
+ statements.push(db.prepare(
+ `INSERT OR IGNORE INTO resources (
+ id, memo_id, bucket_name, object_key, storage_config_id, kind, mime_type, filename,
+ byte_size, sha256, width, height, metadata_json, is_deleted, created_at, updated_at, deleted_at
+ ) VALUES (?, ?, ?, ?, 'builtin', ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NULL)`,
+ ).bind(
+ resourceId,
+ mapId(resource.memoId),
+ bucketName,
+ objectKey,
+ "svg" in resource ? "image" : "attachment",
+ resource.mimeType,
+ resource.filename,
+ bytes.byteLength,
+ await sha256Bytes(bytes),
+ "svg" in resource ? resource.width : null,
+ "svg" in resource ? resource.height : null,
+ JSON.stringify({ source: "instance-example" }),
+ now,
+ now,
+ ));
+ }
+
+ statements.push(db.prepare(
+ `DELETE FROM workspace_example_seeds WHERE workspace_id = ?`,
+ ).bind(workspaceId));
+ await db.batch(statements);
+};
diff --git a/apps/api/src/workspace-provisioning.ts b/apps/api/src/workspace-provisioning.ts
index 4644cdda..93e1f03b 100644
--- a/apps/api/src/workspace-provisioning.ts
+++ b/apps/api/src/workspace-provisioning.ts
@@ -17,6 +17,7 @@ import {
localizeMemoTemplateSeed,
} from "@edgeever/shared/memo-template-seeds";
import { createId, isoNow } from "./entity-utils";
+import { markWorkspaceExampleSeedPendingStatement } from "./workspace-example-seed";
import { sha256 } from "./hash-utils";
import type {
DatabaseAdapter,
@@ -327,6 +328,7 @@ export const ensureUserWorkspace = async (
now,
)),
...createWorkspaceDefaultSeedStatements(db, workspaceId, now, locale),
+ markWorkspaceExampleSeedPendingStatement(db, workspaceId, now),
]);
return { workspaceId, role: "member" };
};
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index 3fa11aea..fbb3c73e 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -235,8 +235,16 @@ export const WorkspaceScreen = ({
const notebooks = notebooksQuery.data?.notebooks ?? [];
useEffect(() => {
const english = isEnglishMobileLocale(localePreference);
- const preferredNotebookId = english ? "nb_demo_features_en" : "nb_demo_features";
- const alternateNotebookId = english ? "nb_demo_features" : "nb_demo_features_en";
+ const notebookIdForSlug = (slug: string, fallbackId: string) =>
+ notebooks.find((notebook) => notebook.slug === slug)?.id ?? fallbackId;
+ const preferredNotebookId = notebookIdForSlug(
+ english ? "feature-demos" : "demo-features",
+ english ? "nb_demo_features_en" : "nb_demo_features",
+ );
+ const alternateNotebookId = notebookIdForSlug(
+ english ? "demo-features" : "feature-demos",
+ english ? "nb_demo_features" : "nb_demo_features_en",
+ );
if (!notebooks.some((notebook) => notebook.id === preferredNotebookId)) {
return;
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index 990f9d21..9d992632 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -686,7 +686,9 @@ export const WorkspaceApp = ({
const notebooks = notebooksQuery.data?.notebooks ?? [];
useEffect(() => {
const english = i18n.resolvedLanguage === "en-US";
- const preferredNotebookId = english ? "nb_demo_features_en" : "nb_demo_features";
+ const preferredSlug = english ? "feature-demos" : "demo-features";
+ const preferredNotebookId = notebooks.find((notebook) => notebook.slug === preferredSlug)?.id
+ ?? (english ? "nb_demo_features_en" : "nb_demo_features");
if (!notebooks.some((notebook) => notebook.id === preferredNotebookId)) {
return;
diff --git a/migrations/0079_workspace_example_seeds.sql b/migrations/0079_workspace_example_seeds.sql
new file mode 100644
index 00000000..47cad5d2
--- /dev/null
+++ b/migrations/0079_workspace_example_seeds.sql
@@ -0,0 +1,34 @@
+-- Example notebooks wait here until the API can write their generated notes.
+-- A row means the workspace still waits. The API removes it after seeding, or
+-- when the workspace is no longer eligible, so a failed attempt is retried.
+CREATE TABLE IF NOT EXISTS workspace_example_seeds (
+ workspace_id TEXT PRIMARY KEY REFERENCES workspaces(id) ON DELETE CASCADE,
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
+);
+
+-- Only an upgrade whose sole surviving note is the untouched system welcome
+-- note qualifies. A second note, a deleted note, or a user edit leaves the
+-- workspace unchanged. New workspaces insert their own pending row at creation.
+INSERT OR IGNORE INTO workspace_example_seeds (workspace_id)
+SELECT w.id
+FROM workspaces w
+WHERE EXISTS (
+ SELECT 1 FROM memos m
+ WHERE m.workspace_id = w.id
+ AND m.is_deleted = 0
+ AND m.id = 'memo_welcome'
+ AND m.created_by = 'system'
+ AND m.updated_by = 'system'
+ AND m.title IN (
+ '欢迎来到 EdgeEver',
+ 'Welcome to EdgeEver',
+ 'EdgeEver へようこそ',
+ 'Witaj w EdgeEver',
+ 'Добро пожаловать в EdgeEver'
+ )
+)
+AND NOT EXISTS (
+ SELECT 1 FROM memos m
+ WHERE m.workspace_id = w.id
+ AND NOT (m.is_deleted = 0 AND m.id = 'memo_welcome')
+);