diff --git a/.scratch/worktree-salvage/migration.md b/.scratch/worktree-salvage/migration.md new file mode 100644 index 00000000..339f52ab --- /dev/null +++ b/.scratch/worktree-salvage/migration.md @@ -0,0 +1,11 @@ +# 工作树内容迁入核对 + +基线为 dev 5375074a,包含线上 327759af。原工作树全部保留,不迁入 `.claude/launch.json`。 + +- workbench-ui-polish 的四个已提交改动经 git cherry 验证已存在等价补丁,不重复迁入。 +- 迁入空草稿引用复用、浏览器锁观察去重、审查追溯 memo、聚焦意见按焦点变化滚动、日期格式化器复用。 +- 旧完整任务池 JSON.stringify 比较不迁入。适配当前摘要协议:只比较摘要和处理状态,保留已有任务详情/草稿引用;成员、阶段、版本、送检、校验、显示及处理状态变化继续应用。 +- delivery-v4-only 的 1e11755b 仅提取只读盘点脚本和测试,加入当前验证映射。目录传输也可承载 V4,故外层 manifest 只能标记“需检查实际 part schema”,不据此判定必须重建。 +- 盘点执行只登录并读取元数据,禁止跟随跳转;不下载媒体、不转换、不发布或修改客户数据。缺少原始来源、冻结字典、PTS 映射的记录只能列为待检查。 +- 不整批搬入旧 ADR/交付文档,保留 dev 的 2026-11-08 修订。旧盘点的 18 包/12 修订等数字仅为历史快照,不能作为当前完整性结论;重新盘点须依据实时只读结果。 +- 当前已有旧任务 V4 快照、重试和发布防护实现,见 docs/delivery-classification-v4.zh-CN.md。新 V4 真实出包验收、历史包新批次正式转换/发布、广范围慢查询、BOS 到客户端链路仍分别待验证或处理,本次工具迁入不等于这些问题已完成。 diff --git a/.scratch/worktree-salvage/verification.md b/.scratch/worktree-salvage/verification.md new file mode 100644 index 00000000..25f3b8c5 --- /dev/null +++ b/.scratch/worktree-salvage/verification.md @@ -0,0 +1,22 @@ +# 迁入验证 + +基线:dev 5375074a(代码树与线上 327759af 相同)。候选:codex/worktree-salvage。仅本地合成夹具;没有线上转换、替换、写验收或部署。 + +## 已通过 + +- 最终 `npm run verify:quick -- --base 5375074a`:类型/架构、格式、验证工具、定向前端行为、Go 定向规则均通过;报告 `local-data/test-results/verify-1794192683011179000/report.json`。 +- 任务级 19 组中 17 组初轮通过,包含真实 Mongo 摘要/搜索等价、源校验、搜索分页浏览器、返工、审查草稿保存、决定竞态及权限隔离。源代码在这些检查之后未变。记录 `local-data/test-results/verify-1794192097543999000/report.json`。运行期间仅修改新增浏览器测试,故该报告 inputsChangedDuringRun 为 true,不将其宣称为全套通过。 +- 新增 `node tests/browser/workbench-render-reuse.mjs` 最终独立通过:使用真实审查组件/草稿 Hook 与合成数据;5 次无关刷新不滚动、不重新格式化追溯;切换首尾时间点时焦点条目可见;追溯版本变更更新。报告及截图 `local-data/test-results/workbench-render-reuse/`,已查看截图。 +- 盘点工具 7 项单测通过,覆盖目录外层不证明 part 格式、缺失冻结事实、不跟随跳转和非法 origin 拒绝。 +- 旧测试中的源码字符串断言不迁入最终版本:日期缓存使用真实输出/构造次数,摘要使用真实字段/引用行为,滚动与 memo 使用真实浏览器结果。 + +## 遗留与边界 + +- `TestReviewTraceBrowserReplica/quality` 等待编辑框可编辑失败(readonly textarea)。候选及未修改的 327759af 同样出现该问题;后者经 `npm run test:go:gate`、GOFLAGS 精确选择该用例复核。该用例未录入 known-failures,门禁如实标记失败,不扩充或改写基线以掩盖。 +- 原基线工作树的 local-data 内另有既有 Go 实验文件,导致其全包门禁附加编译错误;不据此宣称整个 Go 基线通过。候选正式门禁记录另存 `local-data/test-results/worktree-salvage/trace-gate/`。此处只确认具体同一只读失败在改动前已存在,不宣称其已修复。 +- 新增浏览器测试初次缺少动作上下文、定位同时匹配当前/全量意见列表,以及效果读取早于 useEffect,均已修正后独立重测通过;没有为使测试通过改业务权限。 +- 生产容量、真实 BOS 播放性能、历史包完整转换/正式发布和 V4 实际出包仍未验收。本地迁入不构成发布门禁通过。 + +## 内容保全 + +workbench-ui-polish 的六个已修改源码文件、未跟踪测试和 .claude 配置保持原样;delivery-v4-only 的独有提交及本地材料保持原样。未重复迁入四个已存在等价补丁的 UI 提交。未推送、建 PR 或部署本批改动。 diff --git a/.scratch/worktree-salvage/work.md b/.scratch/worktree-salvage/work.md new file mode 100644 index 00000000..96ac0540 --- /dev/null +++ b/.scratch/worktree-salvage/work.md @@ -0,0 +1,8 @@ +# Recover useful worktree changes + +Goal: Preserve reviewed UI render optimizations and the V4 read-only inventory tool on current dev. +Agent: Codex +Base: origin/dev @ 5375074a +Scope: Five UI/render sources, summary-aware annotation buffer reconciliation, inventory CLI/tests, verification mapping and current handoff notes. +Out of scope: Original worktree edits/deletion, local .claude launch configuration, production data conversion, deployment, push or PR without authorization. +Risk: Preserve draft/payload identity, locks, server eligibility and lifecycle updates; inventory is inspection only, not V4 validation/publication. diff --git a/docs/delivery-classification-v4.zh-CN.md b/docs/delivery-classification-v4.zh-CN.md index 99195c59..18c72574 100644 --- a/docs/delivery-classification-v4.zh-CN.md +++ b/docs/delivery-classification-v4.zh-CN.md @@ -65,3 +65,12 @@ 用户进一步要求不再新生成旧格式交付包。同一组织、项目和版本家族已启用 V4 时,旧任务后续放行也冻结兼容的 V4 打包配置;原工作流、人工任务归属和已验收内容不变。执行、重试与重启沿用冻结镜像及参数。无法证明原始来源、冻结字典、标签和时间证据时停在明确失败状态,先恢复证据,不回退旧格式。 已完整发布的旧文件仅允许校验完成清单、成员哈希和归属后只读恢复状态;缺失或冲突的旧上传不得继续补发。转换生成独立候选或新交付批次,不覆盖旧完成清单。线上替换、历史证据恢复和新批次正式发布需要分别验证;本地转换通过不代表全部历史包可正式交付。 + + +## 存量盘点工具(2026-11-08) + +`scripts/local/delivery_v4_inventory.py` 从指定账号文件读取管理员身份,登录后只读盘点生产交付包及固定物化修订;输出到指定的本地 JSON。使用 `--accounts-file <本地账号文件> --output local-data/<盘点报告>.json`,`--limit` 限制检查的已验收包数,超过上限时报告覆盖不完整。账号文件与报告不进入版本库。 + +外层目录 manifest 同样可承载 V4,因此盘点仅标记需要检查实际 part 内容;即使见到 V4 标记也仍需完整契约、来源、标签、哈希及秒数到 PTS 校验。工具禁止跟随内容跳转,不下载媒体,不转换、发布或替换旧包。冻结事实缺项不等于其他内部证据绝不可恢复。正式转换仍使用独立候选与新批次,并按前述边界验收和授权。 + +旧工作树中的包数、修订数和“待实施”清单是历史快照,不代表当前线上完整性。后续处置须绑定新盘点结果,不能以本工具迁入或一次单测通过宣布生产迁移完成。 diff --git a/scripts/local/delivery_v4_inventory.py b/scripts/local/delivery_v4_inventory.py new file mode 100644 index 00000000..299499ba --- /dev/null +++ b/scripts/local/delivery_v4_inventory.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Read-only inventory for the v4-only cutover. Never publishes or repairs data.""" +import argparse +from collections import Counter +from datetime import datetime, timezone +import http.cookiejar +import json +from pathlib import Path +import urllib.parse +import urllib.request +import ssl + +V4 = "droboticflow.delivery.part-index/v4" + + +def classify_package(package, contents, revision=None): + """Workflow settings are intentionally not proof of the exported schema.""" + manifest = contents.get("manifest") or {} + schema = manifest.get("schemaVersion", "unknown") + row = {"packageId": package["id"], "workflowId": package.get("workflowId"), + "runId": package.get("childRunId"), "status": package.get("status"), + "captureId": (manifest.get("capture") or {}).get("captureId"), + "exportedManifestSchema": schema, + "state": "requires_output_inspection", "reasons": []} + if schema.startswith("droboticflow.delivery.manifest/"): + # Directory transport is also used for V4. Inspect the actual part JSON + # before deciding whether rebuilding is required. + row["state"] = "directory_requires_part_schema_inspection" + # Even a schema marker is not full v4 validation (hashes/source/PTS/tags). + elif schema == V4: + row["state"] = "v4_candidate_requires_contract_validation" + if revision is not None: + slices = revision.get("items") or [] + missing = [x.get("sliceId", "unknown") for x in slices + if x.get("deliveryDisposition") != "discard" and + not (x.get("dictionary") or (x.get("classification") or {}).get("dictionary"))] + row["revisionSchema"] = revision.get("schemaVersion") + row["revisionNumber"] = revision.get("revision") + row["revisionSliceCount"] = len(slices) + row["slicesWithoutFrozenDictionary"] = missing + if missing: + row["reasons"].append("pinned_revision_missing_frozen_dictionary") + if not revision.get("originalSource"): + row["reasons"].append("pinned_revision_missing_original_source") + row["reasons"].append("full_source_and_seconds_to_pts_validation_pending") + else: + row["reasons"].append("pinned_revision_not_inspected") + return row + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +class ReadOnlyAPI: + def __init__(self, origin, account): + parsed = urllib.parse.urlsplit(origin) + if (parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.path not in ("", "/") + or parsed.username or parsed.password or parsed.query or parsed.fragment): + raise ValueError("invalid origin") + self.origin = origin.rstrip("/") + # Refuse redirects, including redirects from the login POST or content + # endpoints. The inventory never follows a signed URL into media/BOS. + ca = Path("/etc/ssl/cert.pem") + tls = ssl.create_default_context(cafile=str(ca) if ca.exists() else None) + self.opener = urllib.request.build_opener(NoRedirect(), urllib.request.HTTPSHandler(context=tls), + urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) + request = urllib.request.Request(self.origin + "/api/auth/login", data=json.dumps( + {"phone": account["phone"], "password": account["password"]}).encode(), + headers={"Content-Type": "application/json"}) + with self.opener.open(request, timeout=20) as response: + response.read(65536) + + def get(self, path): + if not path.startswith("/api/") or "://" in path: + raise ValueError("invalid API path") + with self.opener.open(self.origin + path, timeout=45) as response: + raw = response.read(8 * 1024 * 1024 + 1) + if len(raw) > 8 * 1024 * 1024: + raise ValueError("metadata too large") + return json.loads(raw) + + def pinned_revision(self, manifest): + lineage = manifest.get("lineage") or {} + run, artifact = lineage.get("sourceRunId"), lineage.get("acceptedSliceDirectoryArtifactId") + if not run or not artifact: + return None + root = "/api/runs/" + urllib.parse.quote(run, safe="") + "/artifacts/" + urllib.parse.quote(artifact, safe="") + members = self.get(root + "/members?limit=200") + # Never guess a different revision or download media to infer facts. + found = [x for x in members.get("items", []) if x.get("name") == "revision-manifest.json"] + if len(found) != 1 or not found[0].get("contentAvailable"): + return None + return self.get(root + "/members/" + urllib.parse.quote(found[0]["id"], safe="") + "/content") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--accounts-file", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--limit", type=int, default=100) + args = parser.parse_args() + if not 1 <= args.limit <= 100: + parser.error("limit must be 1..100") + config = json.loads(args.accounts_file.read_text()) + account = next(x for x in config["accounts"] if x["role"] == "admin-all") + api = ReadOnlyAPI(config["origin"], account) + items = api.get("/api/delivery-packages?mode=production")["items"] + selected = sorted([x for x in items if x.get("status") == "accepted"], key=lambda x: x["id"])[:args.limit] + report = {"schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), + "readOnly": True, "requiredCustomerSchema": V4, + "productionPackagesSeen": len(items), + "acceptedPackagesSeen": sum(x.get("status") == "accepted" for x in items), + "packages": [], "limitations": [ + "This inventory is not a conversion or publication approval.", + "Missing fields in a pinned revision may be recoverable from other internal evidence; never infer current dictionary tags.", + "Not a full v4 builder, source identity or seconds-to-PTS validation."]} + for number, package in enumerate(selected, 1): + try: + contents = api.get("/api/delivery-packages/" + urllib.parse.quote(package["id"], safe="") + "/contents") + try: + revision = api.pinned_revision(contents.get("manifest") or {}) + except Exception: + revision = None + row = classify_package(package, contents, revision) + except Exception: + row = {"packageId": package["id"], "state": "inspection_failed", "reasons": ["metadata_read_failed"]} + report["packages"].append(row) + print(f"{number}/{len(selected)} {row['state']}", flush=True) + report["packageListCoverageComplete"] = len(selected) == report["acceptedPackagesSeen"] + report["revisionInspectionComplete"] = report["packageListCoverageComplete"] and all( + x.get("revisionSchema") for x in report["packages"]) + report["states"] = dict(Counter(x["state"] for x in report["packages"])) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2)) + print(json.dumps({"output": str(args.output), "states": report["states"], + "packageListCoverageComplete": report["packageListCoverageComplete"], + "revisionInspectionComplete": report["revisionInspectionComplete"]})) + + +if __name__ == "__main__": + try: + main() + except Exception: + # HTTP errors can contain signed locations/identity context. Never dump them. + raise SystemExit("Inventory failed; no data changed. Check local authentication/network configuration.") diff --git a/scripts/verification-scopes.json b/scripts/verification-scopes.json index 7ca83ae3..1c6484fb 100644 --- a/scripts/verification-scopes.json +++ b/scripts/verification-scopes.json @@ -1,6 +1,49 @@ { "version": 1, "scopes": [ + { + "name": "workbench-render-reuse", + "paths": [ + "^src/components/(ReviewProblemPanel|ReviewTrace)\\.tsx$", + "^src/hooks/useAnnotationWorkSession\\.ts$", + "^src/lib/datetime\\.ts$", + "^tests/browser/(workbench-render-reuse\\.mjs|fixtures/workbench-render-reuse\\.tsx)$", + "^src/lib/annotation-work-mode\\.js$" + ], + "frontend": [ + "tests/frontend/workbench-render-churn.test.mjs", + "tests/frontend/annotation-buffer-reconciliation.test.mjs", + "tests/frontend/annotation-work-mode.test.mjs" + ], + "go": {}, + "task": [ + { + "argv": ["node", "tests/browser/workbench-render-reuse.mjs"], + "tests": true + } + ] + }, + { + "name": "delivery-v4-inventory", + "paths": ["^scripts/local/delivery_v4_inventory\\.py$", "^tests/agents/test_delivery_v4_inventory\\.py$"], + "frontend": [], + "go": {}, + "task": [ + { + "argv": [ + "python3", + "-m", + "unittest", + "discover", + "-s", + "tests/agents", + "-p", + "test_delivery_v4_inventory.py" + ], + "tests": true + } + ] + }, { "name": "legacy-v4-release", "paths": [ diff --git a/src/components/CaptureAnnotationWorkbench.tsx b/src/components/CaptureAnnotationWorkbench.tsx index 396f9ba1..d3a8e2a9 100644 --- a/src/components/CaptureAnnotationWorkbench.tsx +++ b/src/components/CaptureAnnotationWorkbench.tsx @@ -333,6 +333,7 @@ type Props = ReviewViewingProps & { import { annotationTimelineColors as colors } from "../lib/annotation-colors.js"; const formatTime = formatAnnotationTime; +const NO_DRAFTS: AnnotationDraft[] = []; const frameStep = 1 / 30; @@ -925,7 +926,7 @@ export function CaptureAnnotationWorkbench({ delete editors[selectedSlice.id]; if (editingAnnotation && !isQualityReview) editors[selectedSlice.id] = { annotation: editingAnnotation, endSelection }; - return Object.entries(editors).flatMap(([sliceId, editor]) => { + const drafts = Object.entries(editors).flatMap(([sliceId, editor]) => { const saved = segments.find((segment) => segment.id === editor.annotation.id); const selectingEnd = Boolean(editor.endSelection && !editor.endSelection.confirmed); // A split can already be in the parent's local segments while its blank @@ -939,6 +940,8 @@ export function CaptureAnnotationWorkbench({ return []; return [{ sliceId, annotation: editor.annotation, selectingEnd, isNew: !saved }]; }); + // Slice switches rebuild parkedEditors; an unchanged "no drafts" must not re-render the page. + return drafts.length ? drafts : NO_DRAFTS; }, [parkedEditors, selectedSlice.id, editingAnnotation, endSelection, segments, isQualityReview, continuousActions]); useEffect(() => { onDraftsChange?.(outstandingDrafts); diff --git a/src/components/ReviewProblemPanel.tsx b/src/components/ReviewProblemPanel.tsx index c742d06f..2179d758 100644 --- a/src/components/ReviewProblemPanel.tsx +++ b/src/components/ReviewProblemPanel.tsx @@ -1,6 +1,6 @@ import { formatAnnotationTime } from "../lib/annotation-time.js"; import { userErrorMessage } from "../lib/user-error-message.js"; -import { useLayoutEffect, useRef } from "react"; +import { useEffect, useLayoutEffect, useRef } from "react"; import type { useReviewDraft } from "../hooks/useReviewDraft"; import type { ReviewProblem } from "../services/api/review-draft"; import { opinionKey, type OpinionScope } from "../lib/review-opinions"; @@ -36,8 +36,24 @@ export function ReviewProblemPanel({ // 票 07:编辑器常驻内联,绑定当前所选目标档(未选按画面默认);无弹层。 const resident = review.editor || review.confirmClear || locked ? null : review.residentEditor; const problems = review.draft?.problems.filter((problem) => problem.scope !== "task") ?? []; + // Scroll the J/K-focused opinion (its card, then its timestamp row) into view when the + // focus moves or its list first renders — not on every re-render, which forced a layout + // per render while switching slices. + const panelRef = useRef(null); + const focusedScope = + focusedProblemId == null + ? null + : (review.cards.find((card) => card.problems.some((problem) => problem.id === focusedProblemId))?.scope ?? null); + const listReady = !review.loading && Boolean(review.draft); + useEffect(() => { + if (!focusedScope) return; + const card = panelRef.current?.querySelector(`[data-opinion-scope="${focusedScope}"]`); + card?.scrollIntoView({ block: "nearest" }); + card?.querySelector("button[data-review-focus]")?.scrollIntoView({ block: "nearest" }); + }, [focusedProblemId, focusedScope, listReady]); return (
@@ -74,7 +90,6 @@ export function ReviewProblemPanel({ aria-selected={review.selectedScope === card.scope || resident?.scope === card.scope} data-opinion-scope={card.scope} data-review-focus={cardFocused || undefined} - ref={cardFocused ? (node) => node?.scrollIntoView({ block: "nearest" }) : undefined} className="rounded border p-2 text-left aria-selected:border-orange-500 aria-selected:bg-orange-50/50 data-review-focus:ring-2 data-review-focus:ring-rose-400 data-review-focus:ring-inset dark:aria-selected:bg-orange-950/20" >
); -} +}); export function ReviewListTrace({ summary, diff --git a/src/hooks/useAnnotationWorkSession.ts b/src/hooks/useAnnotationWorkSession.ts index b55e14d7..16fe4cd9 100644 --- a/src/hooks/useAnnotationWorkSession.ts +++ b/src/hooks/useAnnotationWorkSession.ts @@ -77,7 +77,17 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work const viewportRef = useRef({ scope, suspended: false }); if (viewportRef.current.scope !== scope) viewportRef.current = { scope, suspended: false }; const supported = Boolean(navigator.locks); - const [observation, setObservation] = useState({ scope: "", blocked: false, error: false }); + const [observation, setObservationState] = useState({ scope: "", blocked: false, error: false }); + // The lock is polled every 2s; keep the same object when nothing changed so the page does not re-render. + const setObservation = useCallback( + (next: typeof observation) => + setObservationState((previous) => + previous.scope === next.scope && previous.blocked === next.blocked && previous.error === next.error + ? previous + : next, + ), + [], + ); const channelRef = useRef(null); const owns = useCallback((session?: AnnotationWorkSession | null) => { diff --git a/src/lib/annotation-work-mode.js b/src/lib/annotation-work-mode.js index 5d4b7b23..56886b14 100644 --- a/src/lib/annotation-work-mode.js +++ b/src/lib/annotation-work-mode.js @@ -83,13 +83,30 @@ export function reconcileAnnotationBufferItems(items, bufferItems, { userId, pro // Summary polls update lifecycle fields only on already-loaded records. Never // manufacture a full item or replace its subject/editor payload with a summary. +// Compare only the small JSON summary/processing projection, never task payloads. +function sameBufferValue(left, right) { + if (Object.is(left, right)) return true; + if (!left || !right || typeof left !== "object" || typeof right !== "object") return false; + if (Array.isArray(left) !== Array.isArray(right)) return false; + const keys = Object.keys(left); + return ( + keys.length === Object.keys(right).length && + keys.every((key) => Object.hasOwn(right, key) && sameBufferValue(left[key], right[key])) + ); +} + +export function reuseAnnotationBufferSnapshot(previous, next) { + return sameBufferValue(previous, next) ? previous : next; +} + export function reconcileAnnotationBufferSummaries(items, summaries, scope) { const existing = new Map(items.map((item) => [item.id, item])); const loaded = summaries.flatMap((summary) => { const item = existing.get(summary.id); if (!item) return []; const { sliceStatus, slicePhase, ...state } = summary; - return [{ ...item, ...state }]; + return [Object.keys(state).every((key) => sameBufferValue(item[key], state[key])) ? item : { ...item, ...state }]; }); - return reconcileAnnotationBufferItems(items, loaded, scope); + const next = reconcileAnnotationBufferItems(items, loaded, scope); + return next.length === items.length && next.every((item, index) => item === items[index]) ? items : next; } diff --git a/src/lib/datetime.ts b/src/lib/datetime.ts index 20be883c..8d4f61b8 100644 --- a/src/lib/datetime.ts +++ b/src/lib/datetime.ts @@ -16,16 +16,27 @@ function isValidDate(value: string | undefined) { return parseDateValue(value) !== null; } +// Building an Intl.DateTimeFormat is far costlier than formatting with one, and +// time-zone validity never changes at runtime, so both are cached per zone. +const timeZoneValidity = new Map(); +const formatterCache = new Map(); + export function isValidTimeZone(value: string | undefined) { if (!value || !value.trim()) { return false; } - try { - new Intl.DateTimeFormat(DEFAULT_LOCALE, { timeZone: value.trim() }); - return true; - } catch { - return false; + const zone = value.trim(); + let valid = timeZoneValidity.get(zone); + if (valid === undefined) { + try { + new Intl.DateTimeFormat(DEFAULT_LOCALE, { timeZone: zone }); + valid = true; + } catch { + valid = false; + } + timeZoneValidity.set(zone, valid); } + return valid; } function browserTimeZone() { @@ -48,11 +59,13 @@ export function resolveTimeZone(value: string | undefined) { } function formatterParts(value: string, timeZone: string, options: Intl.DateTimeFormatOptions) { - const formatter = new Intl.DateTimeFormat(DEFAULT_LOCALE, { - timeZone: resolveTimeZone(timeZone), - hour12: false, - ...options, - }); + const zone = resolveTimeZone(timeZone); + const key = `${zone}|${JSON.stringify(options)}`; + let formatter = formatterCache.get(key); + if (!formatter) { + formatter = new Intl.DateTimeFormat(DEFAULT_LOCALE, { timeZone: zone, hour12: false, ...options }); + formatterCache.set(key, formatter); + } const parsed = parseDateValue(value); if (!parsed) { return {} as Record; diff --git a/src/pages/AnnotationOperations.tsx b/src/pages/AnnotationOperations.tsx index 0ba04487..92fd185a 100644 --- a/src/pages/AnnotationOperations.tsx +++ b/src/pages/AnnotationOperations.tsx @@ -69,6 +69,7 @@ import { refillAnnotationWorkBuffer, hasDirectedAnnotationRework, reconcileAnnotationBufferSummaries, + reuseAnnotationBufferSnapshot, } from "../lib/annotation-work-mode.js"; import { useAnnotationWorkSession, type AnnotationWorkSession } from "../hooks/useAnnotationWorkSession"; import { alignSliceTimeline, initializeFrameAlignedSlices, sliceTimelineIssue } from "../lib/annotation-timeline.js"; @@ -5870,21 +5871,22 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: : []; if (!sameScope() || snapshotEpoch !== bufferReadEpochRef.current || annotationMutationScopeRef.current.busy()) return null; - setWorkBuffer(buffer); + setWorkBuffer((previous) => reuseAnnotationBufferSnapshot(previous, buffer)); if (!buffer.enabled) return buffer; const managedIds = bufferManagedIdsRef.current; - setHumanPools((pools) => ({ - ...pools, - mine: reconcileAnnotationBufferSummaries( - [...pools.mine, ...discovered.filter((item) => !pools.mine.some((old) => old.id === item.id))], + setHumanPools((pools) => { + const added = discovered.filter((item) => !pools.mine.some((old) => old.id === item.id)); + const mine = reconcileAnnotationBufferSummaries( + added.length ? [...pools.mine, ...added] : pools.mine, buffer.summaries, { userId: actorID, projectId: originProject, managedIds, }, - ), - })); + ); + return mine === pools.mine ? pools : { ...pools, mine }; + }); bufferManagedIdsRef.current = new Set(buffer.summaries.map((item) => item.id)); const current = detailRef.current; if ( diff --git a/tests/agents/test_delivery_v4_inventory.py b/tests/agents/test_delivery_v4_inventory.py new file mode 100644 index 00000000..398c9c51 --- /dev/null +++ b/tests/agents/test_delivery_v4_inventory.py @@ -0,0 +1,53 @@ +import importlib.util +from pathlib import Path +import unittest + +spec = importlib.util.spec_from_file_location("inventory", Path(__file__).resolve().parents[2] / "scripts/local/delivery_v4_inventory.py") +inventory = importlib.util.module_from_spec(spec) +spec.loader.exec_module(inventory) + + +class DeliveryV4InventoryTest(unittest.TestCase): + def test_accepted_recent_run_is_not_proof_of_v4(self): + row = inventory.classify_package({"id": "old", "status": "accepted"}, { + "manifest": {"schemaVersion": "droboticflow.delivery.manifest/v6"}}) + self.assertEqual(row["state"], "directory_requires_part_schema_inspection") + self.assertIn("pinned_revision_not_inspected", row["reasons"]) + + def test_missing_old_evidence_is_not_guessed(self): + row = inventory.classify_package({"id": "old"}, {"manifest": {}}, { + "schemaVersion": "droboticflow.slice-materialization/v3", "items": [ + {"sliceId": "kept", "sliceName": "historical name", "deliveryDisposition": "keep"}, + {"sliceId": "discarded", "deliveryDisposition": "discard"}]}) + self.assertEqual(row["slicesWithoutFrozenDictionary"], ["kept"]) + self.assertIn("pinned_revision_missing_original_source", row["reasons"]) + + def test_schema_marker_cannot_bypass_full_validation(self): + row = inventory.classify_package({"id": "candidate"}, {"manifest": {"schemaVersion": inventory.V4}}) + self.assertEqual(row["state"], "v4_candidate_requires_contract_validation") + + def test_empty_dictionary_is_missing_and_frozen_dictionary_is_preserved(self): + dictionary = {"id": "label", "version": 2, "tags": ["fixed"]} + revision = {"originalSource": {"bucket": "b"}, "items": [ + {"sliceId": "one", "dictionary": dictionary}, {"sliceId": "two", "dictionary": {}}]} + row = inventory.classify_package({"id": "candidate"}, {"manifest": {}}, revision) + self.assertEqual(row["slicesWithoutFrozenDictionary"], ["two"]) + self.assertEqual(dictionary["tags"], ["fixed"]) + + def test_directory_wrapper_does_not_prove_legacy_part_format(self): + for version in ("v3", "v6", "v7"): + row = inventory.classify_package({"id": "candidate"}, { + "manifest": {"schemaVersion": "droboticflow.delivery.manifest/" + version}}) + self.assertEqual(row["state"], "directory_requires_part_schema_inspection") + + def test_inventory_never_follows_content_or_login_redirects(self): + self.assertIsNone(inventory.NoRedirect().redirect_request(None, None, 302, "", {}, "https://external.invalid")) + + def test_invalid_origin_is_rejected_before_network_access(self): + for origin in ("file:///tmp/a", "https://u:p@example.com", "https://example.com/path", "https:///", "https://example.com?x=y"): + with self.assertRaises(ValueError): + inventory.ReadOnlyAPI(origin, {"phone": "synthetic", "password": "synthetic"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/browser/fixtures/workbench-render-reuse.tsx b/tests/browser/fixtures/workbench-render-reuse.tsx new file mode 100644 index 00000000..ef16dc4f --- /dev/null +++ b/tests/browser/fixtures/workbench-render-reuse.tsx @@ -0,0 +1,52 @@ +import { useEffect, useState } from "react"; +import { createRoot } from "react-dom/client"; +import { useReviewDraft } from "../../../src/hooks/useReviewDraft"; +import { ReviewProblemPanel } from "../../../src/components/ReviewProblemPanel"; +import { ReviewTracePanel, type ReviewTraceData } from "../../../src/components/ReviewTrace"; +import "../../../src/index.css"; + +function Fixture() { + const [tick, setTick] = useState(0); + const [focus, setFocus] = useState(null); + const [trace, setTrace] = useState({ + author: "Synthetic", + authorId: "synthetic-user", + supplier: "Synthetic supplier", + firstSubmittedAt: "2026-11-08T10:00:00Z", + revision: 1, + reviewer: "Synthetic reviewer", + rejections: 0, + events: [{ id: "e", kind: "提交", actor: "Synthetic", at: "2026-11-08T10:00:00Z", revision: 1 }], + }); + const review = useReviewDraft("render-reuse", "synthetic-user", true, { + writable: true, + snapshot: { itemId: "render-reuse", resultVersion: "v1", generation: 1 }, + headers: () => ({}), + handleError: () => {}, + }); + useEffect(() => { + review.onPosition({ + time: 1, + sliceId: "s", + navigationSliceId: "s", + timeBasis: "capture-seconds", + actionId: "a", + selectedActionId: "a", + actionStart: 0, + actionEnd: 31, + actions: [{ id: "a", start: 0, end: 31 }], + }); + }, [review.onPosition]); + return ( +
+ + {tick} + + + + + "Synthetic slice"} focusedProblemId={focus} /> +
+ ); +} +createRoot(document.getElementById("root")!).render(); diff --git a/tests/browser/workbench-render-reuse.mjs b/tests/browser/workbench-render-reuse.mjs new file mode 100644 index 00000000..df187da1 --- /dev/null +++ b/tests/browser/workbench-render-reuse.mjs @@ -0,0 +1,115 @@ +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import { chromium } from "playwright"; +import { createServer } from "vite"; +import { browserExecutableOptions } from "../../scripts/lib/browser-executable.mjs"; +const out = "local-data/test-results/workbench-render-reuse"; +await fs.mkdir(out, { recursive: true }); +const server = await createServer({ + configFile: "tests/browser/vite.platform-feedback.config.ts", + cacheDir: out + "/vite-cache", + server: { host: "127.0.0.1", port: 0 }, +}); +let browser, page; +const report = { passed: false, errors: [], cases: [] }; +try { + await server.listen(); + const origin = server.resolvedUrls.local[0]; + browser = await chromium.launch({ ...browserExecutableOptions(), headless: true, args: ["--no-proxy-server"] }); + page = await browser.newPage({ viewport: { width: 900, height: 750 } }); + page.on("pageerror", (error) => report.errors.push(error.message)); + await page.addInitScript(() => { + window.scrollCalls = []; + const scroll = Element.prototype.scrollIntoView; + Element.prototype.scrollIntoView = function (...args) { + window.scrollCalls.push(this.getAttribute("data-problem-id") || this.getAttribute("data-opinion-scope")); + return scroll.apply(this, args); + }; + window.dateFormats = 0; + const format = Intl.DateTimeFormat.prototype.formatToParts; + Intl.DateTimeFormat.prototype.formatToParts = function (...args) { + window.dateFormats++; + return format.apply(this, args); + }; + }); + await page.route("**/*", async (route) => { + const url = new URL(route.request().url()); + if (url.origin !== new URL(origin).origin) return route.abort(); + if (url.pathname === "/__render-reuse") + return route.fulfill({ + contentType: "text/html", + body: await server.transformIndexHtml( + "/__render-reuse", + '
', + ), + }); + if (url.pathname.endsWith("/review-draft")) { + assert.equal(route.request().method(), "GET"); + return route.fulfill({ + json: { + draft: { + itemId: "render-reuse", + stageId: "quality_review", + reviewRound: 1, + resultVersion: "v1", + modelVersion: 2, + version: 1, + updatedAt: "", + problems: Array.from({ length: 30 }, (_, n) => ({ + id: `p${n}`, + scope: "timestamp", + sliceId: "s", + atSeconds: n, + text: `Synthetic note ${n}`, + severity: "major", + })), + }, + }, + }); + } + if (url.pathname.startsWith("/api/")) throw Error("Unexpected fixture API request"); + return route.continue(); + }); + await page.goto(origin + "__render-reuse"); + await page.locator("[data-opinion-scope=timestamp]").getByText("Synthetic note 29", { exact: true }).waitFor(); + await page.getByRole("button", { name: "定位末条", exact: true }).click(); + await page.waitForFunction( + () => document.querySelectorAll("[data-opinion-scope=timestamp] button[data-review-focus=true]").length === 1, + ); + await page.waitForFunction(() => window.scrollCalls.length === 2); + const before = await page.evaluate(() => ({ scrolls: window.scrollCalls.length, formats: window.dateFormats })); + assert.equal(before.scrolls, 2); + for (let i = 0; i < 5; i++) await page.getByRole("button", { name: "无关刷新", exact: true }).click(); + await page.getByText("5", { exact: true }).waitFor(); + assert.deepEqual( + await page.evaluate(() => ({ scrolls: window.scrollCalls.length, formats: window.dateFormats })), + before, + ); + report.cases.push("unrelated renders neither scroll opinions nor reformat unchanged trace"); + await page.getByRole("button", { name: "定位首条", exact: true }).click(); + await page.waitForFunction((n) => window.scrollCalls.length === n + 2, before.scrolls); + const row = page.locator("[data-opinion-scope=timestamp] button[data-review-focus=true]"); + assert.match(await row.textContent(), /Synthetic note 0$/); + const visible = await row.evaluate((el) => { + const r = el.getBoundingClientRect(), + p = el.parentElement.getBoundingClientRect(); + return r.top >= p.top - 1 && r.bottom <= p.bottom + 1; + }); + assert.equal(visible, true); + report.cases.push("changing focus reveals the target timestamp within its scroll list"); + await page.getByRole("button", { name: "更新版本", exact: true }).click(); + await page.getByText("V2", { exact: true }).waitFor(); + assert.ok((await page.evaluate(() => window.dateFormats)) > before.formats); + await page.screenshot({ path: out + "/focused.png", fullPage: true }); + assert.deepEqual(report.errors, []); + report.passed = true; +} catch (error) { + report.error = String(error); + process.exitCode = 1; + await page?.screenshot({ path: out + "/failure.png", fullPage: true }).catch(() => {}); +} finally { + await fs.writeFile(out + "/report.json", JSON.stringify(report, null, 2)); + await browser?.close(); + await server.close(); + console.log(JSON.stringify(report)); +} diff --git a/tests/frontend/annotation-buffer-reconciliation.test.mjs b/tests/frontend/annotation-buffer-reconciliation.test.mjs index 5ff0885e..14e326ef 100644 --- a/tests/frontend/annotation-buffer-reconciliation.test.mjs +++ b/tests/frontend/annotation-buffer-reconciliation.test.mjs @@ -2,7 +2,11 @@ import test from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import ts from "typescript"; -import { refillAnnotationWorkBuffer, reconcileAnnotationBufferSummaries } from "../../src/lib/annotation-work-mode.js"; +import { + refillAnnotationWorkBuffer, + reconcileAnnotationBufferSummaries, + reuseAnnotationBufferSnapshot, +} from "../../src/lib/annotation-work-mode.js"; const source = fs.readFileSync(new URL("../../src/pages/AnnotationOperations.tsx", import.meta.url), "utf8"); function callback(name, env) { const ast = ts.createSourceFile("page.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); @@ -56,11 +60,12 @@ function fixture({ mine = [item("gone")], items = [], read } = {}) { }, workSession: { hasContinuousIntent: () => false, pauseContinuous: () => {} }, viewportBlocksDispatch: () => false, - setWorkBuffer: (x) => (buffer = x), + setWorkBuffer: (x) => (buffer = typeof x === "function" ? x(buffer) : x), setHumanPools: (f) => (pools = f(pools)), setTasks: () => {}, setExternalBufferTaskId: (x) => (missing = x), reconcileAnnotationBufferSummaries, + reuseAnnotationBufferSnapshot, }; return { env, @@ -214,3 +219,70 @@ test("scope changes during first detail hydration discard the entire late snapsh assert.equal(f.state().buffer, null); assert.deepEqual(f.state().pools.mine, []); }); + +test("stable summary polls preserve array, detail and draft references without traversing payload", () => { + const summary = { id: "a", status: "in_progress", display: { captureId: "capture" } }; + const full = item("a", { display: summary.display }); + Object.defineProperty(full, "subject", { + enumerable: true, + get() { + throw Error("must not inspect task payload"); + }, + }); + const items = [full]; + assert.equal( + reconcileAnnotationBufferSummaries(items, [structuredClone(summary)], { userId: "u", projectId: "p" }), + items, + ); +}); + +test("summary lifecycle and display changes are applied without replacing drafts", () => { + const payload = { draft: "unsaved" }; + const before = item("a", { version: 1, reviewRound: 0, subject: { payload } }); + for (const change of [ + { version: 2 }, + { reviewRound: 1 }, + { status: "rework" }, + { assignedUserId: "other" }, + { currentStageId: "semantic_annotation" }, + { pendingCombinedSubmissionId: "submission" }, + { sourceValidationStatus: "failed" }, + { display: { captureId: "updated" } }, + ]) { + const next = reconcileAnnotationBufferSummaries([before], [{ id: "a", ...change }], { + userId: "u", + projectId: "p", + }); + assert.notEqual(next[0], before); + assert.equal(next[0].subject.payload, payload); + for (const [key, value] of Object.entries(change)) assert.deepEqual(next[0][key], value); + } +}); + +test("snapshot reuse observes processing, phases, capacity and membership changes", async () => { + const before = { + enabled: true, + capacity: 8, + occupied: 1, + summaries: [{ id: "a", slicePhase: "ready" }], + processing: { a: { status: "pending", kind: "submission" } }, + }; + assert.equal(reuseAnnotationBufferSnapshot(before, structuredClone(before)), before); + for (const change of [ + { enabled: false }, + { capacity: 4 }, + { occupied: 0 }, + { summaries: [] }, + { summaries: [{ id: "a", slicePhase: "failed" }] }, + { processing: { a: { status: "failed", kind: "submission", error: "retry" } } }, + ]) { + const next = { ...before, ...change }; + assert.equal(reuseAnnotationBufferSnapshot(before, next), next); + } + const f = fixture({ mine: [item("a")], items: [{ id: "a", status: "in_progress" }] }); + await f.run(); + const stable = f.state(); + await f.run(); + assert.equal(f.state().pools, stable.pools); + assert.equal(f.state().buffer, stable.buffer); +}); diff --git a/tests/frontend/workbench-render-churn.test.mjs b/tests/frontend/workbench-render-churn.test.mjs new file mode 100644 index 00000000..376974b6 --- /dev/null +++ b/tests/frontend/workbench-render-churn.test.mjs @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { formatClockTime, formatCompactDateTime, formatDateTime, isValidTimeZone } from "../../src/lib/datetime.ts"; + +test("cached date formatters keep the exact output and fallbacks", () => { + const RealFormat = Intl.DateTimeFormat; + let constructed = 0; + Intl.DateTimeFormat = function (...args) { + constructed++; + return new RealFormat(...args); + }; + Object.assign(Intl.DateTimeFormat, RealFormat); + try { + const at = "2026-10-27T01:02:03.456789Z"; + assert.equal(formatCompactDateTime(at, "Asia/Shanghai"), "2026-10-27 09:02"); + assert.equal(formatDateTime(at, "UTC"), "2026-10-27 01:02:03"); + assert.equal(formatClockTime(at, "America/New_York"), "21:02:03"); + assert.equal(formatCompactDateTime("not a date", "Asia/Shanghai"), "not a date"); + assert.equal(formatCompactDateTime("", "Asia/Shanghai"), "--"); + assert.equal(isValidTimeZone("Mars/Base"), false); + assert.equal(isValidTimeZone(" Asia/Tokyo "), true); + constructed = 0; + for (let i = 0; i < 50; i++) formatCompactDateTime(at, "Asia/Shanghai"); + assert.equal(constructed, 0, "repeated formatting reuses the cached formatter and zone check"); + } finally { + Intl.DateTimeFormat = RealFormat; + } +});