A local-first multi-agent app development platform, built on PenguinHarness
Unify how settings panels mark required and optional fields (#396)
Yaowei Zheng2db912e47db8
diff --git a/changelog/unreleased/2026-08-21-settings-disclosure.md b/changelog/unreleased/2026-08-21-settings-disclosure.mdindex b17b1aa7..3c56d1fd 100644--- a/changelog/unreleased/2026-08-21-settings-disclosure.md+++ b/changelog/unreleased/2026-08-21-settings-disclosure.md@@ -16,8 +16,7 @@ and only what shapes a value stays on screen.- The security-policy page opened with a five-sentence paragraph covering both shell entrypoints, the fixed denial text the model receives, the matching algorithm and the evasion- caveat. It was cut to two sentences behind a "?" on the page heading; the rule editor- keeps its visible "Regular expression" placeholder.+ caveat. It was cut to two sentences behind a "?" on the page heading.- The dialog's pane heading gained an optional explanation slot, so any of its pages cancarry one.- On the same page, adding a rule opened its form below every existing rule. The factorydiff --git a/changelog/unreleased/2026-08-21-settings-disclosure.zh.md b/changelog/unreleased/2026-08-21-settings-disclosure.zh.mdindex 88dbc102..fa76c20a 100644--- a/changelog/unreleased/2026-08-21-settings-disclosure.zh.md+++ b/changelog/unreleased/2026-08-21-settings-disclosure.zh.md@@ -13,8 +13,7 @@## Project 设置- 安全策略页开头是一段五句话的说明,涵盖模型接触 shell 的两条路径、模型收到的固定拒绝文案、- 匹配算法以及绕过的边界。该段被压缩为两句并收进页面标题旁的问号;规则编辑器仍保留可见的- 「正则表达式」占位符。+ 匹配算法以及绕过的边界。该段被压缩为两句并收进页面标题旁的问号。- 该对话框的页面标题新增可选说明位,其余页面也可以挂载说明。- 同一页面上,新增规则时表单开在所有已有规则之下。仅出厂规则就已让列表高过对话框的滚动区,表单因此落在可视范围之外,点击看起来毫无反应。现在表单直接开在「新增规则」按钮下方,光标diff --git a/changelog/unreleased/2026-08-21-settings-field-markers.md b/changelog/unreleased/2026-08-21-settings-field-markers.mdnew file mode 100644index 00000000..33bab1ca--- /dev/null+++ b/changelog/unreleased/2026-08-21-settings-field-markers.md@@ -0,0 +1,44 @@+# One way to mark a required field++- **Date:** 2026-08-21+- **Type:** refactor+- **Scope:** `web`+- **PR:** [#396](https://github.com/Prism-Shadow/penguin-harness/pull/396)++[中文版](2026-08-21-settings-field-markers.zh.md)++Settings panels marked mandatory fields three different ways: a red `*`, the word "optional"+appended to the neighbouring label, or nothing at all. They now follow one rule — **a required+field carries the red `*`, an optional field carries no mark, and no label or placeholder says+"optional"**. Explanations that had been folded into a label moved out of it, following the split+[the disclosure pass](2026-08-21-settings-disclosure.md) set: what shapes a value stays visible as+the field's hint.++## Marks that did not match the behaviour++- **Upload limits** (System settings): both the per-attachment and the per-message MB fields are+ refused when empty, and neither was marked. Both now carry the `*`.+- **Add a memory** (Agent settings → Memory): the content field gates both actions of the dialog+ and was not marked. It now carries the `*`.++## Labels that carried their own marker++- **Security policy** (Project settings): the rule editor identified its three fields by+ placeholder alone, so the only sign that a name and a pattern are mandatory was the word+ "optional" on the description. All three now have real labels, and the two mandatory ones carry+ the `*`.+- **New Project**: the display name read "Display name (optional, defaults to the Project id)".+ The label is now just the name, and the fallback is a hint below the field — the same way the+ Create agent dialog has always spelled it.+- **Schedules** (Agent settings): "End at (optional)" and "Workspace (optional; a temporary+ workspace is created when empty)" lost the wording; the workspace fallback became a visible+ hint, sharing one string with the identical field in Project settings → Defaults.++## One asterisk++The mark had been re-typed by hand in four places, one of which had dropped its dark-mode ink and+so rendered duller than every other copy in dark mode. It is now a single `RequiredMark`, which the+models add-group and model dialogs use through `FieldLabel` for their custom label rows, and which+the trace viewer's tool-schema table uses for required properties. The mark is `aria-hidden` beside+a control, which announces `aria-required` instead; the schema table has no control, so it passes a+label and the mark speaks for itself.diff --git a/changelog/unreleased/2026-08-21-settings-field-markers.zh.md b/changelog/unreleased/2026-08-21-settings-field-markers.zh.mdnew file mode 100644index 00000000..290d2639--- /dev/null+++ b/changelog/unreleased/2026-08-21-settings-field-markers.zh.md@@ -0,0 +1,37 @@+# 必填只有一种标法++- **Date:** 2026-08-21+- **Type:** refactor+- **Scope:** `web`+- **PR:** [#396](https://github.com/Prism-Shadow/penguin-harness/pull/396)++[English](2026-08-21-settings-field-markers.md)++设置面板此前用三种方式标注必填:红色星号、在旁边的标签里补一个「可选」、或者什么都不标。现统一+为一条规则——**必填字段带红色星号,可选字段不带任何标记,标签与占位符都不写「可选」**。被塞进标+签的解释文字随之移出,沿用[解释文字收进问号](2026-08-21-settings-disclosure.zh.md)那一批定下的+分工:决定取值形态的文字留在字段的可见提示里。++## 标记与实际行为不符++- **上传限制**(系统设置):单个附件与单条消息两个 MB 字段留空都会被拒绝保存,此前均未标记,现+ 在都带上星号。+- **添加记忆**(Agent 设置 → 记忆):内容字段决定该弹窗两个按钮是否可用,此前未标记,现在带上+ 星号。++## 标签里自带标记++- **安全策略**(Project 设置):规则编辑器的三个字段仅靠占位符区分,于是「名称」与「正则表达+ 式」必填的唯一线索,就是「描述」上的那两个字。三个字段现在都有真正的标签,两个必填项带星号。+- **新建 Project**:显示名此前写作「显示名(可选,缺省为 Project id)」。标签现在只留名称,缺省+ 规则改为字段下方的提示——与「创建 Agent」对话框一贯的写法一致。+- **定时任务**(Agent 设置):「结束时间(可选)」与「Workspace(可选,留空自动创建临时工作+ 区)」去掉了这两个字;Workspace 的缺省说明改为可见提示,与 Project 设置 → 默认值中的同一字段+ 共用同一条文案。++## 只有一个星号++这个标记此前被手写了四份,其中一份漏掉了暗色模式的墨色,在暗色下比其他副本更暗淡。现在统一为+一个 `RequiredMark`:模型页的新建分组与模型对话框中的自定义标签行经由 `FieldLabel` 使用它,Trace+查看器的工具 schema 表格也用它标注必填属性。控件旁的标记是 `aria-hidden`,由控件的 `aria-required`+负责播报;schema 表格没有控件,因此传入 label,由标记自己说明。diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsxindex afd9cb92..1916c2d3 100644--- a/packages/web/src/components/layout/project-dialogs.tsx+++ b/packages/web/src/components/layout/project-dialogs.tsx@@ -164,7 +164,8 @@ export function CreateProjectDialog({/>)}<Input- label={S.project.name}+ label={S.project.displayName}+ hint={S.project.displayNameHint}size="sm"value={name}onChange={(e) => setName(e.target.value)}@@ -777,7 +778,7 @@ function ChatDefaultsSection({ projectId, isOwner }: { projectId: string; isOwneonChange={setWorkspace}variant="form"/>- <FieldHint>{S.project.chatDefaultsWorkspaceHint}</FieldHint>+ <FieldHint>{S.chat.workspaceHintShort}</FieldHint></div></div><div className="mt-3 flex justify-end">@@ -859,9 +860,10 @@ export function RuleEditor({const apply = () => {const n = name.trim();- if (!n || !pattern) return;+ const p = pattern.trim();+ if (!n || !p) return;try {- new RegExp(pattern);+ new RegExp(p);} catch {setErr(S.project.commandPolicyInvalidPattern);return;@@ -869,7 +871,7 @@ export function RuleEditor({const d = desc.trim();onApply({name: n,- pattern,+ pattern: p,...(d !== "" ? { description: d } : {}),enabled: initial?.enabled ?? true,});@@ -877,49 +879,56 @@ export function RuleEditor({return (<div className="space-y-2 py-3">+ {/* Name and pattern are both mandatory — Apply stays disabled without either — and the red+ "*" is what says so; the description carries no mark because it is optional. The flex+ sizing sits on the wrappers because a labelled Input renders its own <label> block+ around the control, so the control itself is not the flex item. */}<div className="flex flex-col gap-2 sm:flex-row">- <Input- size="sm"- className="sm:w-40"- placeholder={S.project.commandPolicyRuleName}- value={name}- maxLength={64}- // The editor mounts only on an explicit Add / Edit click, so taking focus is what- // that click asked for: it puts the caret in the first field for a keyboard user,- // and the browser's scroll-on-focus keeps the form in view on a short viewport.- autoFocus- onChange={(e) => setName(e.target.value)}- />- <Input- size="sm"- className="min-w-0 flex-1 font-mono"- placeholder={S.project.commandPolicyRulePattern}- value={pattern}- maxLength={512}- invalid={Boolean(err)}- onChange={(e) => {- setPattern(e.target.value);- if (err) setErr(undefined);- }}- onKeyDown={(e) => {- if (e.key === "Enter") apply();- }}- />+ <div className="sm:w-40">+ <Input+ size="sm"+ label={S.project.commandPolicyRuleName}+ required+ value={name}+ maxLength={64}+ // The editor mounts only on an explicit Add / Edit click, so taking focus is what+ // that click asked for: it puts the caret in the first field for a keyboard user,+ // and the browser's scroll-on-focus keeps the form in view on a short viewport.+ autoFocus+ onChange={(e) => setName(e.target.value)}+ />+ </div>+ <div className="min-w-0 flex-1">+ <Input+ size="sm"+ className="font-mono"+ label={S.project.commandPolicyRulePattern}+ required+ value={pattern}+ maxLength={512}+ {...(err !== undefined ? { error: err } : {})}+ onChange={(e) => {+ setPattern(e.target.value);+ if (err) setErr(undefined);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") apply();+ }}+ />+ </div></div><Inputsize="sm"- className="w-full"- placeholder={S.project.commandPolicyRuleDesc}+ label={S.project.commandPolicyRuleDesc}value={desc}maxLength={300}onChange={(e) => setDesc(e.target.value)}/>- {err !== undefined && <FieldError>{err}</FieldError>}<div className="flex justify-end gap-2"><Button size="sm" variant="ghost" onClick={onCancel}>{S.common.cancel}</Button>- <Button size="sm" disabled={!name.trim() || !pattern} onClick={apply}>+ <Button size="sm" disabled={!name.trim() || !pattern.trim()} onClick={apply}>{S.project.commandPolicyApplyRule}</Button></div>diff --git a/packages/web/src/components/ui/field.tsx b/packages/web/src/components/ui/field.tsxindex 69fce2af..d7335a77 100644--- a/packages/web/src/components/ui/field.tsx+++ b/packages/web/src/components/ui/field.tsx@@ -24,6 +24,33 @@ export const controlBase =/** Base padding/alignment/transition for a menu row (Select, OptionMenu, and the chat composer menus); callers add flex/block and the hover/selected colors. */export const menuRowClass = "w-full px-3 py-1.5 text-left transition-colors duration-150";+/**+ * The red "*" that marks a field as required, and the only place it is spelled. A field is+ * required when submitting without it is refused — never because its label sounds mandatory —+ * and an optional field carries no counterpart mark: the absence of the asterisk is what says+ * "optional", so no surface writes that word into a label or a placeholder.+ *+ * `aria-hidden` by default because beside a control the mark is decorative: Field, Input,+ * Textarea, Select and OptionMenu set `aria-required` from the same flag, which is what a screen+ * reader announces. Where nothing carries that flag — a read-only table of schema properties,+ * say — pass `label`, and the mark states itself instead of leaving the row unmarked.+ */+export function RequiredMark({ label }: { label?: string }) {+ if (label === undefined) {+ return (+ <span className="ml-0.5 text-red-500 dark:text-red-400" aria-hidden>+ *+ </span>+ );+ }+ return (+ <span className="ml-0.5 text-red-500 dark:text-red-400">+ <span aria-hidden>*</span>+ <span className="sr-only">{label}</span>+ </span>+ );+}+/*** The field's title. Renders as a real `<label htmlFor>` when the caller supplies the control's* id, and as a plain span otherwise — the span form is for the `<label>`-wrapped layout below,@@ -45,11 +72,7 @@ export function FieldLabel({const content = (<>{children}- {required && (- <span className="ml-0.5 text-red-500 dark:text-red-400" aria-hidden>- *- </span>- )}+ {required && <RequiredMark />}</>);return htmlFor !== undefined ? (@@ -109,7 +132,12 @@ export function Field({error?: ReactNode;/** id for the error text — the control passes the same id in aria-describedby. */errorId?: string;- /** Renders a red "*" after the label to mark the field as required. */+ /**+ * Renders a red "*" after the label. An optional field passes nothing — no counterpart mark,+ * and no "optional" in the label. With no `label` there is nothing to hang the mark on, so the+ * flag only reaches the control as `aria-required`; a custom label row must then draw the mark+ * itself with `<FieldLabel required>`, and the two halves have to be kept in step by hand.+ */required?: boolean;/** Semantic explanation, disclosed by a "?" beside the label. Formatting rules belong in `hint`, which stays visible. */info?: ReactNode;diff --git a/packages/web/src/components/ui/option-menu.tsx b/packages/web/src/components/ui/option-menu.tsxindex f900c8b8..f200433b 100644--- a/packages/web/src/components/ui/option-menu.tsx+++ b/packages/web/src/components/ui/option-menu.tsx@@ -75,7 +75,7 @@ export function OptionMenu<T extends string>({label?: string;/** Field-value error: red border + message below, exactly like Input. */error?: string;- /** Renders a red "*" after the label to mark the field as required. */+ /** Renders a red "*" after the label. An optional field passes nothing — no counterpart mark, and no "optional" in the label. */required?: boolean;/** Stretch the trigger button to fill the container width, as a replacement for native Select in dense form areas. */fullWidth?: boolean;diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsxindex 9d1260e0..82a909ec 100644--- a/packages/web/src/features/agents/memory-tab.tsx+++ b/packages/web/src/features/agents/memory-tab.tsx@@ -853,6 +853,7 @@ export function MemoryTab({</p><Textarealabel={S.memory.addContentLabel}+ requiredsize="sm"rows={4}value={addContent}diff --git a/packages/web/src/features/agents/schedules-tab.tsx b/packages/web/src/features/agents/schedules-tab.tsxindex 73a849c2..51877933 100644--- a/packages/web/src/features/agents/schedules-tab.tsx+++ b/packages/web/src/features/agents/schedules-tab.tsx@@ -42,7 +42,7 @@ import { ConfirmModal } from "../../components/ui/confirm-modal";import { SettingsEmpty } from "../../components/ui/empty-state";import { SkeletonList } from "../../components/ui/skeleton";import { FormPicker } from "../../components/ui/form-picker";-import { FieldError, FieldLabel } from "../../components/ui/field";+import { FieldError, FieldHint, FieldLabel } from "../../components/ui/field";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";import { ModelSelect, PickerList } from "../chat/model-select";import { WorkspaceSelect } from "../chat/workspace-select";@@ -682,6 +682,7 @@ export function SchedulesTab({onChange={(workspace) => set({ workspace })}variant="form"/>+ <FieldHint>{S.chat.workspaceHintShort}</FieldHint></div></>)}diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsxindex 668e7ae4..ac3ec01f 100644--- a/packages/web/src/features/models/models-page.tsx+++ b/packages/web/src/features/models/models-page.tsx@@ -1319,12 +1319,9 @@ function AddGroupDialog({picker — the add-model dialog's idiom, so the two flows read as one. */}<div className="block"><span className="mb-1 flex items-baseline justify-between gap-2">- <span className="text-xs font-semibold text-gray-600 dark:text-gray-400">+ <FieldLabel required block={false}>{S.models.baseUrl}- <span className="ml-0.5 text-red-500 dark:text-red-400" aria-hidden>- *- </span>- </span>+ </FieldLabel><buttontype="button"disabled={detecting || busy}@@ -2012,13 +2009,9 @@ function ModelDialog({<><label className="block"><span className="mb-1 flex items-baseline justify-between gap-2">- <span className="text-xs font-semibold text-gray-600 dark:text-gray-400">+ <FieldLabel required block={false}>{S.models.modelId}- {/* Required mark, hand-placed: this label row is custom (link on the right), so FieldLabel's asterisk doesn't apply. */}- <span className="ml-0.5 text-red-500 dark:text-red-400" aria-hidden>- *- </span>- </span>+ </FieldLabel><span className="flex shrink-0 items-baseline gap-2.5">{/* The model-homepage entry lives in the dialog header (top-right button); only the "get model ids" provider link stays here. */}{dialogProvider?.modelsUrl && (@@ -2291,9 +2284,7 @@ function ModelDialog({own <label> wrapper, so this outer container is a <div> (a nested <label> is invalid). */}<div className="block"><span className="mb-1 flex items-baseline justify-between gap-2">- <span className="text-xs font-semibold text-gray-600 dark:text-gray-400">- {S.models.apiKey}- </span>+ <FieldLabel block={false}>{S.models.apiKey}</FieldLabel>{dialogProvider?.apiKeyUrl && (<ahref={dialogProvider.apiKeyUrl}@@ -2307,6 +2298,7 @@ function ModelDialog({</span><PasswordInputsize="sm"+ aria-label={S.models.apiKey}value={form.apiKeyInput}disabled={!canEdit}onChange={(e) => set({ apiKeyInput: e.target.value, clearApiKey: false })}@@ -2374,14 +2366,9 @@ function ModelDialog({<div className="block">{showProtocolPicker ? (<span className="mb-1 flex items-baseline justify-between gap-2">- <span className="text-xs font-semibold text-gray-600 dark:text-gray-400">+ <FieldLabel required={baseUrlRequired} block={false}>{S.models.baseUrl}- {baseUrlRequired && (- <span className="ml-0.5 text-red-500 dark:text-red-400" aria-hidden>- *- </span>- )}- </span>+ </FieldLabel>{/* Always live: no API key is needed (the server falls back to the stored keyand then to the protocol's env var), and anything that does go wrong isexplained in a popup. `detecting` only guards re-entrancy. */}diff --git a/packages/web/src/features/settings/uploads-section.tsx b/packages/web/src/features/settings/uploads-section.tsxindex 5876d836..ea1631e2 100644--- a/packages/web/src/features/settings/uploads-section.tsx+++ b/packages/web/src/features/settings/uploads-section.tsx@@ -32,8 +32,15 @@ export function UploadsSection() {// last digit would snap the field back to a value the user is in the middle of replacing).const [maxMb, setMaxMb] = useState("");const [totalMb, setTotalMb] = useState("");- /** Inline error under whichever field the server rejected. */- const [limitError, setLimitError] = useState<string | null>(null);+ /**+ * Inline error, and which fields it is about. The local shape check knows the offending field;+ * the server's `invalid_attachment_limit` is a statement about the pair, so it marks both.+ */+ const [limitError, setLimitError] = useState<{+ text: string;+ max: boolean;+ total: boolean;+ } | null>(null);const [busy, setBusy] = useState(false);/** Adopt server-side truth: the baseline and the drafts move together. */@@ -65,13 +72,14 @@ export function UploadsSection() {const parsedTotal = Number(totalMb.trim());// Shape-check locally so an empty or non-numeric field never becomes a NaN in the request// body; the RANGE is left to the server, which owns it (this form only reports its verdict).- if (- maxMb.trim() === "" ||- totalMb.trim() === "" ||- !Number.isInteger(parsedMax) ||- !Number.isInteger(parsedTotal)- ) {- setLimitError(S.errors.byCode.invalid_attachment_limit);+ const maxBad = maxMb.trim() === "" || !Number.isInteger(parsedMax);+ const totalBad = totalMb.trim() === "" || !Number.isInteger(parsedTotal);+ if (maxBad || totalBad) {+ setLimitError({+ text: S.errors.byCode.invalid_attachment_limit,+ max: maxBad,+ total: totalBad,+ });return;}if (parsedMax === settings.attachmentMaxMb && parsedTotal === settings.attachmentTotalMb) {@@ -92,7 +100,7 @@ export function UploadsSection() {toastSuccess(S.common.saved);} catch (e) {if (e instanceof ApiError && e.code === "invalid_attachment_limit") {- setLimitError(apiErrorText(e));+ setLimitError({ text: apiErrorText(e), max: true, total: true });} else {toastError(apiErrorText(e));}@@ -112,6 +120,7 @@ export function UploadsSection() {><Inputlabel={S.settings.attachmentMaxMb}+ requiredsize="sm"type="number"inputMode="numeric"@@ -123,6 +132,7 @@ export function UploadsSection() {)}value={maxMb}disabled={!hydrated}+ {...(limitError?.max === true ? { error: limitError.text } : {})}onChange={(e) => {setMaxMb(e.target.value);if (limitError !== null) setLimitError(null);@@ -130,6 +140,7 @@ export function UploadsSection() {/><Inputlabel={S.settings.attachmentTotalMb}+ requiredsize="sm"type="number"inputMode="numeric"@@ -141,7 +152,13 @@ export function UploadsSection() {)}value={totalMb}disabled={!hydrated}- {...(limitError !== null ? { error: limitError } : {})}+ {...(limitError?.total === true+ ? // The message renders once, on the first field at fault; a second faulty field is+ // marked without repeating the sentence.+ limitError.max+ ? { invalid: true }+ : { error: limitError.text }+ : {})}onChange={(e) => {setTotalMb(e.target.value);if (limitError !== null) setLimitError(null);diff --git a/packages/web/src/features/traces/trace-event-row.tsx b/packages/web/src/features/traces/trace-event-row.tsxindex bc140922..ce7e76c5 100644--- a/packages/web/src/features/traces/trace-event-row.tsx+++ b/packages/web/src/features/traces/trace-event-row.tsx@@ -18,6 +18,7 @@ import { S } from "../../lib/strings";import type { OmniMessage } from "@prismshadow/penguin-core/omnimessage";import { formatTime, humanizeTokens } from "../../lib/format";import { Badge, stopReasonTone } from "../../components/ui/badge";+import { RequiredMark } from "../../components/ui/field";import type { BadgeTone } from "../../components/ui/badge";import { ZoomableImage } from "../../components/ui/image-zoom";@@ -256,7 +257,7 @@ function ParamsTable({ schema }: { schema: Record<string, unknown> }) {<tr key={name} className="align-top"><td className="whitespace-nowrap pr-3 font-mono text-gray-700 dark:text-gray-300">{name}- {required.has(name) && <span className="ml-0.5 text-red-500">*</span>}+ {required.has(name) && <RequiredMark label={S.traces.requiredParam} />}</td><td className="whitespace-nowrap pr-3 font-mono text-gray-400 dark:text-gray-500">{typeOf(s)}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex a90470ed..44903f2d 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -293,9 +293,9 @@ export const en: Strings = {"2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only. Cannot be changed later.",idPrefixHint:"The id is prefixed with your username and a hyphen; append lowercase letters, digits or underscores. Cannot be changed later.",- name: "Display name (optional, defaults to the Project id)",- /** The display-name field in Project settings (required there, unlike the create dialog's optional one). */displayName: "Display name",+ /** Create dialog only: leaving the name empty falls back to the id. In Project settings the saved name cannot be blanked. */+ displayNameHint: "Leave empty to use the Project id as the name",settings: "Project settings",settingsTitle: "Project settings",members: "Members",@@ -309,7 +309,6 @@ export const en: Strings = {chatDefaultsNotSet: "Not set",chatDefaultsApprovalNotSet: "Not set (defaults to allow all)",chatDefaultsThinkingNotSet: "Not set (follow the agent's config)",- chatDefaultsWorkspaceHint: "Empty = temporary workspace",/** The model default is single-sourced with the Models page (the same default_model); this is just another entry point. */chatDefaultsModelHint: "Same default model as the Models page",/** Settings dialog tab rail. */@@ -334,7 +333,7 @@ export const en: Strings = {commandPolicyOff: "Disabled",commandPolicyRuleName: "Name",commandPolicyRulePattern: "Regular expression",- commandPolicyRuleDesc: "Description (optional)",+ commandPolicyRuleDesc: "Description",commandPolicyInvalidPattern: "Invalid regular expression",deleteProject: "Delete Project",deleteConfirm:@@ -832,7 +831,7 @@ export const en: Strings = {editWhy:"Content edits are made by the agent in a chat: confirm the prompt to open a new conversation, and the agent updates the memory file and its MEMORY.md index together.",editRequirementLabel: "What to change",- editRequirementPlaceholder: "Describe the change (optional — you can finish it in the chat)",+ editRequirementPlaceholder: "Describe the change — you can finish it in the chat",editPromptLabel: "Prompt preview",editCopyPrompt: "Copy prompt",editOpenChat: "Open a new chat",@@ -946,7 +945,7 @@ export const en: Strings = {prompt: "Prompt",enabled: "Enabled",startAt: "Start at",- endAt: "End at (optional)",+ endAt: "End at",period: "Period",periodPlaceholder: "30m / 12h / 7d; leave empty for a one-off task",target: "Target",@@ -958,7 +957,7 @@ export const en: Strings = {sessionSearch: "Search title or Session id…",sessionNoMatch: "No matching Session",sessionEmpty: "This agent has no Sessions yet",- workspace: "Workspace (optional; a temporary workspace is created when empty)",+ workspace: "Workspace",model: "Model",modelDefault: "Project default",deleteTitle: "Delete scheduled task",@@ -1268,6 +1267,8 @@ Scenarios:workspace: "Workspace",workspaceHint:"Leave empty for an auto-created temporary workspace; if set, it must be an existing directory on the server",+ /** The same rule as `workspaceHint`, short enough to sit under a form field. */+ workspaceHintShort: "Leave empty for a temporary workspace",approvalMode: "Approval mode",approvalModeNames: {"allow-all": "Approve everything",@@ -1694,6 +1695,8 @@ Scenarios:legendToolExec: "tool exec",legendOther: "Other",toolParams: "Parameter schema",+ /** Spoken form of the red "*" in the schema table, where no control carries `aria-required`. */+ requiredParam: "required",legendApprovalWait: "approval wait",task: (n: number) => `Turn ${n}`,globalSummary: "Overall",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex d75321d9..0754c3b0 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -280,9 +280,9 @@ export const zh = {id: "Project id",idHint: "2~64 位:小写字母开头,仅小写字母、数字与下划线;创建后不可修改",idPrefixHint: "id 固定以「用户名-」为前缀,后接小写字母、数字或下划线;创建后不可修改",- name: "显示名(可选,缺省为 Project id)",- /** Display-name field in Project settings (required here, unlike the create dialog's "optional" wording). */displayName: "显示名",+ /** Create dialog only: leaving the name empty falls back to the id. In Project settings the saved name cannot be blanked. */+ displayNameHint: "留空则使用 Project id 作为名称",settings: "Project 设置",settingsTitle: "Project 设置",members: "成员",@@ -295,7 +295,6 @@ export const zh = {chatDefaultsNotSet: "未设置",chatDefaultsApprovalNotSet: "未设置(默认全部放行)",chatDefaultsThinkingNotSet: "未设置(跟随智能体配置)",- chatDefaultsWorkspaceHint: "留空表示使用临时工作区",/** The model default shares its source with the Models page (the same default_model); this is just another entry point. */chatDefaultsModelHint: "与模型页的默认模型同步",/** Settings dialog tab rail. */@@ -320,7 +319,7 @@ export const zh = {commandPolicyOff: "已停用",commandPolicyRuleName: "名称",commandPolicyRulePattern: "正则表达式",- commandPolicyRuleDesc: "描述(可选)",+ commandPolicyRuleDesc: "描述",commandPolicyInvalidPattern: "正则表达式无效",deleteProject: "删除 Project",deleteConfirm: "确认删除该 Project?项目目录将被递归删除,不可恢复。",@@ -803,7 +802,7 @@ export const zh = {editWhy:"内容修改由 agent 在对话中完成:确认引导语后打开新对话,agent 会同步更新记忆文件与 MEMORY.md 索引。",editRequirementLabel: "修改要求",- editRequirementPlaceholder: "描述要怎么改(可留空,跳转后在对话中补充)",+ editRequirementPlaceholder: "描述要怎么改,跳转后可在对话中补充",editPromptLabel: "引导语预览",editCopyPrompt: "复制 Prompt",editOpenChat: "打开新对话",@@ -910,7 +909,7 @@ export const zh = {prompt: "Prompt",enabled: "启用",startAt: "开始时间",- endAt: "结束时间(可选)",+ endAt: "结束时间",period: "周期",periodPlaceholder: "30m / 12h / 7d,留空为一次性",target: "目标",@@ -922,7 +921,7 @@ export const zh = {sessionSearch: "搜索标题或 Session id…",sessionNoMatch: "无匹配的 Session",sessionEmpty: "该 Agent 暂无 Session",- workspace: "Workspace(可选,留空自动创建临时工作区)",+ workspace: "Workspace",model: "Model",modelDefault: "Project 默认",deleteTitle: "删除定时任务",@@ -1224,6 +1223,8 @@ Benchmark:model: "Model",workspace: "Workspace",workspaceHint: "留空自动创建临时工作区;指定时必须是服务器上已存在的目录",+ /** The same rule as `workspaceHint`, short enough to sit under a form field. */+ workspaceHintShort: "留空自动创建临时工作区",approvalMode: "审批模式",/** Short description (the trigger button shows only the description, not the mode id). */approvalModeNames: {@@ -1646,6 +1647,8 @@ Benchmark:legendToolExec: "工具调用执行",legendOther: "其他",toolParams: "参数 Schema",+ /** Spoken form of the red "*" in the schema table, where no control carries `aria-required`. */+ requiredParam: "必填",legendApprovalWait: "审批等待",task: (n: number) => `第 ${n} 轮`,globalSummary: "全局统计",diff --git a/packages/web/test/required-mark.test.ts b/packages/web/test/required-mark.test.tsnew file mode 100644index 00000000..bbcefc79--- /dev/null+++ b/packages/web/test/required-mark.test.ts@@ -0,0 +1,212 @@+/**+ * The field-marker contract (src/components/ui/field.tsx): **a required field carries the red+ * "*", an optional field carries nothing at all, and no label or placeholder writes the word+ * "optional".**+ *+ * The absence of the mark is the whole signal, so it only reads if the mark is spelled one way+ * everywhere and never competes with a second, wordier convention — the same reason+ * test/icon-scale.test.ts fails on a second copy of the close cross.+ *+ * The source scan parses the real JSX with the TypeScript parser: whether a red span holds a lone+ * "*" is a question about an element's children, and a regex cannot see children.+ */+import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { readdirSync, readFileSync, statSync } from "node:fs";+import { join, sep } from "node:path";+import { fileURLToPath } from "node:url";+import ts from "typescript";+import { Input } from "../src/components/ui/input";+import { RequiredMark } from "../src/components/ui/field";+import { zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";++const SRC = fileURLToPath(new URL("../src", import.meta.url));+const FIELD = join(SRC, "components", "ui", "field.tsx");++function tsxFiles(dir = SRC, out: string[] = []): string[] {+ for (const name of readdirSync(dir)) {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) tsxFiles(path, out);+ else if (name.endsWith(".tsx")) out.push(path);+ }+ return out;+}++/**+ * Every string literal reachable from a node, joined. `className` is written four ways here —+ * `"a b"`, `{"a b"}`, `` {`a ${x}`} `` and `{c ? "a" : "b"}` — and a scan that reads only the+ * first would miss the copy most likely to be re-typed.+ */+function literals(node: ts.Node, out: string[] = []): string[] {+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) out.push(node.text);+ else if (ts.isTemplateExpression(node)) {+ out.push(node.head.text);+ for (const span of node.templateSpans) out.push(span.literal.text);+ }+ ts.forEachChild(node, (child) => void literals(child, out));+ return out;+}++/** The element's `className`, in whichever of those forms it was written. */+function classNameOf(open: ts.JsxOpeningElement): string {+ for (const attr of open.attributes.properties) {+ if (!ts.isJsxAttribute(attr)) continue;+ if (!ts.isIdentifier(attr.name) || attr.name.escapedText !== "className") continue;+ const init = attr.initializer;+ if (init !== undefined) return literals(init).join(" ");+ }+ return "";+}++/** The element's own text, whether written as JSX text or as a `{"*"}` expression child. */+function childText(node: ts.JsxElement): string {+ return node.children+ .map((c) => {+ if (ts.isJsxText(c)) return c.text;+ if (ts.isJsxExpression(c) && c.expression !== undefined)+ return literals(c.expression).join("");+ return "";+ })+ .join("")+ .trim();+}++/** Every element that paints a lone "*" in a red ink class — i.e. a hand-rolled required mark. */+function marksIn(path: string, text: string): string[] {+ const found: string[] = [];+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, false, ts.ScriptKind.TSX);+ const visit = (node: ts.Node): void => {+ // The children test is cheap and rejects all but a handful of the tree's ~2200 elements,+ // so it runs before the attribute walk.+ if (ts.isJsxElement(node) && childText(node) === "*") {+ if (classNameOf(node.openingElement).includes("text-red-")) {+ const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;+ found.push(`${path.slice(SRC.length + 1).replaceAll(sep, "/")}:${line}`);+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return found;+}++function handRolledMarks(): string[] {+ const found: string[] = [];+ for (const path of tsxFiles()) {+ if (path === FIELD) continue; // the one place the mark is allowed to be spelled+ found.push(...marksIn(path, readFileSync(path, "utf8")));+ }+ return found.sort();+}++/**+ * Both dictionaries are searched with both patterns: the zh entries mix English freely+ * ("Workspace(可选…)" was one of them), so a locale-specific pattern would only be enforcing+ * the rule on half of each file. The Chinese alternatives are listed because 可选 is one of+ * several ways to write it — 可留空 / 选填 / 非必填 all say the same thing to a reader.+ * Functions are skipped: an interpolating entry is prose by construction, never a field label.+ */+const SAYS_OPTIONAL = /\boptional(ly)?\b|(?<!不)可选(?!择)|可留空|选填|非必填|可不填/i;++function optionalWording(dict: unknown, path = ""): string[] {+ if (typeof dict === "string") return SAYS_OPTIONAL.test(dict) ? [path] : [];+ if (dict === null || typeof dict !== "object") return [];+ return Object.entries(dict as Record<string, unknown>).flatMap(([key, value]) =>+ optionalWording(value, path === "" ? key : `${path}.${key}`),+ );+}++/**+ * Entries where the word is part of an explanation rather than a field marker, and so stays,+ * listed per locale — an exception earned by one dictionary's wording says nothing about the+ * other's. A new entry needs a reason of the same kind: "this sentence describes something that+ * is itself optional", not "this label is optional".+ */+const PROSE_EXCEPTIONS: Record<"zh" | "en", ReadonlySet<string>> = {+ // Describes the tool schema's own `description` argument, which really is an optional argument.+ zh: new Set(["agent.callDescriptionHint"]),+ en: new Set([+ "agent.callDescriptionHint",+ // States the accepted number format: the k/m suffix may be left off.+ "chat.goalBudgetInvalid",+ ]),+};++describe("required mark", () => {+ it("renders only when the field is required", () => {+ const required = renderToStaticMarkup(+ createElement(Input, { label: "Name", required: true, value: "", readOnly: true }),+ );+ expect(required).toContain("*");+ expect(required).toContain("text-red-500");+ // Decorative to assistive tech — aria-required on the control is what gets announced.+ expect(required).toMatch(/<span[^>]*aria-hidden[^>]*>\*<\/span>/);+ expect(required).toContain('aria-required="true"');+ });++ it("states itself where no control carries aria-required", () => {+ // The trace viewer's schema table is not a form: nothing else there says "required".+ const spoken = renderToStaticMarkup(createElement(RequiredMark, { label: "required" }));+ expect(spoken).toMatch(/<span[^>]*aria-hidden[^>]*>\*<\/span>/);+ expect(spoken).toContain("required");+ expect(spoken).not.toMatch(/^<span[^>]*aria-hidden/);+ });++ it("leaves an optional field completely unmarked", () => {+ // No counterpart mark and no wording: absence is the signal, so anything here would blunt it.+ const optional = renderToStaticMarkup(+ createElement(Input, { label: "Name", value: "", readOnly: true }),+ );+ // Scoped to the mark's own shape: a bare `toContain("*")` over the markup would also trip+ // on a Tailwind `*:` variant landing in any class the control renders.+ expect(optional).not.toMatch(/<span[^>]*>\*<\/span>/);+ expect(optional).not.toContain("text-red-");+ expect(optional).not.toContain("aria-required");+ });++ it("is spelled in exactly one place", () => {+ expect(+ handRolledMarks(),+ "A red '*' belongs to RequiredMark (components/ui/field.tsx). Pass `required` to " ++ "Field/Input/Textarea/Select/OptionMenu, use <FieldLabel required> for a custom label " ++ "row, or render <RequiredMark /> directly.",+ ).toEqual([]);+ });++ it("finds a hand-rolled mark however its className is written", () => {+ // Without this the scan above could silently stop matching and still report a clean tree.+ const probe = join(SRC, "probe.tsx");+ const shapes = [+ 'const a = <span className="ml-0.5 text-red-500">*</span>;',+ "const b = <span className={`ml-0.5 text-red-500`}>*</span>;",+ 'const c = <span className={dim ? "text-red-500" : ""}>*</span>;',+ 'const d = <span className="text-red-500">{"*"}</span>;',+ ];+ expect(marksIn(probe, shapes.join("\n"))).toHaveLength(shapes.length);+ expect(marksIn(probe, '<span className="text-gray-500">*</span>')).toEqual([]);+ });++ for (const [locale, dict] of [+ ["zh", zh],+ ["en", en],+ ] as const) {+ it(`never says "optional" in a ${locale} label`, () => {+ const said = optionalWording(dict).filter((p) => !PROSE_EXCEPTIONS[locale].has(p));+ expect(+ said,+ 'A field is optional because it has no red "*", never because its label says so.',+ ).toEqual([]);+ });++ it(`keeps the ${locale} prose exceptions real (guards the allow-list against rot)`, () => {+ // A stale exception would quietly re-open the hole it was cut for. Per locale, because a+ // union lets one dictionary's wording keep the other's dead entry alive.+ const said = new Set(optionalWording(dict));+ for (const path of PROSE_EXCEPTIONS[locale]) {+ expect(said, `${locale}: ${path} no longer says it`).toContain(path);+ }+ });+ }+});