Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 将任务简介中的 Markdown 转为可读纯文本 (#4130)
Dash4dd95d8636c1
diff --git a/apps/desktop/src/main/localDb/__tests__/mapperMarkdownPreview.test.ts b/apps/desktop/src/main/localDb/__tests__/mapperMarkdownPreview.test.tsnew file mode 100644index 0000000000..7cd284c6dd--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/mapperMarkdownPreview.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import { extractMessagePreview, finalizePlainPreview, sessionToCamel } from '../mapper';+import type { SessionRowWithCount } from '../mapper';++describe('sidebar Markdown preview', () => {+ const markdown =+ '[PR #3943](https://github.com/makecindy/cindy/pull/3943) 已合并,CI 无失败、review 已通过。';+ const plain = 'PR #3943 已合并,CI 无失败、review 已通过。';++ it('keeps link labels and the conclusion in live and serialized previews', () => {+ expect(finalizePlainPreview(markdown, 'assistant')).toBe(plain);+ expect(extractMessagePreview(JSON.stringify(markdown), 'assistant')).toBe(plain);+ expect(extractMessagePreview(JSON.stringify({ text: markdown }), 'user')).toBe(plain);+ });++ it('normalizes existing raw cached previews on read', () => {+ const session = sessionToCamel({+ createdAt: 1,+ updatedAt: 1,+ totalCostUsd: 0,+ listPreview: markdown,+ listPreviewRole: 'assistant',+ } as SessionRowWithCount);+ expect(session.preview).toBe(plain);+ });++ it('counts readable characters rather than a long link destination', () => {+ const text = `看过了,[PR #4069](https://example.com/${'a'.repeat(250)}) 已修复。`;+ expect(finalizePlainPreview(text, 'assistant')).toBe('看过了,PR #4069 已修复。');+ expect(finalizePlainPreview(`**${'字'.repeat(160)}**`, 'assistant')).toBe('字'.repeat(140));+ });++ it.each([+ [+ '## 结果\n\n> **已完成**,`APPROVED / CLEAN`。\n- [x] 检查通过',+ '结果 已完成,APPROVED / CLEAN。 检查通过',+ ],+ [+ '[**PR**](https://example.com/a_(b)) 和 [文档][doc]\n\n[doc]: https://example.com',+ 'PR 和 文档',+ ],+ [+ '\n\n```ts\nconst ok = true;\n```',+ '效果图 const ok = true;',+ ],+ ['| 项目 | 状态 |\n| --- | --- |\n| CI | **通过** |', '项目 状态 CI 通过'],+ [+ 'src/my_file.ts、foo_bar_baz、2 * 3、[普通括号]',+ 'src/my_file.ts、foo_bar_baz、2 * 3、[普通括号]',+ ],+ ['尚未写完 **结果', '尚未写完 **结果'],+ ['<script>alert(1)</script>\n\n正文', '正文'],+ ['<img src="https://example.com/image.png" alt="效果图">', '效果图'],+ [+ '完成 <img src="cindy-media://blobs/image" alt="Light & Dark"> 通过',+ '完成 Light & Dark 通过',+ ],+ ['<img src="javascript:alert(1)" alt="不支持的图片">', null],+ ['<img src="https://example.com/image.png">', null],+ ['<script><img src="https://example.com/image.png" alt="隐藏内容"></script>', null],+ ['---', null],+ ])('extracts readable content from %s', (text, expected) => {+ expect(finalizePlainPreview(text, 'assistant')).toBe(expected);+ });+});diff --git a/apps/desktop/src/main/localDb/__tests__/sessionListProjection.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionListProjection.test.tsindex 2dbc4913aa..54ca851e3f 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionListProjection.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionListProjection.test.ts@@ -43,6 +43,41 @@ const extractSql = `SELECT ${LIST_PREVIEW_EXTRACT_SQL} AS preview, m.role AS rolLIMIT 1`;describe('session list SQL preview extract', () => {+ it.each(['```\n# foo\n```', '`---`', '\\*literal\\*'])(+ 'keeps raw Markdown through cache backfill: %s',+ (markdown) => {+ const db = openPreviewDb();+ try {+ db.prepare('INSERT INTO sessions (id) VALUES (?)').run('s1');+ db.prepare(+ 'INSERT INTO messages (id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?)',+ ).run('m1', 's1', 'assistant', JSON.stringify(markdown), 1);+ const cold = db.prepare(extractSql).get('s1') as { preview: string; role: string };+ const display = finalizePlainPreview(cold.preview, cold.role);+ db.prepare(SESSION_LIST_PROJECTION_BACKFILL_SQL).run(+ JSON.stringify([{ id: 's1', preview: display }]),+ );+ const warm = db+ .prepare(+ 'SELECT list_preview AS preview, list_preview_role AS role FROM sessions WHERE id = ?',+ )+ .get('s1') as { preview: string; role: string };+ expect(warm.preview).toBe(markdown);+ expect(finalizePlainPreview(warm.preview, warm.role)).toBe(display);+ db.prepare(+ 'UPDATE sessions SET list_preview = NULL, list_preview_role = NULL WHERE id = ?',+ ).run('s1');+ db.prepare(SESSION_LIST_PROJECTION_BACKFILL_SQL).run(JSON.stringify([{ id: 's1' }]));+ const refreshed = db+ .prepare('SELECT list_preview FROM sessions WHERE id = ?')+ .get('s1') as { list_preview: string };+ expect(refreshed.list_preview).toBe(markdown);+ } finally {+ db.close();+ }+ },+ );+it('extracts user .text and assistant JSON strings without slicing JSON', () => {const db = openPreviewDb();db.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');@@ -224,12 +259,26 @@ describe('session list projection backfill SQL', () => {db.prepare(`INSERT INTO messages (id, session_id, role, content, created_at)VALUES (?, 's1', 'assistant', ?, 2), (?, 's1', 'user', ?, 1), (?, 's2', 'assistant', ?, 1)`,- ).run('m1', JSON.stringify('hello'), 'm0', JSON.stringify({ text: 'older' }), 'm2', JSON.stringify('stale'));+ ).run(+ 'm1',+ JSON.stringify('hello'),+ 'm0',+ JSON.stringify({ text: 'older' }),+ 'm2',+ JSON.stringify('stale'),+ );db.prepare(SESSION_LIST_PROJECTION_BACKFILL_SQL).run(JSON.stringify([{ id: 's1', preview: 'stale payload', role: 'user', count: 99, hasPreview: 1, hasCount: 1 },- { id: 's2', preview: 'overwrite?', role: 'assistant', count: 9, hasPreview: 1, hasCount: 1 },+ {+ id: 's2',+ preview: 'overwrite?',+ role: 'assistant',+ count: 9,+ hasPreview: 1,+ hasCount: 1,+ },{ id: 's3', preview: 'new preview', role: 'user', count: 99, hasPreview: 1, hasCount: 1 },]),);diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex 343e9e3b1a..bd677b2dc1 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -7,14 +7,27 @@*/import { ipcMain, BrowserWindow } from 'electron';-import { and, asc, eq, inArray, lt, lte, gt, gte, desc, isNull, or, sql, type SQL } from 'drizzle-orm';+import {+ and,+ asc,+ eq,+ inArray,+ lt,+ lte,+ gt,+ gte,+ desc,+ isNull,+ or,+ sql,+ type SQL,+} from 'drizzle-orm';import { createId } from '@paralleldrive/cuid2';import { getDbClient } from '../client/current';import type { ContextRebuildArgs } from '../client/tx/types';import { latestVisiblePreviewRow } from '../latestMessageText';import { messages, sessions } from '../schema';-import { persistSessionListPreview } from '../sessionListProjection';import {messageToCamel,messageCreateToRow,@@ -177,11 +190,7 @@ async function maybeBroadcastSessionListPreview(// 不在这里落库。insert/update 事务已经把 list_preview 置空;事后 persist 无法// 校验同一 clientId 的内容版本,交错改写会把旧正文写回非 NULL 缓存。// 侧栏即时刷新靠广播;下次 list/回填从 messages 现算。- broadcastOwnedPayload(- 'local-db:sessions:patched',- { sessionId, patch: { preview } },- ownerScope,- );+ broadcastOwnedPayload('local-db:sessions:patched', { sessionId, patch: { preview } }, ownerScope);}function isAutoResumeUserRow(agentMetaJson: string | null): boolean {@@ -190,9 +199,9 @@ function isAutoResumeUserRow(agentMetaJson: string | null): boolean {const parsed: unknown = JSON.parse(agentMetaJson);return Boolean(parsed &&- typeof parsed === 'object' &&- !Array.isArray(parsed) &&- (parsed as { autoResume?: unknown }).autoResume === true,+ typeof parsed === 'object' &&+ !Array.isArray(parsed) &&+ (parsed as { autoResume?: unknown }).autoResume === true,);} catch {return false;@@ -979,13 +988,9 @@ export async function commitMessageDeletion(try {const latest = await latestVisiblePreviewRow(sessionId);preview = extractMessagePreview(latest?.content, latest?.role);- await persistSessionListPreview(- sessionId,- preview,- latest?.role ?? null,- latest?.createdAt,- latest?.clientId,- );+ // Keep the transaction's invalidation. Only SQL backfill may populate the+ // raw Markdown cache; persisting this display text would parse code literals+ // a second time on the next list read (and could overwrite a newer edit).} catch (error) {// 删除已经原子提交;message.delete 事务已把 list_preview / role / count 置 NULL,// 投影刷新失败不能把成功操作伪装成失败。广播保守空值,list 回落子查询。@@ -1008,7 +1013,8 @@ export async function commitContextRebuild(sessionId: string,handoff: string,meta: {- reason: 'context-overflow' | 'model-window-switch' | 'pi-prompt-timeout' | 'native-session-recovery';+ reason:+ 'context-overflow' | 'model-window-switch' | 'pi-prompt-timeout' | 'native-session-recovery';sourceUserClientId: string | null;sourceAgentKind?: 'cc' | 'codex' | 'pi';sourceModel?: string | null;@@ -1027,7 +1033,9 @@ export async function commitContextRebuild(consumed: false,reason: meta.reason,sourceUserClientId: meta.sourceUserClientId,- ...(meta.replacementRoute ? { sourceSdkSessionId: meta.replacementRoute.expectedSdkSessionId } : {}),+ ...(meta.replacementRoute+ ? { sourceSdkSessionId: meta.replacementRoute.expectedSdkSessionId }+ : {}),...(meta.sourceAgentKind ? { sourceAgentKind: meta.sourceAgentKind } : {}),...(meta.sourceModel !== undefined ? { sourceModel: meta.sourceModel } : {}),...(meta.sourceProviderId !== undefined ? { sourceProviderId: meta.sourceProviderId } : {}),@@ -1505,35 +1513,35 @@ export async function createMessage(expectedClearBoundaryMs: guarded ? (expected ?? null) : undefined,});if (guarded && inserted.changes === 0) {- const [existingAfterGuard] = await db- .select()- .from(messages)- .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, body.clientId)))- .limit(1);- const [sessionAfterGuard] = await db- .select({ clearedAt: sessions.clearedAt })- .from(sessions)- .where(eq(sessions.id, sessionId))- .limit(1);- const actual = sessionAfterGuard?.clearedAt ?? null;- if (- existingAfterGuard &&- actual === expected &&- existingAfterGuard.rewindAt === null &&- (expected === null || existingAfterGuard.createdAt > expected)- ) {- return messageToCamel(existingAfterGuard);- }- if (actual !== expected) {- throw Object.assign(- new Error(- `REMOTE_OPTIMISTIC_INPUT_CLEARED: expectedClearBoundaryMs=${expected ?? 'null'}; currentClearBoundaryMs=${actual ?? 'null'}`,- ),- { code: 'REMOTE_OPTIMISTIC_INPUT_CLEARED' },- );- }- throw new Error('Message insert skipped without a clear-boundary change');+ const [existingAfterGuard] = await db+ .select()+ .from(messages)+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, body.clientId)))+ .limit(1);+ const [sessionAfterGuard] = await db+ .select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ const actual = sessionAfterGuard?.clearedAt ?? null;+ if (+ existingAfterGuard &&+ actual === expected &&+ existingAfterGuard.rewindAt === null &&+ (expected === null || existingAfterGuard.createdAt > expected)+ ) {+ return messageToCamel(existingAfterGuard);+ }+ if (actual !== expected) {+ throw Object.assign(+ new Error(+ `REMOTE_OPTIMISTIC_INPUT_CLEARED: expectedClearBoundaryMs=${expected ?? 'null'}; currentClearBoundaryMs=${actual ?? 'null'}`,+ ),+ { code: 'REMOTE_OPTIMISTIC_INPUT_CLEARED' },+ );}+ throw new Error('Message insert skipped without a clear-boundary change');+ }} catch (err) {const after = await db.select()diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex c7e879984d..fb9fa0a2ae 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -9,6 +9,7 @@import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';+import { markdownPreviewText } from '../../shared/markdownPreviewText.js';import type {sessions,@@ -73,9 +74,7 @@ type SessionUsageRow = Pick<* 运行时固定 effort 模型用 `null`;`sessions.effort` 是 NOT NULL 枚举。* 空白 / null 表示不落库,UPDATE 保留该行已有的合法档位。*/-export function persistableSessionEffort(- effort: unknown,-): SessionInsert['effort'] | undefined {+export function persistableSessionEffort(effort: unknown): SessionInsert['effort'] | undefined {if (typeof effort !== 'string') return undefined;const trimmed = effort.trim();return trimmed ? (trimmed as SessionInsert['effort']) : undefined;@@ -125,7 +124,7 @@ const PREVIEW_CONTENT_BOUND_CHARS = 4096;/*** 从消息 content(DB 存的 JSON string)提炼 sidebar 卡片预览纯文本。* - user 消息:content 是 `{"text":"...","images":[],"files":[]}` → 取 .text- * - assistant 消息:content 是 JSON.stringify 后的 markdown 字符串 → 解析后原样用+ * - assistant 消息:content 是 JSON.stringify 后的 markdown 字符串 → 提取可读正文* - 解析失败 / 空文本 → null(渲染端隐藏预览行)* 换行折叠成空格——卡片预览是流式 3 行 clamp,不保留消息内排版。*/@@ -140,7 +139,8 @@ export function finalizePlainPreview(// 实现细节。返回 null 与"无预览"同渲染语义。if (isSyntheticTriggerText(next)) return null;if (role === 'assistant') next = stripInternalWebCitations(next);- const collapsed = next.replace(/\s+/g, ' ').trim();+ // Strip formatting before the display limit: URLs must not consume the preview budget.+ const collapsed = markdownPreviewText(next);if (!collapsed) return null;return collapsed.length > PREVIEW_MAX_CHARS ? collapsed.slice(0, PREVIEW_MAX_CHARS) : collapsed;}@@ -203,8 +203,7 @@ export function boundSerializedMessageContent(* 出口处补一个空字符串 `userId: ''`,避免类型缺失;上层消费如果需要用户 id 应该读 AuthContext。*/export function sessionToCamel(row: SessionRowWithCount): Session {- const legacyMoney =- row.totalCostUsd > 0 ? legacyUsdMoney(row.totalCostUsd) : undefined;+ const legacyMoney = row.totalCostUsd > 0 ? legacyUsdMoney(row.totalCostUsd) : undefined;const currentMoney =row.totalCostCurrency && row.totalCostAmount > 0? normalizeRegionalMoney({@@ -224,8 +223,7 @@ export function sessionToCamel(row: SessionRowWithCount): Session {// 否则(CNY 无法表达进 USD 字段)保持冻结历史值。只消费 totalCostUsd 的读方// (device-link v1 / 手机端)在全量 reseed 后才不会丢本构建新增的 USD 花费。const legacyUsdProjection =- row.totalCostUsd +- (row.totalCostCurrency === 'USD' ? row.totalCostAmount : 0);+ row.totalCostUsd + (row.totalCostCurrency === 'USD' ? row.totalCostAmount : 0);const base: Session = {id: row.id,userId: '', // 本地 db 已按 user 隔离,无需冗余存储@@ -824,8 +822,7 @@ export function projectAutomationConsentToRow(/** ScheduleRun 行 → 内存对象。 */export function scheduleRunToCamel(row: ScheduleRunRow): ScheduleRun {- const legacyCost =- row.costUsd > 0 ? legacyUsdMoney(row.costUsd) : undefined;+ const legacyCost = row.costUsd > 0 ? legacyUsdMoney(row.costUsd) : undefined;const currentCost =row.costCurrency && row.costAmount > 0? normalizeRegionalMoney({@@ -860,9 +857,7 @@ export function scheduleRunToCamel(row: ScheduleRunRow): ScheduleRun {? legacyEstimate.currency === currentEstimate.currency? addRegionalMoney([legacyEstimate, currentEstimate]): currentEstimate- : (currentEstimate ??- legacyEstimate ??- zeroUsageMoney('value-estimate'));+ : (currentEstimate ?? legacyEstimate ?? zeroUsageMoney('value-estimate'));return {id: row.id,scheduleId: row.scheduleId,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.tsindex 1287971284..f889024042 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts@@ -48,8 +48,7 @@ describe('performMessageDeletion', () => {expect(deletionBlock).toContain('preview = extractMessagePreview(latest?.content, latest?.role);',);- expect(deletionBlock).toContain('await persistSessionListPreview(');- expect(deletionBlock).toContain('latest?.createdAt');+ expect(deletionBlock).not.toContain('persistSessionListPreview(');expect(deletionBlock).not.toContain('.where(eq(messages.sessionId, sessionId))');});diff --git a/apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts b/apps/desktop/src/renderer/components/chat/remarkHtmlImages.tsindex 01bf7a39c5..5add71a675 100644--- a/apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts+++ b/apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts@@ -8,88 +8,10 @@*/import type { Plugin } from 'unified';-import type { Root, Html, Image } from 'mdast';+import type { Root, Html } from 'mdast';import { visit, SKIP } from 'unist-util-visit';-const IMG_TAG_RE = /^\s*<img\b([^>]*)\/?>\s*$/i;-const ATTR_RE = /([A-Za-z_:][A-Za-z0-9:._-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g;-const SAFE_DIMENSION_RE = /^\d{1,4}$/;-const SAFE_HTML_IMAGE_SRC_RE = /^https?:\/\//i;--function decodeHtmlAttribute(value: string): string {- return value.replace(/&(amp|quot|#39|apos|lt|gt);/g, (entity, name: string) => {- switch (name) {- case 'amp':- return '&';- case 'quot':- return '"';- case '#39':- case 'apos':- return "'";- case 'lt':- return '<';- case 'gt':- return '>';- default:- return entity;- }- });-}--function parseAttributes(raw: string): Map<string, string> {- const attrs = new Map<string, string>();- ATTR_RE.lastIndex = 0;- let match: RegExpExecArray | null;- while ((match = ATTR_RE.exec(raw)) !== null) {- const key = match[1].toLowerCase();- const value = match[2] ?? match[3] ?? match[4] ?? '';- attrs.set(key, decodeHtmlAttribute(value));- }- return attrs;-}--function hPropertiesFromAttrs(attrs: Map<string, string>): Record<string, string> | undefined {- const hProperties: Record<string, string> = {};- for (const key of ['width', 'height'] as const) {- const value = attrs.get(key);- if (value && SAFE_DIMENSION_RE.test(value)) {- hProperties[key] = value;- }- }- return Object.keys(hProperties).length > 0 ? hProperties : undefined;-}--function isSafeHtmlImageSrc(src: string): boolean {- return (- SAFE_HTML_IMAGE_SRC_RE.test(src) ||- src.startsWith('xdt-image://') ||- src.startsWith('cindy-media://') ||- src.startsWith('xdt-file://') ||- src.startsWith('cindy-remote-media://')- );-}--function htmlImgToImageNode(node: Html): Image | null {- const match = node.value.match(IMG_TAG_RE);- if (!match) return null;-- const attrs = parseAttributes(match[1]);- const src = attrs.get('src')?.trim();- if (!src || !isSafeHtmlImageSrc(src)) return null;-- const image: Image = {- type: 'image',- url: src,- alt: attrs.get('alt') ?? '',- title: attrs.get('title') || null,- position: node.position,- };- const hProperties = hPropertiesFromAttrs(attrs);- if (hProperties) {- image.data = { hProperties };- }- return image;-}+import { htmlImgToImageNode } from '../../../shared/htmlImage';const remarkHtmlImages: Plugin<[], Root> = () => {return (tree) => {diff --git a/apps/desktop/src/shared/htmlImage.ts b/apps/desktop/src/shared/htmlImage.tsnew file mode 100644index 0000000000..9c94219832--- /dev/null+++ b/apps/desktop/src/shared/htmlImage.ts@@ -0,0 +1,81 @@+import type { Html, Image } from 'mdast';++const IMG_TAG_RE = /^\s*<img\b([^>]*)\/?>\s*$/i;+const ATTR_RE = /([A-Za-z_:][A-Za-z0-9:._-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g;+const SAFE_DIMENSION_RE = /^\d{1,4}$/;+const SAFE_HTML_IMAGE_SRC_RE = /^https?:\/\//i;++function decodeHtmlAttribute(value: string): string {+ return value.replace(/&(amp|quot|#39|apos|lt|gt);/g, (entity, name: string) => {+ switch (name) {+ case 'amp':+ return '&';+ case 'quot':+ return '"';+ case '#39':+ case 'apos':+ return "'";+ case 'lt':+ return '<';+ case 'gt':+ return '>';+ default:+ return entity;+ }+ });+}++function parseAttributes(raw: string): Map<string, string> {+ const attrs = new Map<string, string>();+ ATTR_RE.lastIndex = 0;+ let match: RegExpExecArray | null;+ while ((match = ATTR_RE.exec(raw)) !== null) {+ const key = match[1].toLowerCase();+ const value = match[2] ?? match[3] ?? match[4] ?? '';+ attrs.set(key, decodeHtmlAttribute(value));+ }+ return attrs;+}++function hPropertiesFromAttrs(attrs: Map<string, string>): Record<string, string> | undefined {+ const hProperties: Record<string, string> = {};+ for (const key of ['width', 'height'] as const) {+ const value = attrs.get(key);+ if (value && SAFE_DIMENSION_RE.test(value)) {+ hProperties[key] = value;+ }+ }+ return Object.keys(hProperties).length > 0 ? hProperties : undefined;+}++function isSafeHtmlImageSrc(src: string): boolean {+ return (+ SAFE_HTML_IMAGE_SRC_RE.test(src) ||+ src.startsWith('xdt-image://') ||+ src.startsWith('cindy-media://') ||+ src.startsWith('xdt-file://') ||+ src.startsWith('cindy-remote-media://')+ );+}++export function htmlImgToImageNode(node: Html): Image | null {+ const match = node.value.match(IMG_TAG_RE);+ if (!match) return null;++ const attrs = parseAttributes(match[1]);+ const src = attrs.get('src')?.trim();+ if (!src || !isSafeHtmlImageSrc(src)) return null;++ const image: Image = {+ type: 'image',+ url: src,+ alt: attrs.get('alt') ?? '',+ title: attrs.get('title') || null,+ position: node.position,+ };+ const hProperties = hPropertiesFromAttrs(attrs);+ if (hProperties) {+ image.data = { hProperties };+ }+ return image;+}diff --git a/apps/desktop/src/shared/markdownPreviewText.ts b/apps/desktop/src/shared/markdownPreviewText.tsnew file mode 100644index 0000000000..66d4e79edd--- /dev/null+++ b/apps/desktop/src/shared/markdownPreviewText.ts@@ -0,0 +1,45 @@+import { Lexer, type Token, type Tokens } from 'marked';++import { htmlImgToImageNode } from './htmlImage';++/** Extract display text without generating HTML or counting link destinations. */+export function markdownPreviewText(markdown: string): string {+ return previewTokens(Lexer.lex(markdown, { gfm: true }))+ .replace(/\s+/g, ' ')+ .trim();+}++function previewTokens(tokens: Token[]): string {+ return tokens+ .map((token): string => {+ switch (token.type) {+ case 'space':+ case 'br':+ case 'hr':+ case 'def':+ return ' ';+ case 'html':+ return `${htmlImgToImageNode({ type: 'html', value: token.text })?.alt ?? ''} `;+ case 'list':+ return `${token.items.map((item: Tokens.ListItem) => previewTokens(item.tokens)).join(' ')} `;+ case 'table':+ return (+ [token.header, ...token.rows]+ .map((row: { tokens: Token[] }[]) =>+ row.map((cell) => previewTokens(cell.tokens)).join(' '),+ )+ .join(' ') + ' '+ );+ case 'heading':+ case 'paragraph':+ case 'blockquote':+ return `${previewTokens(token.tokens ?? [])} `;+ case 'code':+ return `${token.text} `;+ default:+ if ('tokens' in token && token.tokens) return previewTokens(token.tokens);+ return 'text' in token ? token.text : '';+ }+ })+ .join('');+}