From 48f0c12fd22e8ab81795438204f589cb5faa8759 Mon Sep 17 00:00:00 2001 From: govin Date: Thu, 24 Sep 2026 11:25:18 +0800 Subject: [PATCH] frontend: let the writer set a figure's size in the editor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Figures come out of a plotting tool at whatever size they were made. On the paper this was written for, the sixteen of them are 1441, 1857, 2409 and 4169 pixels wide — every one wider than the 1276px column — so with no size they all printed at the full width, and the near-square ones (1857×1986, 1974×2068) took 1365px of height, a page each. Measured in the browser, all sixteen came out at exactly 1276px: not one of them was the size its author wanted. `{width=…}` has been in the syntax all along, so this is the control that was missing, not the feature. A row that is a figure now carries 宽度 in its header: 25/50/70/100%, or any value typed in — the size a panel wants is what it measures, not a round number — with 原尺寸 as the empty value. Beside it, what the picture will measure on the page (`原图 1857×1986 · 显示 893×955`), worked out against the column actually rendered behind the dialog, which is the number the writer is deciding with. Two rules keep it honest. The value goes through `parseImageWidth` — the same function that parses the attribute when the paper is printed — so what the control shows is what will be printed, and a value it cannot read is refused with the forms that work instead of stored as a size that quietly does nothing. And the attribute is written into the sentence content by `withImageWidth`, which edits only the first picture: the control is offered for a figure, and a sentence with words around its picture is not one. Reading the size back out of the content rather than keeping a copy of it in the draft means there is one place it can be wrong instead of two. `check-image.mjs` grows from 15 checks to 24, driving the real control: that only figure rows offer one, that it shows what each is set to, that typing 30% converts to 383×239 immediately, that what was typed is what gets stored, that the paper then prints it at 30% of the column, that clearing it goes back to the natural 480×300, and that "宽一点" is refused while the sentence keeps its size. The MCP side of the same rule was wrong and is fixed with it: `image_upload(width= "60")` wrote `{width=60px}`, and the reader takes a bare number as a share of the column — `parseImageWidth` only reads pixels when the value says `px`. A model asking for 60% got a 60-pixel figure. v7 is deployed with the corrected reading, and smoke_mcp.py checks it. --- backend/app/mcp/tools/images.py | 19 +- backend/scripts/smoke_mcp.py | 8 + deploy/README.md | 6 +- deploy/k8s/10-paper-doc-mcp.yaml | 6 +- docs/MCP.md | 6 + docs/OVERVIEW.md | 18 +- frontend/scripts/check-image.mjs | 97 ++++++++++ .../components/papers/ParagraphEditDialog.vue | 176 +++++++++++++++++- frontend/src/utils/rich.ts | 33 ++++ 9 files changed, 357 insertions(+), 12 deletions(-) diff --git a/backend/app/mcp/tools/images.py b/backend/app/mcp/tools/images.py index e9c2322..765b9e2 100644 --- a/backend/app/mcp/tools/images.py +++ b/backend/app/mcp/tools/images.py @@ -63,7 +63,8 @@ def register(server: MCPServer) -> None: str | None, Field( description=( - "可选宽度:70%(占栏宽)或 400px。不传则按原尺寸,最大不超过栏宽" + "可选宽度:70%(占栏宽)或 400px;只写数字按百分比算。" + "不传则按原尺寸,最大不超过栏宽" ) ), ] = None, @@ -169,6 +170,12 @@ def _width_attribute(width: str | None) -> str: Tolerant about how it is written — ``70%``, ``70 %``, ``{width=70%}`` and ``w=400px`` all mean the same thing, which is what a model repeats back from a sentence it read — and strict about what it means. + + A bare number is a **percentage**, because that is what the reader makes of + one: ``parseImageWidth`` only takes a value as pixels when it is written + ``px``, and treats everything else as a share of the column. ``400`` is + therefore out of range and refused with the two forms that work, rather than + written as ``400px`` and printed at a third of the page. """ if width is None or not str(width).strip(): return "" @@ -181,10 +188,16 @@ def _width_attribute(width: str | None) -> str: "不写则按原尺寸显示(最多不超过栏宽)" ) - digits, unit = int(match.group(1)), (match.group(2) or "px").lower() + digits = int(match.group(1)) + unit = (match.group(2) or "%").lower() limit = _MAX_PERCENT if unit == "%" else _MAX_PIXELS if not 1 <= digits <= limit: - s.fail(f"width 的 {unit} 值要在 1 到 {limit} 之间,收到的是“{width}”") + # The pointer to pixels only helps when the caller wrote a bare number: + # "150%" is already written as a percentage and does not want advice. + hint = f"像素要写成 “{digits}px”" if match.group(2) is None else "" + s.fail( + f"width 的 {unit} 值要在 1 到 {limit} 之间,收到的是“{width}”。{hint}" + ) return f"{{width={digits}{unit}}}" diff --git a/backend/scripts/smoke_mcp.py b/backend/scripts/smoke_mcp.py index 3b9d5ac..c0a9e6e 100644 --- a/backend/scripts/smoke_mcp.py +++ b/backend/scripts/smoke_mcp.py @@ -1037,6 +1037,14 @@ async def _run(url: str | None = None, token: str | None = None) -> int: tolerant["markdown"] == f"![写法宽容](/api/images/{tolerant['key']}){{width=400px}}", tolerant["markdown"], ) + bare = await call( + session, "image_upload", data_base64=GIF_1PX_BASE64, caption="只写数字", width="60" + ) + check( + "a bare number means a share of the column, as it does in the page", + bare["markdown"] == f"![只写数字](/api/images/{bare['key']}){{width=60%}}", + bare["markdown"], + ) message = await expect_error( session, "image_upload", data_base64=GIF_1PX_BASE64, width="70em" ) diff --git a/deploy/README.md b/deploy/README.md index 6edcdee..98ee234 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -18,11 +18,11 @@ paper-doc 的 MCP 服务跑在 k3s 里,命名空间 **`paper-doc`**,客户 | Secret | `paper-doc-secrets` | `DB_USER` / `DB_PASSWORD` / `MCP_HTTP_TOKEN` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` | | Secret | `aliyun-acr` | 镜像仓库拉取凭证(从 `default` 复制) | -镜像:`registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v6` -(`sha256:c89c0ba250c872dec45e6e5ce056dcf1f73c5415f55aa8b05216ce785ae28732`; +镜像:`registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v7` +(`sha256:f55a0d4e5ac790b78aaeb95a58034a28266e33282a379a2e1e8ffa10c191f611`; `kubectl -n paper-doc get pods -o jsonpath='{.items[0].status.containerStatuses[0].imageID}'` 对得上,才说明跑的就是 ACR 上那一版。历史:v1 首发布 → v2 重命名表 → v3 参考文献库 → -v4 补参考文献 MCP 工具 → v5 换行与参考文献表 → **v6 插图与公式对齐**。) +v4 补参考文献 MCP 工具 → v5 换行与参考文献表 → v6 插图与公式对齐 → **v7 插图的宽度写法与页面一致**。) **数据库**:TiDB 已经在这个集群里,Deployment 用集群内的 Service `tidb-tidb.tidb:4000`,而不是宿主机用的 NodePort `192.168.1.88:32738`。 diff --git a/deploy/k8s/10-paper-doc-mcp.yaml b/deploy/k8s/10-paper-doc-mcp.yaml index 2954196..e28d2b8 100644 --- a/deploy/k8s/10-paper-doc-mcp.yaml +++ b/deploy/k8s/10-paper-doc-mcp.yaml @@ -75,7 +75,7 @@ spec: type: RuntimeDefault containers: - name: mcp - image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v6 + image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v7 imagePullPolicy: IfNotPresent ports: - name: http @@ -199,14 +199,14 @@ spec: # imagePullSecrets: [{name: aliyun-acr}] # initContainers: # - name: migrate -# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v6 +# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v7 # command: ["alembic", "upgrade", "head"] # envFrom: [{configMapRef: {name: paper-doc-config}}] # env: [...] # the same secret keys as above; the MinIO # # pair is what lets the API serve the figures # containers: # - name: api -# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v6 +# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v7 # command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] # ports: [{name: http, containerPort: 8000}] # envFrom: [{configMapRef: {name: paper-doc-config}}] diff --git a/docs/MCP.md b/docs/MCP.md index cc85003..1d4da4d 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -471,6 +471,12 @@ Header: Authorization: Bearer `width` 写法宽容(`70%`、`70 %`、`{width=70%}`、`w=400px` 都收),含义严格:像素 1–4000、百分比 1–100, 超出会被拒绝而不是默默忽略——网页端读不懂的尺寸会退回原尺寸,那等于写了个不生效的值。 +**只写数字按百分比算**(`60` = `60%`),和网页端一致:只有写成 `px` 才算像素,因为这是 +`frontend/src/utils/rich.ts` 里 `parseImageWidth` 的读法,页面和工具必须读同一种。 + +同一个大小在网页端也能改:段落编辑器里,凡是"整句只有一张图"的行都会出现「宽度」下拉框, +可以选 25/50/70/100%,也可以直接填任意值(如 `63%`、`380px`),旁边实时显示这会在版面上 +占多大(如 `原图 1857×1986 · 显示 893×955`)。 存储没配好(缺 `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY`)时,这个工具报 503 语义的说明, **写作路径照常**:论文、段落、句子、模板、文献都不碰对象存储。 diff --git a/docs/OVERVIEW.md b/docs/OVERVIEW.md index fbf1133..a8fdd26 100644 --- a/docs/OVERVIEW.md +++ b/docs/OVERVIEW.md @@ -413,7 +413,23 @@ line": The size is optional and comes from pandoc's attribute form — `{width=70%}`, `{width=400px}` — and is validated to digits plus one unit before it becomes a -CSS length, so no second declaration can be smuggled through it. +CSS length, so no second declaration can be smuggled through it. A bare number +is a **share of the column**, because `parseImageWidth` only reads a value as +pixels when it says `px`; the MCP tool that writes the same attribute follows +that rule rather than inventing its own. + +Leaving the size off means the picture prints at its own width, capped to the +column — and that turned out to be the wrong default to *live* with. Figures +come out of a plotting tool at whatever size they were made: one paper's are +1441, 1857, 2409 and 4169 pixels wide, so every one of them is wider than the +1276px column and they all printed at the full width, with the near-square ones +(1857×1986, 1974×2068) filling a whole page at 1365px tall. A written size is +therefore part of the editor: a row that is a figure carries a 宽度 control — +presets, or any value typed in — and beside it what the picture will measure on +the page (`原图 1857×1986 · 显示 893×955`), measured against the real column +behind the dialog. The control writes the attribute through the reader's own +`parseImageWidth`, so what it shows is what gets printed, and a value that +function cannot read is refused instead of stored as a size that does nothing. Configuration is three variables (`MINIO_ENDPOINT`, `MINIO_ACCESS_KEY`, `MINIO_SECRET_KEY`, plus `MINIO_BUCKET`). Left empty, the paper still writes and diff --git a/frontend/scripts/check-image.mjs b/frontend/scripts/check-image.mjs index 6222341..60fe07e 100644 --- a/frontend/scripts/check-image.mjs +++ b/frontend/scripts/check-image.mjs @@ -268,6 +268,103 @@ try { check('the inserted figure is in the paper', saved.count === 2, JSON.stringify(saved)) check('and it is the one that was uploaded', saved.captions.includes('第二张图'), saved.captions.join()) check('both pictures decoded', saved.decoded.every((width) => width === 480), saved.decoded.join()) + + // --- the figure's size, set from the editor ------------------------------ + // + // Figures come out of the plotting tool at whatever size they were made — + // one paper's are 1441, 2400 and 4169 pixels wide — and every one of them can + // be wider than the column, so with no size they all print at the full column + // and a near-square panel fills a page. This control is the answer to that, + // and what has to hold is that what it writes is what the reader prints. + await page.locator('.paragraph-actions button:has-text("编辑")').first().click() + await page.waitForSelector('.editor .rows', { timeout: 15000 }) + await page.waitForSelector('.width-select') + // The hint divides the column by the picture's own size, so it needs the + // thumbnail to have decoded first. + await page.waitForFunction( + () => document.querySelector('.size-hint')?.textContent?.includes('原图'), + { timeout: 15000 }, + ) + + // What each select is showing: Element Plus prints the chosen label in its + // own element, not as the value of the input the writer types into. + const controls = await page.evaluate(() => + [...document.querySelectorAll('.width-select')].map((node) => + (node.querySelector('.el-select__selected-item')?.textContent ?? '').trim() || + (node.querySelector('.el-select__placeholder')?.textContent ?? '').trim(), + ), + ) + check('only a figure row offers a size', controls.length === 2, JSON.stringify(controls)) + check( + 'and each one shows the size it is set to', + controls[0] === '50%' && controls[1] !== '50%', + JSON.stringify(controls), + ) + + const hint = async () => + (await page.locator('.size-hint').first().innerText()).replace(/\s+/g, ' ') + check( + 'the hint says what it will measure on the page', + /显示 638×399/.test(await hint()), + await hint(), + ) + + // Typing a value that is not one of the presets is the point of the control: + // the size a panel wants is what it measures, not a round number. + await page.locator('.width-select input').first().fill('30%') + await page.keyboard.press('Enter') + await page.waitForTimeout(400) + check('typing 30% converts immediately', /显示 383×239/.test(await hint()), await hint()) + + await page.getByRole('button', { name: '保存段落' }).click() + await page.waitForSelector('.el-dialog', { state: 'detached', timeout: 15000 }) + await page.waitForTimeout(700) + + const stored = await api('GET', `/papers/${paperId}/paragraphs/${sort}`) + const sized = stored.paragraph.sentences.find((sentence) => + sentence.content.includes('试验装置示意图'), + ) + check('what was typed is what is stored', sized?.content.endsWith('{width=30%}'), sized?.content) + + const shrunk = await page.evaluate(() => { + const body = document.querySelector('.paragraph-body') + const column = Math.round(body.getBoundingClientRect().width) + const figure = [...document.querySelectorAll('.sentence--figure')].find( + (node) => node.querySelector('.figure-caption')?.textContent.trim() === '试验装置示意图', + ) + const box = figure.querySelector('img').getBoundingClientRect() + return { column, width: Math.round(box.width), height: Math.round(box.height) } + }) + check( + 'and the paper prints it at that size', + Math.abs(shrunk.width - shrunk.column * 0.3) <= 2, + `${shrunk.width} vs ${shrunk.column * 0.3}`, + ) + + // Taking the size off again: 原尺寸, which is what the placeholder promises. + await page.locator('.paragraph-actions button:has-text("编辑")').first().click() + await page.waitForSelector('.width-select', { timeout: 15000 }) + await page.waitForFunction( + () => document.querySelector('.size-hint')?.textContent?.includes('原图'), + { timeout: 15000 }, + ) + await page.locator('.width-select').first().hover() + await page.locator('.width-select .el-select__clear').first().click({ force: true }) + await page.waitForTimeout(300) + check('clearing it goes back to the natural size', /显示 480×300/.test(await hint()), await hint()) + + // A size the reader cannot read is refused rather than stored: a figure that + // quietly prints at its natural size is the bug this control exists to fix. + await page.locator('.width-select input').first().fill('宽一点') + await page.keyboard.press('Enter') + await page.waitForTimeout(400) + check( + 'a size that is not one is refused', + await page.evaluate(() => Boolean(document.querySelector('.el-message--warning'))), + ) + check('and the sentence keeps the size it had', /显示 480×300/.test(await hint()), await hint()) + await page.getByRole('button', { name: '取消' }).click() + await page.waitForSelector('.el-dialog', { state: 'detached', timeout: 15000 }) } finally { await browser.close() if (paperId) { diff --git a/frontend/src/components/papers/ParagraphEditDialog.vue b/frontend/src/components/papers/ParagraphEditDialog.vue index abe0d38..f9f8af0 100644 --- a/frontend/src/components/papers/ParagraphEditDialog.vue +++ b/frontend/src/components/papers/ParagraphEditDialog.vue @@ -46,7 +46,14 @@ import { type SentenceInput, } from '@/api/papers' import { PARAGRAPH_UNSET_LABEL, foldWhitespace } from '@/utils/format' -import { hasDisplayMath, imagesOf, type ImageSegment } from '@/utils/rich' +import { + figureOf, + hasDisplayMath, + imagesOf, + parseImageWidth, + withImageWidth, + type ImageSegment, +} from '@/utils/rich' const props = defineProps<{ /** Visibility, used with `v-model`. */ @@ -82,6 +89,15 @@ interface SentenceDraft { /** How a display formula in this sentence is set. */ align: FormulaAlign citations: CitationDraft[] + /** + * The natural size of the row's first picture, once it has decoded. + * + * Measured from the loaded thumbnail rather than stored: it is a property of + * the file, and the editor's job here is to tell the writer what 50% of *this* + * picture would come to, which cannot be guessed from the Markdown. + */ + naturalWidth: number | null + naturalHeight: number | null } const visible = computed({ @@ -154,6 +170,8 @@ watch( reference_id: citation.reference_id, quote: citation.quote, })), + naturalWidth: null, + naturalHeight: null, })) } catch (error) { ElMessage.error(errorMessage(error)) @@ -177,6 +195,8 @@ function addSentence(): void { lineBreak: false, align: 'center', citations: [], + naturalWidth: null, + naturalHeight: null, }) } @@ -189,6 +209,97 @@ function rowImages(row: SentenceDraft): ImageSegment[] { return imagesOf(row.content) } +// --- how wide a figure prints --------------------------------------------- + +/** The sizes the select offers; anything else is typed into it. */ +const WIDTH_PRESETS = ['25%', '50%', '70%', '100%'] + +/** + * The size a row's figure prints at, as the reader parsed it. + * + * Read from the content, never stored beside it: `{width=70%}` *is* the size, + * and a second copy of it in the draft is a second thing that can be wrong. + * A row that holds no figure, or one whose attribute the reader would not + * accept, answers `null` — which is what "原尺寸" means. + */ +function figureWidth(row: SentenceDraft): string | null { + return figureOf(row.content)?.width ?? null +} + +/** Remember a picture's own size, so the hint below can do the arithmetic. */ +function rememberNatural(row: SentenceDraft, event: Event): void { + const image = event.target as HTMLImageElement + row.naturalWidth = image.naturalWidth || null + row.naturalHeight = image.naturalHeight || null +} + +/** + * The column the paper prints in, measured from the page behind the dialog. + * + * A percentage is a share of *that*, so without it the editor could only say + * "70%" and leave the writer to find out how tall that is. Falls back to + * `null`, and the hint then says nothing rather than something invented. + */ +function paperColumn(): number | null { + const body = document.querySelector('.paragraph-body') + const width = body?.getBoundingClientRect().width ?? 0 + return width > 0 ? Math.round(width) : null +} + +/** + * What a row's figure will measure on the page — `893×955` — or `null`. + * + * This is the number the writer actually needs. A paper's figures come out of + * the plotting tool at whatever size they were made — a 4169-pixel panel and a + * 1296-pixel one — and both are wider than the column, so without a size they + * all print at the full column and a near-square one fills a whole page. + * Measured on this paper's column: 1276px wide, and 图12 (1857×1986) would come + * out 1365px tall at 原尺寸 against 955px at 70%. + */ +function drawnSize(row: SentenceDraft): string | null { + const { naturalWidth, naturalHeight } = row + if (!naturalWidth || !naturalHeight) return null + + const width = figureWidth(row) + let pixels: number | null = null + if (!width) { + // No size: the picture prints at its own unless the column is narrower. + const column = paperColumn() + pixels = column ? Math.min(naturalWidth, column) : naturalWidth + } else if (width.endsWith('%')) { + const column = paperColumn() + pixels = column ? Math.round((column * Number.parseFloat(width)) / 100) : null + } else { + pixels = Number.parseInt(width, 10) + } + if (!pixels) return null + + return `${pixels}×${Math.round((pixels * naturalHeight) / naturalWidth)}` +} + +/** + * Apply what the writer chose, or said, to the row's figure. + * + * The value goes through the same `parseImageWidth` the reader uses, so what is + * written into the sentence is exactly what will be printed; a value it cannot + * read is refused here with the two forms that work, rather than stored as a + * size that quietly does not apply. + */ +function onWidthChange(row: SentenceDraft, value: string | null | undefined): void { + const text = (value ?? '').trim() + if (!text) { + row.content = withImageWidth(row.content, null) + return + } + + const parsed = parseImageWidth(`{width=${text}}`) + if (!parsed) { + ElMessage.warning('宽度填百分比或像素:70%、60 或 400px(百分比 1–100,像素 1–4000)') + return + } + row.content = withImageWidth(row.content, parsed) +} + // --- images --------------------------------------------------------------- /** The hidden file picker the 「插入图片」 button drives. */ @@ -240,6 +351,8 @@ async function insertImages(files: File[]): Promise { lineBreak: true, align: 'center', citations: [], + naturalWidth: null, + naturalHeight: null, }) } catch (error) { ElMessage.error(errorMessage(error)) @@ -500,6 +613,45 @@ async function submit(): Promise { :label="option.label" /> + + + +
{ right paragraph. -->
- + +
{{ image.alt || '方括号里写的就是图注' }}
@@ -699,6 +859,18 @@ async function submit(): Promise { width: 112px; } +.width-select { + width: 118px; +} + +/* What the figure will measure on the page: a number the writer acts on, so it + sits beside the control rather than in a tooltip nobody opens. */ +.size-hint { + font-size: 12px; + color: var(--el-text-color-secondary); + white-space: nowrap; +} + .citations { display: flex; flex-direction: column; diff --git a/frontend/src/utils/rich.ts b/frontend/src/utils/rich.ts index 70976bf..7e8f5c0 100644 --- a/frontend/src/utils/rich.ts +++ b/frontend/src/utils/rich.ts @@ -103,6 +103,39 @@ export function parseImageWidth(attributes: string | undefined): string | null { return value >= 1 && value <= 100 ? `${value}%` : null } +/** + * The image alternative on its own, with its parts captured separately. + * + * Written out rather than reused from `RICH_PATTERN` because this one *rebuilds* + * the markup: a replace over the combined pattern would have to reconstruct the + * groups of formulas it never touched, and a mis-copied group is a sentence the + * writer did not write. It has to keep matching what that pattern calls an + * image — the alternative is the first one there, for the same reason (`![` is + * not how a formula starts). + */ +const IMAGE_AT = /!\[([^\]]*)\]\(([^()\s]+)(?:\s+"([^"]*)")?\)(?:\{([^}]*)\})?/ + +/** + * Write a size onto the picture a sentence holds — or take it off again. + * + * Only the first picture is touched. The control that calls this is offered for + * a *figure* (a sentence holding nothing but one image), and a sentence with + * words around its picture is a different thing that this must not silently + * resize. + * + * `width` is what `parseImageWidth` returned — already canonical, e.g. `70%` or + * `400px` — or `null` for "leave it at its natural size". + */ +export function withImageWidth(content: string, width: string | null): string { + let replaced = false + return content.replace(IMAGE_AT, (whole, alt: string, src: string, title?: string) => { + if (replaced) return whole + replaced = true + const name = title === undefined ? '' : ` "${title}"` + return `![${alt}](${src}${name})${width ? `{width=${width}}` : ''}` + }) +} + /** Split a sentence into its plain, mathematical and pictorial parts. */ export function splitRich(content: string): RichSegment[] { const segments: RichSegment[] = []