From 9d331e71904adb3904c54566c78bdff0ee9d0815 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Fri, 16 Oct 2026 12:42:28 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Persist=20explicit=20continuous?= =?UTF-8?q?=20work=20mode=20and=20bound=20refill?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../continuous-work-toggle-20261016/spec.md | 20 ++ CONTEXT.md | 4 +- .../0003-bounded-annotation-work-buffer.md | 12 +- docs/annotation-keyboard-guide.zh-CN.md | 12 +- docs/annotation-workspace-layout.md | 8 +- src/components/AnnotationWorkModeToggle.tsx | 29 ++ src/hooks/useAnnotationWorkSession.ts | 67 +++- src/lib/annotation-work-mode.js | 65 ++++ src/pages/AnnotationOperations.tsx | 292 +++++++++++------- .../fixtures/annotation-work-mode.html | 1 + .../browser/fixtures/annotation-work-mode.tsx | 131 ++++++++ tests/frontend/annotation-work-entry.test.mjs | 179 +++++++++++ tests/frontend/annotation-work-mode.test.mjs | 145 +++++++++ 13 files changed, 841 insertions(+), 124 deletions(-) create mode 100644 .scratch/continuous-work-toggle-20261016/spec.md create mode 100644 src/components/AnnotationWorkModeToggle.tsx create mode 100644 src/lib/annotation-work-mode.js create mode 100644 tests/browser/fixtures/annotation-work-mode.html create mode 100644 tests/browser/fixtures/annotation-work-mode.tsx create mode 100644 tests/frontend/annotation-work-entry.test.mjs create mode 100644 tests/frontend/annotation-work-mode.test.mjs diff --git a/.scratch/continuous-work-toggle-20261016/spec.md b/.scratch/continuous-work-toggle-20261016/spec.md new file mode 100644 index 00000000..a74a1ad7 --- /dev/null +++ b/.scratch/continuous-work-toggle-20261016/spec.md @@ -0,0 +1,20 @@ +# Persistent annotation work mode +Status: resolved + +Customer request 2026-10-16: one lit/unlit control beside personal buffer selects automatic continuous work or manual claim. Persist per account in this browser; first use defaults to manual. Focus entry, refresh and task selection never silently enable it. Manual task selection/resume must not allocate; only explicit random-claim action may allocate. Off stops subsequent auto claims/switches immediately, preserving drafts, owned tasks and accepted jobs. An already sent request may finish and remain assigned; do not lose its receipt. + +Also resolve diagnosed under-capacity directed-rework refill loop: keep rework-first server behavior, stop automatic refill on an already owned item or unchanged occupancy and bound attempts. Preserve API/storage/task contracts, permissions, atomic receipts, capacity and old in-flight requests. No server schema or migrations. No push/PR/deploy authorized in this task. + +Verify real coordinator progress/no-progress, real hook preference persistence and cross-tab off, manual focus entry, explicit claim, toggling during pending request, refresh, account change and draft preservation. Local replica/synthetic UI only; no production business writes. + +## Answer and verification + +Implemented a single switch adjacent to personal buffer (legacy flows retain a mode control without buffer capacity). Account/browser preference defaults to manual and is shared across projects and same-origin tabs. Focus entry uses that preference. Selecting owned items resumes without claim; an explicit random button is available even after refresh before the focused session is active. Off stays usable during requests and stops following auto dispatches, retaining confirmed late allocations. Storage failure cannot enable auto; a failed off persistence stops this document and displays a warning. + +Refill now uses one bounded coordinator. Known directed rework suppresses automatic claim attempts, existing-item/no-progress responses stop the loop, and rework is preferred among ready buffered items. Existing API, permission, receipt, capacity and task data contracts are unchanged. + +Evidence: diagnostic actual server handler reproduced three 200 responses returning the same rework at 1/2 before this fix (main-root local-data/verification/random-claim-20261016/local-refill-repro.log). New known-rework regression also failed before its loop condition was corrected; final executable mode/coordinator/actual page callback regressions pass 12/12. Frontend gate: 13 known failures against 14 baseline, no new failures, baseline untouched. Lint, formatting, production build and targeted server rework/capacity/replay tests pass. + +CUA synthetic UI uses actual session hook, switch and coordinator: default manual and click-existing produce zero claims; on permits allocation; off preserves draft and confirmed in-flight work and stops following requests; reopen stays off; second-tab off updates active tab. Full local snapshot API was started with verify-existing/external processor, BOS disabled. Final built full platform displayed the control beside 4/2 personal buffer; manual Start Work entered an already-owned demo task without enabling continuous mode. Full focused editing is constrained by IAB 1280px viewport versus existing 1413px minimum; no viewport guard bypass or complete focus editing acceptance is claimed. + +Screenshots: main-root local-data/verification/work-mode-20261016/actual-task-pool.png and manual-mode.png. Logs in worktree local-data/pr-checks/work-mode-*. No production business writes or new deployment, PR or push performed. diff --git a/CONTEXT.md b/CONTEXT.md index db6ec525..41255921 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -83,7 +83,9 @@ _Avoid_:切片编辑模式(2026-10-13 交互重设计,原地挪边界模 **送检**:标注结果及其审核数据已经准备完成,任务交给质检环节等待处理。送检成功不代表质检通过。 _Avoid_:质检完成(属于后续审核结果) -**连续工作**:标注员在所选项目内接续处理本人可操作任务的工作方式;切片在后台生成时可处理另一任务,任务实际交给质检后再按个人缓冲容量补充随机任务。 +**连续工作**:标注员明确开启后,在所选项目内接续处理本人可操作任务的工作方式;切片在后台生成时可处理另一任务,任务实际交给质检后再按个人缓冲容量补充随机任务。进入专注视图、打开任务或继续已有任务本身不代表开启连续工作。 + +**手动接取**:标注员关闭连续工作后,仅在主动点击随机领取时接取新任务;选择和处理本人已有任务不触发自动补领或自动切换。工作模式选择须明确保留,不能因重新进入工作页而改为连续。 **个人任务缓冲池**:当前标注员在一个项目内已经领取、尚未实际交给质检的任务集合;包括正在切片生成、送检处理或失败待处理的任务,用于在后台处理期间继续其他可操作任务。 _Avoid_:公共可领取任务池(其中的任务尚未归属当前标注员) diff --git a/docs/adr/0003-bounded-annotation-work-buffer.md b/docs/adr/0003-bounded-annotation-work-buffer.md index 11a5f4dc..0442afc7 100644 --- a/docs/adr/0003-bounded-annotation-work-buffer.md +++ b/docs/adr/0003-bounded-annotation-work-buffer.md @@ -4,8 +4,16 @@ status: accepted # 后台切片期间使用有容量限制的个人任务缓冲池 -切片生成会让串行工作停顿,因此泛宇人工标注改为在后台任务被确定受理后接续处理其他可操作任务;个人缓冲池按账号与项目计数,默认 2、可设 2–8,手动随机领取和自动补领共用容量约束。处理中、失败待处理的任务继续占位,只有实际送检成功才腾位,避免将“已受理”误当完成而持续占用更多任务;调小容量保留既有任务,退回仍进入公共可领取池。 +切片生成会让串行工作停顿,因此泛宇人工标注改为在后台任务被确定受理后接续处理其他可操作任务;个人缓冲池按账号与项目计数,默认 2、可设 2–8,手动随机领取和自动补领共用容量约束。处理中、失败待处理的任务继续占位,只有实际送检成功才腾位,避免将“已受理”误当完成而持续占用更多任务;调小容量保留既有任务;返工定向归还按 CONTEXT.md 当前规则处理。 开始/继续时补齐,优先处理已生成待标注的任务;单个后台任务失败不阻断其他任务。暂停或返回任务池停止自动切换与补领,但不取消后台处理;刷新后须明确继续,以在连续作业效率与操作者可控性之间保留边界。 -这是 2026-09-21 Q23–Q28、Q31 已确认的目标规则,尚未实施;具体交互与历史规则替代见[追加讨论](../../.scratch/annotation-contiguous-actions/supplement-20260921.md)。任务切换仍遵守 [ADR-0001](./0001-annotation-undo-stage-boundary.md)的撤销边界。 +容量缓冲已经实施。原始依据是 2026-09-21 Q23–Q28、Q31;具体交互与历史规则替代见[追加讨论](../../.scratch/annotation-contiguous-actions/supplement-20260921.md)。任务切换仍遵守 [ADR-0001](./0001-annotation-undo-stage-boundary.md)的撤销边界。 + +## 2026-10-16 工作模式选择(替代原自动开启规则) + +个人任务池旁提供唯一总开关。首次默认手动,按账号在当前浏览器记住选择,跨项目和页面沿用,不跨设备同步。点亮后才允许连续接取和自动切换;熄灭立即停止后续补领和切换,已有任务、当前编辑及已受理后台处理保留。专注视图、开始/继续工作、刷新与点击已有任务均不得擅自将手动改为连续。刷新后仍需显式恢复工作会话,保存的“开启”选择不等于自动获取页面锁或后台静默领取。错误或明确暂停会保存关闭状态;视口临时暂停只暂停执行,不改变开关。 + +手动模式只有明确点击随机领取才发起领取;点击本人任务只恢复已有任务。未知领取结果保留原请求编号,由下一次明确随机领取核对,不能因进入专注页自动重发。其他标签页关闭开关会阻断后续自动请求。浏览器无法保存选择时不允许开启自动接取。 + +返工优先仍保留:返回已有返工任务不等于新分配。自动补领遇到已有任务或占用没有增加即停止,并有次数上限,不能为填满容量而重复请求。上述选择规则替代本记录早期关于开始时自动补齐的默认行为;容量、实际送检后释放占位及任务归属约束不变。 diff --git a/docs/annotation-keyboard-guide.zh-CN.md b/docs/annotation-keyboard-guide.zh-CN.md index 7c730d89..6eb4789a 100644 --- a/docs/annotation-keyboard-guide.zh-CN.md +++ b/docs/annotation-keyboard-guide.zh-CN.md @@ -4,13 +4,13 @@ ## 一条任务怎么做 -1. 在标注中心选择项目,点击“开始工作”。页面在当前标签页切换到“标注工作页”;有尚未完成的任务时先继续它。 +1. 在标注中心选择项目,在个人任务池旁选择“手动接取”或点亮“连续工作 · 自动接取”。首次默认手动,选择按账号保存在当前浏览器。点击已有任务继续,只有明确点击随机领取或开启自动接取才分配新任务。 2. 看视频,按 `C` 在当前帧切片。视频会暂停在切点;按空格继续往后看。 3. 给切片选择字典名称。确认划分后,按 `Ctrl/⌘+Enter` 打开生成确认,再单独按一次 `Enter` 执行。等待生成完成。 4. 进入动作描述阶段,按 `N` 标记起点,继续观看,在终点再次按 `N`(或 `Enter`)。 5. 按 `F` 选描述字典,或按 `Enter` 开始手工输入。字典模板可以修改。按 `Ctrl/⌘+Enter` 保存这一条描述。 6. 检查完所有切片后,处理完全部草稿,再按 `Ctrl/⌘+Enter` 打开送检确认,单独按 `Enter` 确认。 -7. 连续工作开启时,只有当前任务确实送检成功,才会领取下一条。需要休息时选“完成当前任务后停止”。 +7. 连续工作开启时,只有当前任务确实送检成功,才会领取下一条。需要停止自动接取时熄灭个人任务池旁的总开关。 Windows/Linux 下使用 Ctrl;macOS 下常用组合键可使用 ⌘。批量无效使用 Ctrl+X。 @@ -115,9 +115,9 @@ Ctrl/⌘+Enter 有三种结果:当前有草稿就保存它;其他片还有 打开确认后,松开按键,再按一次 Enter 才执行;Esc 取消。“处理中”表示后台仍在工作,请等最终结果。 -刷新或重新打开工作页后,先在“继续已领取任务”中选择任务,再点“继续工作”;这次只恢复当前任务,不会默默领取新任务。想继续自动接下一条,点“开始连续工作”或“恢复连续工作”。如果上次领取的结果还不确定,使用“核对领取结果并开始连续工作”;页面会先找回同一次领取的结果,再继续。同一浏览器的同一账号与项目只有一个活动工作页。第二页显示“返回活动工作页”,请回原标签处理。原页面退出或关闭后,再到另一页点“继续工作”。 +刷新或重新打开工作页后,点击已有任务或“继续工作”恢复已保存内容,并沿用任务池旁的总开关。熄灭后一直保持手动,进入专注视图、点击任务或下次打开均不会自动开启;手动模式仅点击“随机领取任务”才接取新任务。点亮后允许自动接取,页面锁仍需正常取得。未保存草稿与撤销历史无法跨刷新恢复。 -遇到空池、网络不确定、后台失败或权限变化,连续工作会暂停。按页面提供的恢复入口处理;不确定的领取重试会沿用同一次请求,避免多领一条。“完成当前任务后停止”不会释放已经领取的任务。 +遇到空池、网络结果不确定或权限变化,连续工作会关闭并记住手动状态。领取结果未知时再次手动点击“随机领取任务”,沿用原请求编号核对,不会重复分配。熄灭不会撤回已发出的请求,其确认结果仍归本人;当前编辑和后台任务保留。同一浏览器同账号同项目的活动工作页互斥规则不变。 ## 快速排查 @@ -126,8 +126,8 @@ Ctrl/⌘+Enter 有三种结果:当前有草稿就保存它;其他片还有 | 快捷键没有控制视频 | 先退出文字输入或字典,按一次 Esc 回工作区;弹窗内按提示操作 | | 提交时提示其他切片还有草稿 | 点击提示中的切片,保存或取消那里的草稿,再提交 | | 显示“处理中” | 等待完成;此时不重复保存、撤销或领取 | -| 显示领取结果不确定 | 点击“核对领取结果并开始连续工作”,不要另开页面反复领取 | -| 显示没有可领取任务 | 连续工作已暂停,稍后显式恢复 | +| 显示领取结果不确定 | 手动点击“随机领取任务”核对原请求,不要另开页面反复领取 | +| 显示没有可领取任务 | 开关已关闭,稍后明确点亮恢复 | | 第二个页面不能继续 | 回到原活动页;原页正常退出或关闭后,再在这里继续 | | 刷新后撤销没有效果 | 刷新不保留撤销历史,只恢复已保存数据 | diff --git a/docs/annotation-workspace-layout.md b/docs/annotation-workspace-layout.md index f48d0484..ae743255 100644 --- a/docs/annotation-workspace-layout.md +++ b/docs/annotation-workspace-layout.md @@ -1,6 +1,6 @@ # 标注工作页操作说明 -选择项目后点击“开始工作”,即可在当前标签页连续标注。系统先续做本人未完成任务,没有时才在有权限的项目与供应商范围内随机领取;领取前不能挑选视频。 +选择项目后,个人任务池旁的总开关选择工作模式:点亮“连续工作 · 自动接取”才自动接取,熄灭“手动接取”时只有点击“随机领取任务”才接取新任务。首次默认手动;按账号在当前浏览器保存,切换项目、进入专注视图或重新打开都沿用选择。点击已有任务只恢复它,不会开启连续工作。领取前不能挑选视频。 ## 连接方式与手动模式 @@ -14,9 +14,9 @@ 首次进入默认使用专注视图:平台导航收起,左侧是同步双视频、播放控制和时间轴,右侧是当前切片或动作描述编辑区。页面顶部始终保留“切回原布局”和“返回任务池”。 -连续工作中,当前任务真实送检成功后会接续下一条。准备结束时点击“完成当前任务后停止”:仍可完成手中任务,但不会再领取下一条,也不会释放已经领取的任务。需要接着做时点击“恢复连续工作”。任务池为空时连续工作暂停,不会反复领取。 +点亮总开关后,连续工作可在后台处理期间接续其他任务,实际送检后补足容量。熄灭立即进入手动模式,停止后续补领和自动切换;当前任务、草稿和已受理后台任务保留。任务池为空、网络结果不确定或权限变化时关闭并记住手动状态,须明确点亮才恢复。视口临时暂停不改变选择。已有返工任务优先恢复,自动补领不会重复请求同一任务。 -“返回任务池”会执行原有离开保护。若有未保存草稿,选择继续编辑可返回当前工作;确认离开会丢弃页面中未保存的编辑。刷新、关闭标签页或重新打开后,必须显式点击“继续工作”,只恢复服务端已经保存的内容,不能恢复浏览器草稿与撤销历史。 +“返回任务池”会执行原有离开保护。若有未保存草稿,选择继续编辑可返回当前工作;确认离开会丢弃页面中未保存的编辑。刷新、关闭标签页或重新打开后,须显式点击已有任务或“继续工作”,沿用保存的工作模式并恢复服务端已经保存的内容,不能恢复浏览器草稿与撤销历史。 安全连接下,同一浏览器的同源标签页中,同一账号、同一项目只能有一个活动工作页。第二个标签页提示已有活动页时,返回原页继续;原页退出或关闭后再恢复。不要通过反复开页重复领取。 @@ -58,7 +58,7 @@ 低于底线时,页面暂停播放与自动接续,保留当前任务、播放位置、草稿和历史。放大窗口或降低浏览器缩放后,必须点击“继续当前工作”;仅调整尺寸不会恢复工作,视频仍需手动播放。此前选择的“完成当前任务后停止”仍然有效。 -已发出的保存、生成、送检或领取请求可能在暂停期间完成。系统会核对原请求,不能把暂停当作取消,也不会因窗口改变重复领取。提示结果未知时,使用“核对阶段结果”或“核对领取结果并开始连续工作”;领取核对沿用原请求编号。权限变化或活动页冲突须先处理,恢复窗口不会解除这些限制。 +已发出的保存、生成、送检或领取请求可能在暂停期间完成。系统会核对原请求,不能把暂停当作取消,也不会因窗口改变重复领取。提示结果未知时,使用“核对阶段结果”;领取结果未知时手动点击“随机领取任务”;领取核对沿用原请求编号。权限变化或活动页冲突须先处理,恢复窗口不会解除这些限制。 随时可点击“切回原布局”,返回旧版的滚动布局;“进入专注视图”再次收起导航。运行中切换保留任务、阶段、选中项、播放帧、各片草稿、撤销记录及连续工作选择,不会保存或重新领取。布局偏好按当前账号和当前浏览器保存,不会串到其他账号;浏览器禁止本地存储时,当前切换仍可用,但下次未必记住。 diff --git a/src/components/AnnotationWorkModeToggle.tsx b/src/components/AnnotationWorkModeToggle.tsx new file mode 100644 index 00000000..2143e66b --- /dev/null +++ b/src/components/AnnotationWorkModeToggle.tsx @@ -0,0 +1,29 @@ +import { cn } from "../lib/utils"; + +export function AnnotationWorkModeToggle({ + enabled, + disabled, + onToggle, +}: { + enabled: boolean; + disabled: boolean; + onToggle: () => void; +}) { + return ( + + ); +} diff --git a/src/hooks/useAnnotationWorkSession.ts b/src/hooks/useAnnotationWorkSession.ts index bd9cf73f..b55e14d7 100644 --- a/src/hooks/useAnnotationWorkSession.ts +++ b/src/hooks/useAnnotationWorkSession.ts @@ -1,4 +1,18 @@ -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { + readContinuousWorkMode, + writeContinuousWorkMode, + continuousWorkModeEvent, +} from "../lib/annotation-work-mode.js"; + +function subscribeToWorkMode(listener: () => void) { + window.addEventListener("storage", listener); + window.addEventListener(continuousWorkModeEvent, listener); + return () => { + window.removeEventListener("storage", listener); + window.removeEventListener(continuousWorkModeEvent, listener); + }; +} export type AnnotationWorkSession = { readonly scope: string; @@ -36,6 +50,25 @@ function releaseSession(session: AnnotationWorkSession | null) { /** Browser-local ownership only; backend task assignment remains authoritative. */ export function useAnnotationWorkSession(userId: string, projectId: string, workPage: boolean) { const scope = userId && projectId ? `droboticflow.annotation-work:${JSON.stringify([userId, projectId])}` : ""; + const continuousEnabled = useSyncExternalStore( + subscribeToWorkMode, + () => readContinuousWorkMode(userId), + () => false, + ); + const prefersContinuous = useCallback(() => readContinuousWorkMode(userId), [userId]); + const setContinuousEnabled = useCallback( + (enabled: boolean) => { + // Persist before enabling; a storage failure must never silently allow claims. + if (!enabled && ownedSession?.scope === scope) { + ownedSession.epoch++; + ownedSession.continuous = false; + ownedSession.pauseReason = "手动模式:仅点击随机领取时接取新任务。"; + notify(); + } + writeContinuousWorkMode(userId, enabled); + }, + [userId, scope], + ); const identityRef = useRef({ scope }); if (identityRef.current.scope !== scope) identityRef.current = { scope }; const [, render] = useState(0); @@ -124,6 +157,15 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work }; }, [scope, workPage, owns]); + useEffect(() => { + if (!continuousEnabled && owns() && ownedSession.continuous) { + ownedSession.epoch++; + ownedSession.continuous = false; + ownedSession.pauseReason = "手动模式:仅点击随机领取时接取新任务。"; + notify(); + } + }, [continuousEnabled, owns]); + const acquire = useCallback(async (): Promise => { const identity = identityRef.current; if (!identity.scope) return { status: "stale" }; @@ -185,22 +227,30 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work (session: AnnotationWorkSession, enabled: boolean, reason = "") => { if (!owns(session)) return false; ownedSession.epoch++; - ownedSession.continuous = enabled; + ownedSession.continuous = enabled && prefersContinuous(); ownedSession.pauseReason = reason; notify(); return true; }, - [owns], + [owns, prefersContinuous], ); const pauseContinuous = useCallback( (reason: string) => { + // Pauses also persist manual mode, so re-entry cannot undo the stop. + if (owns()) { + try { + writeContinuousWorkMode(userId, false); + } catch { + /* The in-memory stop still takes effect. */ + } + } if (!owns() || !ownedSession.continuous) return; ownedSession.epoch++; ownedSession.continuous = false; ownedSession.pauseReason = reason; notify(); }, - [owns], + [owns, userId], ); // Viewport suspension never changes user intent or clears a hard pause reason. const setViewportSuspended = useCallback((suspended: boolean) => { @@ -209,8 +259,8 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work render((version) => version + 1); }, []); const hasContinuousIntent = useCallback( - () => owns() && Boolean(ownedSession?.active && ownedSession.continuous), - [owns], + () => prefersContinuous() && owns() && Boolean(ownedSession?.active && ownedSession.continuous), + [owns, prefersContinuous], ); const isViewportSuspended = useCallback(() => viewportRef.current.suspended, []); const isContinuous = useCallback( @@ -219,12 +269,15 @@ export function useAnnotationWorkSession(userId: string, projectId: string, work ); return { + continuousEnabled, + prefersContinuous, + setContinuousEnabled, continuousEpoch: () => ownedSession?.epoch ?? -1, viewportSuspended: isViewportSuspended(), setViewportSuspended, isViewportSuspended, hasContinuousIntent, - continuous: owns() && Boolean(ownedSession?.continuous), + continuous: continuousEnabled && owns() && Boolean(ownedSession?.continuous), pauseReason: owns() ? ownedSession?.pauseReason || "" : "", setContinuous, pauseContinuous, diff --git a/src/lib/annotation-work-mode.js b/src/lib/annotation-work-mode.js new file mode 100644 index 00000000..4c24d01a --- /dev/null +++ b/src/lib/annotation-work-mode.js @@ -0,0 +1,65 @@ +const keyFor = (userId) => `droboticflow.annotation-continuous:${JSON.stringify(userId)}`; +const manualUntilSaved = new Set(); +export const continuousWorkModeEvent = "droboticflow:annotation-work-mode"; + +// Preference is per account/browser, independent of project, route and lock ownership. +// Missing or inaccessible storage always defaults to manual allocation. +export function readContinuousWorkMode(userId, storage) { + if (!userId || manualUntilSaved.has(userId)) return false; + try { + storage ??= globalThis.localStorage; + return storage?.getItem(keyFor(userId)) === "on"; + } catch { + return false; + } +} +export function writeContinuousWorkMode(userId, enabled, storage) { + // Even when persistence fails, stopping must take effect in this document. + if (!enabled) manualUntilSaved.add(userId); + try { + storage ??= globalThis.localStorage; + if (!userId || !storage) throw new Error("无法保存工作模式,请检查浏览器存储权限。"); + storage.setItem(keyFor(userId), enabled ? "on" : "off"); + manualUntilSaved.delete(userId); + } finally { + if (typeof window !== "undefined") window.dispatchEvent(new Event(continuousWorkModeEvent)); + } +} + +export function hasDirectedAnnotationRework(items) { + return items.some( + (item) => + item.currentStageId === "annotation_combined" && + item.reviewRound > 0 && + ["claimed", "rework"].includes(item.status), + ); +} + +// A successful claim may resume an already-owned rework instead of allocating. +// Stop on that response (or any lack of progress); never try to fill forever. +export async function refillAnnotationWorkBuffer({ readBuffer, claim, shouldContinue, onClaim, refill }) { + let buffer = await readBuffer(); + const attempts = Math.min(8, Math.max(0, buffer.capacity - buffer.occupied)); + for ( + let attempt = 0; + refill && + buffer.enabled && + !hasDirectedAnnotationRework(buffer.items) && + buffer.occupied < buffer.capacity && + attempt < attempts && + shouldContinue(); + attempt++ + ) { + const previous = buffer; + const response = await claim(); + if (response.item && response.task) onClaim(response); + buffer = await readBuffer(); + if ( + !response.item || + previous.items.some((item) => item.id === response.item.id) || + buffer.occupied <= previous.occupied + ) + break; + } + return buffer; +} diff --git a/src/pages/AnnotationOperations.tsx b/src/pages/AnnotationOperations.tsx index d32e055b..3d9b490a 100644 --- a/src/pages/AnnotationOperations.tsx +++ b/src/pages/AnnotationOperations.tsx @@ -1,3 +1,4 @@ +import { AnnotationWorkModeToggle } from "../components/AnnotationWorkModeToggle"; import { loadOwnedAnnotationProject } from "../lib/annotation-project-loading.js"; import { FailedSliceRecoveryNotice } from "../components/FailedSliceRecoveryNotice"; import { initialAnnotationPool } from "../lib/annotation-landing.js"; @@ -45,6 +46,7 @@ import { newAnnotationClaimRequestID } from "../lib/annotation-random-claim.js"; import { createAnnotationHistory } from "../lib/annotation-history.js"; import { useProjectDiscardReasons } from "../hooks/useProjectDiscardReasons"; import { useProjectSliceDictionary } from "../hooks/useProjectSliceDictionary"; +import { refillAnnotationWorkBuffer, hasDirectedAnnotationRework } from "../lib/annotation-work-mode.js"; import { useAnnotationWorkSession, type AnnotationWorkSession } from "../hooks/useAnnotationWorkSession"; import { alignSliceTimeline, initializeFrameAlignedSlices, sliceTimelineIssue } from "../lib/annotation-timeline.js"; import { resolveSliceEditConflicts } from "../lib/slice-edit-conflict.js"; @@ -356,6 +358,7 @@ function readyBufferedItems(items: HumanItem[], processing: Record + Number(hasDirectedAnnotationRework([b])) - Number(hasDirectedAnnotationRework([a])) || Number(!(phase(a)?.status === "completed" || phase(a)?.phase === "annotate")) - Number(!(phase(b)?.status === "completed" || phase(b)?.phase === "annotate")) || (a.claimedAt || "").localeCompare(b.claimedAt || ""), @@ -5075,6 +5078,10 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: setPendingTaskId(taskId); return; } + if (taskId && workPage && !workSession.active) { + void resumeOwnedTask(taskId); + return; + } explicitBufferTask.current = taskId; if (!taskId) { closeTaskAndReturnToPool(); @@ -5099,6 +5106,27 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: setTaskPoolView("mine"); }; + async function resumeOwnedTask(taskId: string) { + if (viewportBlocksDispatch() || !canAccessWorkspace || workEntryFlight.current) return; + const origin = claimContextRef.current; + workEntryFlight.current = true; + setWorkEntryBusy(true); + let session: AnnotationWorkSession | null = null; + try { + const acquisition = await workSession.acquire(); + if (acquisition.status !== "acquired") return; + session = acquisition.session; + if (claimContextRef.current !== origin || !claimPermissionRef.current) return; + workSession.setContinuous(session, workSession.prefersContinuous()); + explicitBufferTask.current = taskId; + openWorkTask(taskId, session); + } finally { + if (session && !session.active) workSession.release(session); + workEntryFlight.current = false; + setWorkEntryBusy(false); + } + } + const randomClaimTask = async ( enterWorkPage = false, entryStillCurrent?: () => boolean, @@ -5210,6 +5238,36 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: } }; + const claimTaskManually = async () => { + if (!workPage || workSession.active) return randomClaimTask(); + if (viewportBlocksDispatch() || !canAccessWorkspace || workEntryFlight.current || annotationDirty) return; + const origin = claimContextRef.current; + workEntryFlight.current = true; + setWorkEntryBusy(true); + let session: AnnotationWorkSession | null = null; + try { + const acquisition = await workSession.acquire(); + if (acquisition.status !== "acquired") return; + session = acquisition.session; + if (claimContextRef.current !== origin || !claimPermissionRef.current) return; + workSession.setContinuous(session, workSession.prefersContinuous()); + const epoch = workSession.continuousEpoch(); + await randomClaimTask( + true, + () => + claimContextRef.current === origin && + workSession.owns(session) && + workSession.continuousEpoch() === epoch && + claimPermissionRef.current, + session, + ); + } finally { + if (session && !session.active) workSession.release(session); + workEntryFlight.current = false; + setWorkEntryBusy(false); + } + }; + // Reconcile one account/project buffer without navigating or touching editor // drafts. Requests already in flight are recorded even after an immediate pause. const reconcileWorkBuffer = async (stillCurrent: () => boolean, refill = false) => { @@ -5220,47 +5278,41 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: claimContextRef.current.userId === actorID && claimContextRef.current.projectId === originProject; bufferFlight.current = true; try { - let buffer = await annotationOperationsApi.workBuffer(originProject); const key = `droboticflow.random-claim:${actorID}:${originProject}`; - while ( - refill && - buffer.enabled && - (!detailRef.current || Boolean(detailRef.current.task.continuousActions)) && - stillCurrent() && - sameScope() && - workSession.hasContinuousIntent() && - !viewportBlocksDispatch() && - buffer.occupied < buffer.capacity - ) { - const requestId = pendingClaimRequest(key) || newAnnotationClaimRequestID(); - localStorage.setItem(key, requestId); - randomClaimKeys.current[key] = requestId; - let response: Awaited>; - try { - response = await annotationOperationsApi.randomClaim(originProject, requestId, true); - } catch (cause) { - if ((cause as { code?: string }).code !== "annotation_buffer_full") throw cause; - // Another browser or a capacity change used the last slot. The server - // definitively rejected this new allocation; it is not an unknown job. - forgetClaimRequest(key, requestId); - buffer = await annotationOperationsApi.workBuffer(originProject); - break; - } - forgetClaimRequest(key, requestId); - if (!sameScope()) return null; - if (response.item && response.task) { - const item = response.item, - task = response.task; + const buffer = await refillAnnotationWorkBuffer({ + refill, + readBuffer: () => annotationOperationsApi.workBuffer(originProject), + shouldContinue: () => + (!detailRef.current || Boolean(detailRef.current.task.continuousActions)) && + stillCurrent() && + sameScope() && + workSession.hasContinuousIntent() && + !viewportBlocksDispatch(), + claim: async () => { + const requestId = pendingClaimRequest(key) || newAnnotationClaimRequestID(); + localStorage.setItem(key, requestId); + randomClaimKeys.current[key] = requestId; + try { + const response = await annotationOperationsApi.randomClaim(originProject, requestId, true); + forgetClaimRequest(key, requestId); + return response; + } catch (cause) { + if ((cause as { code?: string }).code !== "annotation_buffer_full") throw cause; + forgetClaimRequest(key, requestId); + return { item: null }; + } + }, + onClaim: ({ item, task }) => { + // Keep confirmed ownership even if the user switched to manual while + // the request was in flight; never allocate another item in that case. + if (!sameScope()) return; setHumanPools((pools) => ({ ...pools, mine: [item, ...pools.mine.filter((old) => old.id !== item.id)] })); setTasks((tasks) => [task, ...tasks.filter((old) => old.id !== task.id)]); - } - buffer = await annotationOperationsApi.workBuffer(originProject); - if (!response.item) break; - } + }, + }); if (!sameScope()) return null; setWorkBuffer(buffer); setHumanPools((pools) => ({ - ...pools, ...pools, mine: [...buffer.items, ...pools.mine.filter((old) => !buffer.items.some((item) => item.id === old.id))], })); @@ -5325,11 +5377,11 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: session = acquisition.session; continuousEpoch = workSession.continuousEpoch(); if (!entryStillCurrent()) return; - workSession.setContinuous(session, true); + workSession.setContinuous(session, workSession.prefersContinuous()); continuousEpoch = workSession.continuousEpoch(); const key = `droboticflow.random-claim:${actorID}:${selectedProject}`; const unresolvedClaim = pendingClaimRequest(key); - if (unresolvedClaim) { + if (unresolvedClaim && workSession.prefersContinuous()) { // Resolve the previous logical claim before considering another task. await randomClaimTask(true, entryStillCurrent, session); return; @@ -5337,14 +5389,12 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: // Read ownership at the explicit entry action. A stale pool list must not // cause another allocation, or reopen a task already handed to review. const buffer = - (await reconcileWorkBuffer(() => entryStillCurrent() && !viewportBlocksDispatch(), true)) || - (await annotationOperationsApi.workBuffer(projectId)); + (await reconcileWorkBuffer( + () => entryStillCurrent() && !viewportBlocksDispatch(), + workSession.prefersContinuous(), + )) || (await annotationOperationsApi.workBuffer(projectId)); if (!buffer || !entryStillCurrent() || deferEntryForViewport()) return; const buffered = buffer.enabled && (!detailRef.current || Boolean(detailRef.current.task.continuousActions)); - if (!buffered && resumeOnly) { - workSession.setContinuous(session, false); - continuousEpoch = workSession.continuousEpoch(); - } const mine = buffered ? buffer.items : await humanLoopApi.listItems({ pluginId: "annotation-qa", projectId: selectedProject, pool: "mine" }); @@ -5367,7 +5417,8 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: openWorkTask(task.id, session); } else if (!buffered) { if (resumeOnly) setRandomClaimNotice("没有可继续的已领取任务;可返回任务池开始工作。"); - else await randomClaimTask(true, entryStillCurrent, session); + else if (workSession.prefersContinuous()) await randomClaimTask(true, entryStillCurrent, session); + else setRandomClaimNotice("手动模式:点击随机领取任务后才接取新任务。"); } else { workSession.activate(session); setRandomClaimNotice( @@ -5416,18 +5467,46 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: const resumeContinuousWork = async () => { if (viewportBlocksDispatch()) return; - if (!workSession.active || !workSession.owns() || !blindAnnotator || !canAccessWorkspace) return; + if (!blindAnnotator || !canAccessWorkspace) return; // Enabling while editing must preserve the current drafts and history. - if (selectedClaimedByMe && detail && !combinedSubmissionFinished(detail)) { + if ( + workSession.active && + workSession.owns() && + selectedClaimedByMe && + detail && + !combinedSubmissionFinished(detail) + ) { const origin = claimContextRef.current; const acquisition = await workSession.acquire(); if (acquisition.status === "acquired" && claimContextRef.current === origin && claimPermissionRef.current) - workSession.setContinuous(acquisition.session, true); + workSession.setContinuous(acquisition.session, workSession.prefersContinuous()); } else { await startWork(); } }; + const toggleContinuousWork = async () => { + const enabled = !workSession.prefersContinuous(); + try { + workSession.setContinuousEnabled(enabled); + if (!enabled) { + setNextAfterHandoff(null); + setRandomClaimNotice("手动模式:仅点击随机领取时接取新任务,已领取任务和当前编辑保留。"); + } else { + await resumeContinuousWork(); + } + } catch (cause) { + setRandomClaimNotice( + getActionErrorMessage( + cause, + enabled + ? "无法保存工作模式,未开启自动接取。" + : "本次已停止自动接取,但未能保存选择;重新打开前请检查浏览器存储权限。", + ), + ); + } + }; + useEffect(() => { if (!blindAnnotator || !projectId || !canAccessWorkspace) return; let disposed = false; @@ -5755,22 +5834,61 @@ export default function AnnotationOperations({ workPage = false }: { workPage?: ) : null}
- {blindAnnotator && projectId && workBuffer.enabled && (!detail || detail.task.continuousActions) ? ( -