frontend: let the writer set a figure's size in the editor

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.
This commit is contained in:
2026-09-24 11:25:18 +08:00
parent 9e6a1f8c3e
commit 48f0c12fd2
9 changed files with 357 additions and 12 deletions
+16 -3
View File
@@ -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}}}"
+8
View File
@@ -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"
)
+3 -3
View File
@@ -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`。
+3 -3
View File
@@ -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}}]
+6
View File
@@ -471,6 +471,12 @@ Header: Authorization: Bearer <MCP_HTTP_TOKEN>
`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 语义的说明,
**写作路径照常**:论文、段落、句子、模板、文献都不碰对象存储。
+17 -1
View File
@@ -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
+97
View File
@@ -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) {
@@ -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<void> {
lineBreak: true,
align: 'center',
citations: [],
naturalWidth: null,
naturalHeight: null,
})
} catch (error) {
ElMessage.error(errorMessage(error))
@@ -500,6 +613,45 @@ async function submit(): Promise<void> {
:label="option.label"
/>
</el-select>
<!-- A figure's size. Only a sentence that is nothing but a picture
prints as a 插图, and only that one has a size worth setting:
an image inside a sentence belongs to the line it sits in.
Typing is allowed as well as the presets, because the size that
suits a panel is whatever it measures, not a round number. -->
<template v-if="figureOf(row.content)">
<el-select
:model-value="figureWidth(row) ?? ''"
size="small"
class="width-select"
placeholder="原尺寸"
clearable
filterable
allow-create
default-first-option
@change="onWidthChange(row, $event)"
>
<el-option
v-for="preset in WIDTH_PRESETS"
:key="preset"
:value="preset"
:label="preset"
/>
</el-select>
<el-tooltip
content="图片在版面上的实际大小(宽×高)。不填就是原尺寸,最多不超过栏宽。"
placement="top"
:show-after="300"
>
<span class="size-hint">
<template v-if="row.naturalWidth">
原图 {{ row.naturalWidth }}×{{ row.naturalHeight }}
</template>
<template v-if="drawnSize(row)">· 显示 {{ drawnSize(row) }}</template>
</span>
</el-tooltip>
</template>
<div class="toolbar-spacer" />
<el-button
link
@@ -530,7 +682,15 @@ async function submit(): Promise<void> {
right paragraph. -->
<div class="row-images">
<figure v-for="image in rowImages(row)" :key="image.src" class="row-image">
<img :src="image.src" :alt="image.alt" loading="lazy" />
<!-- Thumbnails are identification, not a preview of the printed
size — they are a fixed 168px box, and the size control above
says what the figure will actually measure. -->
<img
:src="image.src"
:alt="image.alt"
loading="lazy"
@load="rememberNatural(row, $event)"
/>
<figcaption>{{ image.alt || '方括号里写的就是图注' }}</figcaption>
</figure>
</div>
@@ -699,6 +859,18 @@ async function submit(): Promise<void> {
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;
+33
View File
@@ -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[] = []