From 3438c8ff2f88eafbd8ef4ba9a025bc5b4ac24b5f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 21 Jul 2026 03:51:27 +0000 Subject: [PATCH] Revamp 5.2: Role-gated editing workflow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add role-gated editing per workflow stage (ROADMAP §5.2, D8). - core/workflow/rules.ts: pure workflowCapabilities(role, stage, status) -> {canEditDirect, mustSuggest, canResolveChanges, canReview, canManage}; effectiveRoleStage (local-only = PM-of-self, zero regression) + forcesSuggesting. - 0009_workflow.sql: project_stage enum + projects.stage/deadline; PM-only writes via the existing projects_update policy (no new policy). - Project.cloud gains stage/deadline (read on open); projectCloud setCloudProjectStage + changeProjectStage orchestration. - Gating: useWorkflowStore published by EditorPage; EditModeToggle forced+disabled for a translator in review; ChangesPanel + ChangeHoverCard hide accept/reject unless revisor/PM; PM stage selector in ManageMembersDialog. - Tests: workflow.rules (full role matrix, final lock, local-only PM-of-self); projectCloud stage read + update. Numbering deviation: ships as 0009 (0007/0008 taken). Green: 671 unit (+10) / tracked-changes e2e / typecheck / build (flag-off Supabase-free). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_015AEnTYBecWG64R3iP8GBiE --- docs/cloud.md | 26 +++++ docs/revamp/ROADMAP.md | 2 +- docs/revamp/STATUS.md | 5 +- src/core/types/index.ts | 10 +- src/core/workflow/rules.ts | 102 ++++++++++++++++++ src/features/editor/EditModeToggle.tsx | 11 +- src/features/editor/EditorPage.tsx | 22 +++- src/features/editor/changes/ChangesPanel.tsx | 91 +++++++++------- src/features/editor/rich/ChangeHoverCard.tsx | 6 +- .../editor/workflow/useWorkflowStore.ts | 38 +++++++ .../projects/cloud/ManageMembersDialog.tsx | 57 +++++++++- src/storage/cloud/projectCloud.ts | 47 +++++++- supabase/migrations/0009_workflow.sql | 22 ++++ tests/unit/cloud.projectCloud.test.ts | 32 ++++++ tests/unit/workflow.rules.test.ts | 89 +++++++++++++++ 15 files changed, 506 insertions(+), 54 deletions(-) create mode 100644 src/core/workflow/rules.ts create mode 100644 src/features/editor/workflow/useWorkflowStore.ts create mode 100644 supabase/migrations/0009_workflow.sql create mode 100644 tests/unit/workflow.rules.test.ts diff --git a/docs/cloud.md b/docs/cloud.md index 5e4e400..2a66b0b 100644 --- a/docs/cloud.md +++ b/docs/cloud.md @@ -125,6 +125,12 @@ and safe to re-run: §5.1 sketched `0006_member_policies.sql`, but `0006`/`0007` were taken, so it ships as `0008`; invite resolves the email inside the RPC rather than via a client-side profiles lookup, keeping emails/ids server-side.)* +- `0009_workflow.sql` — adds a `project_stage` enum + `projects.stage` + (default `translation`) and `projects.deadline`, gating role-based editing (§5.2). + Writes are project_manager-only through the existing `projects_update` policy — + no new policy. Backs Phase 5.2. Apply after `0008`. *(Numbering note: ROADMAP + §5.2 sketched `0007_workflow.sql`, but `0007`/`0008` were taken, so it ships as + `0009`.)* > Note: the linter's "Leaked Password Protection Disabled" warning is unrelated > to these migrations — it's an optional **Authentication → Policies** toggle @@ -293,3 +299,23 @@ a second signed-in account: project_manager" (surfaced as an error in the dialog). - [ ] **Local-only unaffected**: a project with no `cloud` link shows no Members button; a signed-out / unconfigured build never loads the members chunk. + +## 12. Manual verification (Phase 5.2 — Role-gated editing workflow) + +Role gates editing per workflow stage (`core/workflow/rules.ts`), the stage being +`projects.stage` set by a PM in the Members dialog. Apply `0009_workflow.sql` +first. With a project_manager, a translator, and a revisor on one cloud project: + +- [ ] **PM sets the stage**: in Members, the manager moves the project through + Translation → Review → Final; a non-PM sees the stage read-only. +- [ ] **Translator forced to suggest in review**: with the stage on *Review*, the + translator's edit-mode toggle is locked to **Suggesting** (disabled) and + typing produces tracked suggestions, not direct edits. +- [ ] **Accept/reject is reviewer-only**: the translator sees suggestions but **no** + Accept/Reject (panel buttons hidden, hover card suppressed); the revisor and + the PM see and can resolve them. +- [ ] **Final locks editing**: in *Final*, translator + revisor can't edit; only the + PM can (e.g. to reopen by moving the stage back). +- [ ] **Local-only unchanged**: a project with no cloud link behaves as + "PM-of-self" — direct editing, suggesting, and accept/reject all available, + exactly as before roles existed. diff --git a/docs/revamp/ROADMAP.md b/docs/revamp/ROADMAP.md index 3898505..a058021 100644 --- a/docs/revamp/ROADMAP.md +++ b/docs/revamp/ROADMAP.md @@ -83,7 +83,7 @@ Roadmap, status checklist, prompt pack, and vision docs committed to the repo. ### Milestone 5 — Roles & workflow - **5.1 Members & roles management — M — deps: 4.1.** `cloud/members.ts` (invite by email via profiles lookup, change role, remove), `MembersPanel`, `0006_member_policies.sql` (PM-only member writes; trigger keeps ≥1 PM). **DoD**: PM invites translator + revisor; non-PM read-only; server rejects non-PM writes. *Shipped as `0008_member_policies.sql` (0006/0007 taken) + `cloud/members.ts` + a `ManageMembersDialog` on the project card (lazy-loaded) instead of a sidebar `MembersPanel`; invite resolves the email inside the SECURITY DEFINER `invite_member` RPC (PM-checked, no enumeration surface) rather than a client-side profiles lookup; `profiles.email` + a co-member SELECT policy added; a `enforce_min_one_pm` trigger guards the last manager.* -- **5.2 Role-gated editing workflow — M — deps: 5.1, 1.6.** Pure `core/workflow/rules.ts`: `(role, stage, status) → {canEditDirect, mustSuggest, canResolveChanges, canReview, canManage}`; `projects.stage (translation|review|final)` + `deadline` (`0007_workflow.sql`, PM-only update). Translator in review stage is forced into suggesting (toggle disabled); accept/reject visible only to revisor/PM; local-only projects = PM-of-self (all permissive, zero regression). **DoD**: full role matrix works; local-only unchanged. +- **5.2 Role-gated editing workflow — M — deps: 5.1, 1.6.** Pure `core/workflow/rules.ts`: `(role, stage, status) → {canEditDirect, mustSuggest, canResolveChanges, canReview, canManage}`; `projects.stage (translation|review|final)` + `deadline` (`0007_workflow.sql`, PM-only update). Translator in review stage is forced into suggesting (toggle disabled); accept/reject visible only to revisor/PM; local-only projects = PM-of-self (all permissive, zero regression). **DoD**: full role matrix works; local-only unchanged. *Shipped: pure `core/workflow/rules.ts` + `useWorkflowStore` gating (forced-suggest toggle, reviewer-only accept/reject in `ChangesPanel`/`ChangeHoverCard`), `0009_workflow.sql` (`project_stage` + `deadline`, PM-only via existing `projects_update`), `Project.cloud.stage` read on open + `changeProjectStage`, and a PM stage selector in `ManageMembersDialog`.* - **5.3 Approval + attribution in versioning — S — deps: 5.2.** `ProjectVersion.authorId?/approval?`; revisor/PM "Sign off" creates a labeled approval version; one stable author identity across marks, comments, versions, presence. **DoD**: sign-off flow; attribution unified. *Milestone 5 = roles shipped → **web v2 launch candidate**.* ### Milestone 6 — Extensions & connectors diff --git a/docs/revamp/STATUS.md b/docs/revamp/STATUS.md index 3c476ff..49f8464 100644 --- a/docs/revamp/STATUS.md +++ b/docs/revamp/STATUS.md @@ -33,8 +33,8 @@ Rules for autonomous sessions: | 4.3 | Postgres persistence loop (catch-up, append, compaction) | M | 4.2 | done (PR #57) | | 4.4 | Live collab UX: cursors, leases, attribution | M | 4.3, 1.6 | done (PR #58) | | 4.4.1 | Remote caret overlay (live cursors, deferred from 4.4) | S | 4.4 | done (PR #59) | -| 5.1 | Members & roles management | M | 4.1 | in-review (PR #60) | -| 5.2 | Role-gated editing workflow | M | 5.1, 1.6 | pending | +| 5.1 | Members & roles management | M | 4.1 | done (PR #60) | +| 5.2 | Role-gated editing workflow | M | 5.1, 1.6 | in-review (PR #61) | | 5.3 | Approval workflow + attribution in versioning | S | 5.2 | pending | | 6.1 | Extension registry + MT providers as built-in addons | M | 0.1 | pending | | 6.2 | QA rules + formats as addons + Add-ons page | M | 6.1 | pending | @@ -76,3 +76,4 @@ Rules for autonomous sessions: - 2026-07-20 — Phase 4.3 merged in PR #57. Phase 4.4 built: live-collab UX — per-segment edit leases, attribution, and the stale-LWW guard (transport-agnostic, so it works for local BroadcastChannel peers and cloud Realtime peers identically). `src/storage/sync/presence.ts` gains a stable `userId` (Supabase user id when signed in, else the device-local `authorId` — so attribution survives a peer reconnecting under a fresh peerId, D8) and a `CaretRange` on both `PresenceWire` and `PeerPresence`; `syncSession` broadcasts them (`setActiveSegment(id, caret?)`) and `syncManager` resolves `userId` via `ensureLocalAuthor()`/auth. `src/storage/sync/lease.ts` — pure `segmentLease(segmentId, selfPeerId, selfActiveSegmentId, peers)`: among everyone editing a segment the **lowest peerId owns** (D4), the rest are viewers; symmetric + deterministic so two peers entering at once always agree, and the lease **releases the moment the owner blurs** (its `activeSegmentId` moves off) and the next-lowest peer takes over. Wiring: `usePresenceStore` carries `selfPeerId`; `useProjectSync` publishes it; `EditorPage` computes `leaseHolderFor(segmentId)` and passes `leaseLockedBy` to each `SegmentRow`, which renders the target read-only (a separate `editLocked = locked || leaseLockedBy`, kept distinct from the persistent segment lock) with a coloured "{name} is editing" chip. Attribution "everyone's changes tracked" falls out of M1 + sync for free — remote suggesting-mode edits already arrive as pre-attributed `ChangeMarkNode`s. `reverseBridge.ts` stale-LWW guard (risk #5): `target` (char-level Y.Text) and `targetRich` are separate CRDT fields, so a concurrent merge can land a `targetRich` that no longer derives to the merged plain `target`; plain is authoritative, so when `richStateToPlain(targetRich) !== target` the guard drops the stale rich and the editor rebuilds it from plain. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-4`; **the live remote-caret overlay is deferred to Phase 4.4.1** (appended to the table + ROADMAP §4) — the presence model already carries `caret` as the seam, but rendering it needs editor→session caret reporting + offset→DOM measurement (a finicky, separable slice), so 4.4 ships the load-bearing lease/attribution/guard core (the "one editor + one viewer; lease releases on blur" DoD) and the per-segment "is editing" chip as the visible presence cue. Tests: `sync.lease` (alone→own; higher-peerId co-editor→own; lower-peerId→viewer names holder; not-on-segment reports the editor; symmetric one-owner; release; `peersOnSegment`), `sync.presence` (userId + caret round-trip), `sync.reverseBridge` (guard drops a stale targetRich once the merged plain diverges, no-op while they agree), and e2e `lan-collaboration.spec.ts` extended (**simultaneous entry → exactly one read-only viewer + one editable owner; owner blur releases the lease** via two BroadcastChannel tabs). Green: 645 unit (+9) / 28 e2e (+1) / build (flag-off has zero `GoTrueClient`; leases are local-capable so they ship in the entry as intended). - 2026-07-20 — Phase 4.4 merged in PR #58. Phase 4.4.1 built: the live remote-caret overlay deferred from 4.4 (**Milestone 4 fully complete**). `src/core/spell/offsets.ts` gains pure `mapOffsetToNode(spans, offset)` — the caret counterpart to `mapTokenToNode`, resolving a plain-text offset to a text node + local offset (a text/text boundary snaps to the earlier node's end; a tag boundary or past-the-end returns null → the overlay skips that frame). `src/features/editor/rich/richOffsets.ts` — `selectionToCaretRange(selection)` converts a live Lexical selection to plain anchor/focus offsets and `buildLeafSpans(paragraph)` produces the ordered leaf spans, both reproducing exactly the plain projection `richStateToPlain` derives (a tag contributes `{id}`, a **delete change-mark projects to '' and its subtree is skipped**) so a caret one peer reports lands on the same character in another peer's editor. `RemoteCaretOverlay.tsx` (a Lexical plugin mounted in `RichSegmentEditor` beside the spell overlay) paints a coloured caret + name label for each remote peer whose presence puts them on the segment with a caret, measured via `getElementByKey`+DOM range like `SpellUnderlinePlugin` — it never mutates the node tree and every measurement is guarded (renders nothing on failure). Reporting: the **focused** segment's editor (the only one given `onCaret`) computes `selectionToCaretRange` in its update listener and reports it through `EditorPage`→`useProjectSync`→`setActiveSegment(id, caret)`, throttled to one send per 100ms; `useProjectSync.setActiveSegment` now forwards the caret. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-4-1`. Tests: `spell.offsets` extended (`mapOffsetToNode`: inside/boundary/after-tag/end/out-of-range), `richOffsets` (headless: caret offsets + leaf spans agree with the plain projection for text+tag, and a **delete change-mark projects to nothing** so a caret past it collapses correctly), and e2e `lan-collaboration.spec.ts` extended (**a peer's caret renders as a live remote cursor in the other tab**). Green: 653 unit (+8) / 29 e2e (+1) / build (flag-off zero `GoTrueClient`; the overlay is local-capable and ships in the entry, no Supabase). **Milestone 4 (cloud projects + real-time collaboration) complete.** - 2026-07-20 — Phase 4.4.1 merged in PR #59. Phase 5.1 built: members & roles management (start of **Milestone 5**, roles & workflow). `supabase/migrations/0008_member_policies.sql` — adds `profiles.email` (backfilled from `auth.users` + seeded on signup) and a co-member `profiles` SELECT policy via a new `private.shares_project(other)` SECURITY DEFINER helper (the "broader read for member lookup" 0001 deferred to 5.1); switches `project_members` **update/delete to project_manager-only** (`private.has_project_role`), keeping `insert` reachable by the owner's publish self-seed OR a PM; a `enforce_min_one_pm` BEFORE UPDATE/DELETE trigger that blocks removing/demoting a project's **last** manager; and the `invite_member(project_id, email, role)` RPC (SECURITY DEFINER, PM-checked) that resolves the email → user id and upserts membership, returning NULL when no account matches (no id/email enumeration surface). Numbering deviation: ROADMAP §5.1 sketched `0006_member_policies.sql`, but `0006`/`0007` were taken (4.1 helpers + 4.3 compaction), so it ships as `0008`; and invite resolves the email **inside** the RPC rather than a client-side profiles lookup, keeping it server-side. `src/storage/cloud/members.ts` — pure client-injected `listMembers` (joins the roster to profiles for names/emails, marks self, sorts managers first), `inviteMember` (RPC → `{status:'invited'|'not_found'}`), `changeMemberRole`/`removeMember` (direct writes gated by PM-only RLS + the trigger, surfaced as thrown errors). UI: `features/projects/cloud/ManageMembersDialog.tsx` (roster; a PM gets an invite-by-email form + per-member role `` (+ read-only badge for non-PMs) lives in `ManageMembersDialog`. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-5-2`; content-level rules are client-enforced per D8 (the append-only authored log is the audit trail), stated honestly. `docs/cloud.md` (§3 migration list + §12 manual role-matrix). Tests: `workflow.rules` (full role × stage × status matrix incl. reviewed-segment suggest, final lock, local-only PM-of-self, `forcesSuggesting`), `cloud.projectCloud` extended (stage read defaults to translation + `setCloudProjectStage` update). Verified: flag-OFF `dist` has **zero** `GoTrueClient`; the tracked-changes e2e still green (local-only = PM keeps accept/reject). Green: 671 unit (+10) / 8 tracked-changes e2e / build. No new e2e (ROADMAP §5.2 asks none; the full role matrix needs three real accounts, per the §12 manual matrix). diff --git a/src/core/types/index.ts b/src/core/types/index.ts index 3f94bf7..08cc352 100644 --- a/src/core/types/index.ts +++ b/src/core/types/index.ts @@ -7,6 +7,9 @@ export interface BilingualProjectMeta { /** Role a member holds on a cloud project (ROADMAP §4.1, D8). */ export type ProjectRole = 'project_manager' | 'translator' | 'revisor' +/** Project-level workflow stage that gates editing per role (ROADMAP §5.2). */ +export type WorkflowStage = 'translation' | 'review' | 'final' + export interface Project { id: string name: string @@ -18,10 +21,11 @@ export interface Project { /** * Cloud publication link (ROADMAP §4.1). Present once the project is published * to — or opened from — Supabase; absent for local-only projects. `id` is the - * cloud `projects` row id; `role` is this user's role in it. Additive and - * unindexed: local-only projects never carry it. + * cloud `projects` row id; `role` is this user's role in it. `stage`/`deadline` + * carry the §5.2 workflow snapshot read on open. Additive and unindexed: + * local-only projects never carry it (they are "PM-of-self", fully permissive). */ - cloud?: { id: string; role: ProjectRole } + cloud?: { id: string; role: ProjectRole; stage?: WorkflowStage; deadline?: string | null } } /** diff --git a/src/core/workflow/rules.ts b/src/core/workflow/rules.ts new file mode 100644 index 0000000..90ebbcb --- /dev/null +++ b/src/core/workflow/rules.ts @@ -0,0 +1,102 @@ +import type { ProjectRole, SegmentStatus, WorkflowStage } from '@/core/types' + +export type { WorkflowStage } + +/** + * Pure role-gated editing workflow (ROADMAP §5.2, D8). + * + * Maps `(role, stage, status)` to what a member may do, so both the UI and the + * (client-enforced, per D8) content rules read from one source of truth. The + * server enforces membership + write access (RLS) and the append-only authored + * update log is the audit trail; these capabilities are the *content-level* + * rules layered on top — the honest split documented in D8. + * + * Local-only projects have no cloud role, so callers resolve them as + * "PM-of-self" via {@link effectiveRoleStage} → every capability is granted and + * behaviour is byte-identical to the pre-roles app. + */ + +export interface WorkflowCapabilities { + /** May change the target text directly (vs. only via tracked suggestions). */ + canEditDirect: boolean + /** May contribute text, but only as tracked suggestions (forces suggesting mode). */ + mustSuggest: boolean + /** May accept/reject tracked changes. */ + canResolveChanges: boolean + /** May perform review actions (mark reviewed / sign off). */ + canReview: boolean + /** May manage the project (members, stage, deadline). */ + canManage: boolean +} + +/** + * The capabilities a member with `role` has for a segment with `status` while the + * project is in `stage`. + * + * - **project_manager** — manages everything; edits directly in translation/review, + * and remains the only role that can touch a signed-off (`final`) project. + * - **translator** — edits directly during `translation` (except on an already + * `reviewed` segment, which must be suggested), and is **forced into suggesting** + * during `review`. + * - **revisor** — waits during `translation` (read-only), then edits directly and + * accepts/rejects during `review`. + * - **final** — locked to everyone but a manager. + */ +export function workflowCapabilities( + role: ProjectRole, + stage: WorkflowStage, + status: SegmentStatus, +): WorkflowCapabilities { + const isManager = role === 'project_manager' + const isRevisor = role === 'revisor' + const isTranslator = role === 'translator' + + const canManage = isManager + const canReview = isManager || isRevisor + const canResolveChanges = isManager || isRevisor + + let canEditDirect = false + let mustSuggest = false + + if (stage === 'final') { + // Signed off: only a manager may still edit (to reopen / correct). + canEditDirect = isManager + } else if (isManager) { + canEditDirect = true + } else if (stage === 'translation') { + if (isTranslator) { + // A reviewed (signed-off) segment is suggested, not overwritten. + canEditDirect = status !== 'reviewed' + mustSuggest = !canEditDirect + } + // revisor: waits for the review stage (read-only, no direct edit / suggest). + } else { + // review stage + if (isRevisor) canEditDirect = true + else if (isTranslator) mustSuggest = true // forced suggesting (the §5.2 rule) + } + + return { canEditDirect, mustSuggest, canResolveChanges, canReview, canManage } +} + +/** + * Resolve the effective `(role, stage)` for a project. A local-only project (no + * cloud link) is "PM-of-self": project_manager in the translation stage, so every + * capability is granted and there is zero behaviour change without an account. + */ +export function effectiveRoleStage(cloud?: { + role: ProjectRole + stage?: WorkflowStage +}): { role: ProjectRole; stage: WorkflowStage } { + if (!cloud) return { role: 'project_manager', stage: 'translation' } + return { role: cloud.role, stage: cloud.stage ?? 'translation' } +} + +/** + * Whether `role`/`stage` forces suggesting mode across the project (used to pin + + * disable the edit-mode toggle). True for a translator during review — they can + * contribute, but only as tracked suggestions, regardless of a segment's status. + */ +export function forcesSuggesting(role: ProjectRole, stage: WorkflowStage): boolean { + return role === 'translator' && stage === 'review' +} diff --git a/src/features/editor/EditModeToggle.tsx b/src/features/editor/EditModeToggle.tsx index a9c2009..81e675a 100644 --- a/src/features/editor/EditModeToggle.tsx +++ b/src/features/editor/EditModeToggle.tsx @@ -22,7 +22,7 @@ const MODES: Array<{ id: EditMode; label: string; icon: typeof PenLine; hint: st * In suggesting mode, typing and deleting in the rich editor become tracked * changes attributed to the local author. */ -export function EditModeToggle() { +export function EditModeToggle({ forced = false }: { forced?: boolean }) { const editMode = useEditorModeStore((s) => s.editMode) const setEditMode = useEditorModeStore((s) => s.setEditMode) @@ -31,8 +31,10 @@ export function EditModeToggle() { role="radiogroup" aria-label="Edit mode" data-testid="edit-mode-toggle" + data-forced={forced ? 'true' : undefined} + title={forced ? 'Your role must suggest changes at this workflow stage' : undefined} className="inline-flex items-center gap-1 self-start rounded-full border p-1" - style={{ borderColor: 'var(--color-border)', background: 'var(--color-surface)' }} + style={{ borderColor: 'var(--color-border)', background: 'var(--color-surface)', opacity: forced ? 0.7 : 1 }} > {MODES.map(({ id, label, icon: Icon, hint }) => { const isActive = editMode === id @@ -42,12 +44,15 @@ export function EditModeToggle() { type="button" role="radio" aria-checked={isActive} - title={hint} + // When the workflow forces suggesting, the toggle is locked to it. + disabled={forced} + title={forced ? 'Your role must suggest changes at this workflow stage' : hint} data-testid={`edit-mode-${id}`} onClick={() => setEditMode(id)} className={cn( 'inline-flex items-center gap-1.5 rounded-full px-3 h-8 text-footnote transition-colors', isActive ? 'font-semibold' : 'hover:bg-[var(--color-fill)]', + forced && 'cursor-not-allowed', )} style={{ background: isActive ? 'var(--color-accent-fill)' : 'transparent', diff --git a/src/features/editor/EditorPage.tsx b/src/features/editor/EditorPage.tsx index eafedc7..36a9661 100644 --- a/src/features/editor/EditorPage.tsx +++ b/src/features/editor/EditorPage.tsx @@ -13,6 +13,8 @@ import { MobileSidebarSheet } from './MobileSidebarSheet' import { StatusFilterBar } from './StatusFilterBar' import { StageSwitcher } from './StageSwitcher' import { EditModeToggle } from './EditModeToggle' +import { useWorkflowStore, useForcesSuggesting } from './workflow/useWorkflowStore' +import { effectiveRoleStage } from '@/core/workflow/rules' import { useSidebarPanelStore } from './useSidebarPanelStore' import { useEditorModeStore } from './useEditorModeStore' import { useEditorActionsStore } from './useEditorActionsStore' @@ -92,6 +94,10 @@ export default function EditorPage() { const reviewMode = useEditorModeStore((s) => s.reviewMode) const stage = useEditorModeStore((s) => s.stage) const statusFilter = useEditorModeStore((s) => s.statusFilter) + const setEditMode = useEditorModeStore((s) => s.setEditMode) + const setWorkflow = useWorkflowStore((s) => s.set) + const resetWorkflow = useWorkflowStore((s) => s.reset) + const forceSuggest = useForcesSuggesting() const showMarks = useChangesStore((s) => s.showMarks) const previewOpen = usePreviewStore((s) => s.open) const togglePreview = usePreviewStore((s) => s.toggle) @@ -112,6 +118,20 @@ export default function EditorPage() { editorHandles.current[focusIndex]?.focus() }, [focusIndex]) + // Publish this project's effective role + workflow stage (§5.2) so the toggle + // and changes UI gate editing. Local-only projects resolve to PM-of-self, so + // nothing is restricted. Runs above the early returns to keep hook order stable. + useEffect(() => { + const { role, stage: wfStage } = effectiveRoleStage(project?.cloud) + setWorkflow(role, wfStage) + return () => resetWorkflow() + }, [project?.cloud?.role, project?.cloud?.stage, setWorkflow, resetWorkflow]) + + // A translator in the review stage may only suggest — pin the edit mode. + useEffect(() => { + if (forceSuggest) setEditMode('suggesting') + }, [forceSuggest, setEditMode]) + // Broadcast which segment the local user is on, so peers' presence follows. // This must run unconditionally — above the early returns below — so the hook // order stays stable across the loading → loaded transition (a hook placed @@ -542,7 +562,7 @@ export default function EditorPage() {
- + {hasDocument && ( - -
+ {canResolve && ( +
+ + +
+ )}
{pending.map((c) => ( actions?.jumpToSegment(c.segmentIndex + 1)} /> ))} @@ -144,7 +151,15 @@ function SuggestionsView({ projectId }: ChangesPanelProps) { ) } -function SuggestionRow({ change, onJump }: { change: PendingChange; onJump: () => void }) { +function SuggestionRow({ + change, + canResolve, + onJump, +}: { + change: PendingChange + canResolve: boolean + onJump: () => void +}) { const color = colorForAuthor(change.authorName) const isInsert = change.type === 'insert' const resolve = (action: ResolveAction) => @@ -189,24 +204,26 @@ function SuggestionRow({ change, onJump }: { change: PendingChange; onJump: () = {change.text}

-
- - -
+ {canResolve && ( +
+ + +
+ )} ) } diff --git a/src/features/editor/rich/ChangeHoverCard.tsx b/src/features/editor/rich/ChangeHoverCard.tsx index e3e233a..93d942c 100644 --- a/src/features/editor/rich/ChangeHoverCard.tsx +++ b/src/features/editor/rich/ChangeHoverCard.tsx @@ -1,6 +1,7 @@ import { useEffect, useState, type RefObject } from 'react' import { Check, X } from 'lucide-react' import { resolveSegmentChange } from '../changes/resolveOps' +import { useCanResolveChanges } from '../workflow/useWorkflowStore' import type { ResolveAction } from './resolve' interface CardState { @@ -26,6 +27,9 @@ export function ChangeHoverCard({ containerRef: RefObject }) { const [card, setCard] = useState(null) + // Accept/reject is a review action (§5.2): only offer the hover card to a + // revisor / project_manager. Local-only projects resolve to PM → shown. + const canResolve = useCanResolveChanges() useEffect(() => { const container = containerRef.current @@ -69,7 +73,7 @@ export function ChangeHoverCard({ return () => document.removeEventListener('keydown', onKey) }, [card]) - if (!card) return null + if (!card || !canResolve) return null const resolve = (action: ResolveAction) => { void resolveSegmentChange(segmentId, card.changeId, action) diff --git a/src/features/editor/workflow/useWorkflowStore.ts b/src/features/editor/workflow/useWorkflowStore.ts new file mode 100644 index 0000000..b1ed937 --- /dev/null +++ b/src/features/editor/workflow/useWorkflowStore.ts @@ -0,0 +1,38 @@ +import { create } from 'zustand' +import type { ProjectRole, WorkflowStage } from '@/core/types' +import { forcesSuggesting, workflowCapabilities } from '@/core/workflow/rules' + +/** + * The open project's effective role + workflow stage (ROADMAP §5.2), published by + * `EditorPage` and read by the edit-mode toggle and the changes UI to gate + * editing. The default is the permissive "PM-of-self" (project_manager / + * translation), so before a project resolves — and for every local-only project — + * nothing is restricted and behaviour is byte-identical to the pre-roles app. + */ +interface WorkflowState { + role: ProjectRole + stage: WorkflowStage + set: (role: ProjectRole, stage: WorkflowStage) => void + reset: () => void +} + +const DEFAULT: Pick = { + role: 'project_manager', + stage: 'translation', +} + +export const useWorkflowStore = create((set) => ({ + ...DEFAULT, + set: (role, stage) => set({ role, stage }), + reset: () => set(DEFAULT), +})) + +/** Whether the current role may accept/reject tracked changes (revisor / PM). */ +export function useCanResolveChanges(): boolean { + return useWorkflowStore((s) => workflowCapabilities(s.role, s.stage, 'translated').canResolveChanges) +} + +/** Whether the current role/stage forces suggesting mode (translator in review). */ +export function useForcesSuggesting(): boolean { + return useWorkflowStore((s) => forcesSuggesting(s.role, s.stage)) +} diff --git a/src/features/projects/cloud/ManageMembersDialog.tsx b/src/features/projects/cloud/ManageMembersDialog.tsx index 8e9fdb2..41651c6 100644 --- a/src/features/projects/cloud/ManageMembersDialog.tsx +++ b/src/features/projects/cloud/ManageMembersDialog.tsx @@ -12,7 +12,7 @@ import { Select } from '@/components/ui/select' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import type { SupabaseClient } from '@supabase/supabase-js' -import type { Project, ProjectRole } from '@/core/types' +import type { Project, ProjectRole, WorkflowStage } from '@/core/types' import type { ProjectMember } from '@/storage/cloud/members' import type * as MembersModule from '@/storage/cloud/members' import { useAuthStore } from '@/features/account/useAuthStore' @@ -31,6 +31,12 @@ const ROLE_LABEL: Record = { translator: 'Translator', revisor: 'Revisor', } +const STAGES: WorkflowStage[] = ['translation', 'review', 'final'] +const STAGE_LABEL: Record = { + translation: 'Translation', + review: 'Review', + final: 'Final', +} export function ManageMembersDialog({ project, @@ -51,6 +57,11 @@ export function ManageMembersDialog({ const [busy, setBusy] = useState(false) const [inviteEmail, setInviteEmail] = useState('') const [inviteRole, setInviteRole] = useState('translator') + const [stage, setStage] = useState(project.cloud?.stage ?? 'translation') + + useEffect(() => { + setStage(project.cloud?.stage ?? 'translation') + }, [project.cloud?.stage]) const loadCtx = async (): Promise<{ client: SupabaseClient; m: typeof MembersModule }> => { const [{ getSupabase }, m] = await Promise.all([ @@ -123,6 +134,22 @@ export function ManageMembersDialog({ return 'reload' }) + const changeStage = async (next: WorkflowStage) => { + setBusy(true) + setError(null) + setNotice(null) + try { + const { changeProjectStage } = await import('@/storage/cloud/projectCloud') + await changeProjectStage(project.id, next) + setStage(next) + setNotice(`Workflow stage set to ${STAGE_LABEL[next].toLowerCase()}.`) + } catch (e) { + setError(e instanceof Error ? e.message : 'Could not change the stage.') + } finally { + setBusy(false) + } + } + return ( )} +
+ + Workflow stage + + {isManager ? ( + + ) : ( + + {STAGE_LABEL[stage]} + + )} +
+ {members === null ? (
Loading… diff --git a/src/storage/cloud/projectCloud.ts b/src/storage/cloud/projectCloud.ts index 9ed7501..3d08ef0 100644 --- a/src/storage/cloud/projectCloud.ts +++ b/src/storage/cloud/projectCloud.ts @@ -1,7 +1,7 @@ import type { SupabaseClient } from '@supabase/supabase-js' import * as Y from 'yjs' import { db } from '@/storage/db' -import type { Project, ProjectRole, Segment } from '@/core/types' +import type { Project, ProjectRole, Segment, WorkflowStage } from '@/core/types' import { projectRepo } from '@/storage/repositories/projectRepo' import { acquireProjectDoc, releaseProjectDoc } from '@/storage/sync/docManager' import { readAllSegments } from '@/storage/sync/segmentCrdt' @@ -35,6 +35,8 @@ interface ProjectRowSelect { source_lang: string target_lang: string owner_id: string + stage?: WorkflowStage + deadline?: string | null } function toSummary(r: ProjectRowSelect): CloudProjectSummary { @@ -107,11 +109,16 @@ export async function fetchCloudProject( client: SupabaseClient, cloudId: string, userId: string, -): Promise<{ summary: CloudProjectSummary; role: ProjectRole } | null> { +): Promise<{ + summary: CloudProjectSummary + role: ProjectRole + stage: WorkflowStage + deadline: string | null +} | null> { const [projectRes, memberRes] = await Promise.all([ client .from('projects') - .select('id,name,source_lang,target_lang,owner_id') + .select('id,name,source_lang,target_lang,owner_id,stage,deadline') .eq('id', cloudId) .maybeSingle(), client @@ -126,7 +133,17 @@ export async function fetchCloudProject( const row = projectRes.data as ProjectRowSelect | null if (!row) return null const role = (memberRes.data as { role: ProjectRole } | null)?.role ?? 'translator' - return { summary: toSummary(row), role } + return { summary: toSummary(row), role, stage: row.stage ?? 'translation', deadline: row.deadline ?? null } +} + +/** Set a cloud project's workflow stage (project_manager-only, enforced by RLS). */ +export async function setCloudProjectStage( + client: SupabaseClient, + cloudId: string, + stage: WorkflowStage, +): Promise { + const { error } = await client.from('projects').update({ stage }).eq('id', cloudId) + if (error) throw new Error(error.message) } /** The compacted Yjs snapshot for a cloud project, or null when unseeded. */ @@ -216,7 +233,7 @@ export async function openCloudProject(cloudId: string): Promise targetLang: meta.summary.targetLang, createdAt: now, updatedAt: now, - cloud: { id: cloudId, role: meta.role }, + cloud: { id: cloudId, role: meta.role, stage: meta.stage, deadline: meta.deadline }, } let segments: Segment[] = [] @@ -233,3 +250,23 @@ export async function openCloudProject(cloudId: string): Promise }) return localId } + +/** + * Advance a cloud project's workflow stage (project_manager-only, §5.2). Writes + * Postgres — RLS rejects a non-PM — then patches the local `project.cloud.stage` + * so the editor's role gating updates immediately. No-op / null when the cloud is + * off or the project isn't cloud-linked. + */ +export async function changeProjectStage( + projectId: string, + stage: WorkflowStage, +): Promise { + if (!isCloudConfigured()) return null + const project = await projectRepo.getById(projectId) + if (!project?.cloud) return null + + const client = await getSupabase() + await setCloudProjectStage(client, project.cloud.id, stage) + await projectRepo.update(projectId, { cloud: { ...project.cloud, stage } }) + return stage +} diff --git a/supabase/migrations/0009_workflow.sql b/supabase/migrations/0009_workflow.sql new file mode 100644 index 0000000..cfb5a5c --- /dev/null +++ b/supabase/migrations/0009_workflow.sql @@ -0,0 +1,22 @@ +-- Verbalis cloud — 0009 project workflow stage + deadline (ROADMAP §5.2, D8) +-- +-- Roles gate *content* editing per stage (client-enforced, D8); the stage itself +-- is a queryable project column so every member reads the same value and only a +-- project_manager can advance it. The existing `projects_update` policy (0005/ +-- 0006) is already project_manager-only, so it covers stage/deadline writes with +-- no new policy. Idempotent; apply after 0008. + +do $$ +begin + if not exists (select 1 from pg_type where typname = 'project_stage') then + create type public.project_stage as enum ('translation', 'review', 'final'); + end if; +end +$$; + +alter table public.projects + add column if not exists stage public.project_stage not null default 'translation', + add column if not exists deadline timestamptz; + +comment on column public.projects.stage is + 'Workflow stage gating role-based editing (ROADMAP §5.2). project_manager-only writes via projects_update.'; diff --git a/tests/unit/cloud.projectCloud.test.ts b/tests/unit/cloud.projectCloud.test.ts index e24e878..dff3942 100644 --- a/tests/unit/cloud.projectCloud.test.ts +++ b/tests/unit/cloud.projectCloud.test.ts @@ -6,6 +6,7 @@ import { listCloudProjects, fetchCloudProject, fetchYdocState, + setCloudProjectStage, } from '@/storage/cloud/projectCloud' import { decodeBytea } from '@/storage/cloud/bytea' @@ -72,6 +73,20 @@ function makeClient() { select() { return selectBuilder(rows) }, + update(patch: Record) { + const filters: [string, unknown][] = [] + const builder = { + eq(col: string, val: unknown) { + filters.push([col, val]) + return builder + }, + then(onFulfilled: (v: { error: null }) => unknown, onRejected?: () => unknown) { + for (const r of applyFilters(rows, filters)) Object.assign(r, patch) + return Promise.resolve({ error: null }).then(onFulfilled, onRejected) + }, + } + return builder + }, } }, } @@ -177,6 +192,23 @@ describe('listCloudProjects / fetchCloudProject / fetchYdocState', () => { expect(await fetchYdocState(client, 'missing')).toBeNull() }) + it('reads the workflow stage (defaulting to translation) and updates it (§5.2)', async () => { + const { client, tables } = makeClient() + await insertCloudProject(client, { + name: 'Doc A', + sourceLang: 'en', + targetLang: 'pt', + ownerId: 'user-1', + state: STATE, + }) + // Unset stage in the row defaults to 'translation'. + expect((await fetchCloudProject(client, 'cloud-1', 'user-1'))?.stage).toBe('translation') + + await setCloudProjectStage(client, 'cloud-1', 'review') + expect((tables.projects[0] as { stage?: string }).stage).toBe('review') + expect((await fetchCloudProject(client, 'cloud-1', 'user-1'))?.stage).toBe('review') + }) + it('defaults role to translator when membership is absent', async () => { const { client, tables } = makeClient() // A project visible via RLS but with no membership row for this user. diff --git a/tests/unit/workflow.rules.test.ts b/tests/unit/workflow.rules.test.ts new file mode 100644 index 0000000..382058e --- /dev/null +++ b/tests/unit/workflow.rules.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest' +import { + workflowCapabilities, + effectiveRoleStage, + forcesSuggesting, + type WorkflowStage, +} from '@/core/workflow/rules' +import type { ProjectRole, SegmentStatus } from '@/core/types' + +const caps = (role: ProjectRole, stage: WorkflowStage, status: SegmentStatus = 'translated') => + workflowCapabilities(role, stage, status) + +describe('workflowCapabilities — role × stage matrix (§5.2)', () => { + it('project_manager manages and edits directly through translation and review', () => { + for (const stage of ['translation', 'review'] as WorkflowStage[]) { + expect(caps('project_manager', stage)).toEqual({ + canEditDirect: true, + mustSuggest: false, + canResolveChanges: true, + canReview: true, + canManage: true, + }) + } + }) + + it('translator edits directly in translation, and is forced to suggest in review', () => { + const t = caps('translator', 'translation') + expect(t.canEditDirect).toBe(true) + expect(t.mustSuggest).toBe(false) + expect(t.canResolveChanges).toBe(false) + expect(t.canReview).toBe(false) + + const r = caps('translator', 'review') + expect(r.canEditDirect).toBe(false) + expect(r.mustSuggest).toBe(true) + }) + + it('a translator must suggest on an already-reviewed segment even in translation', () => { + const c = caps('translator', 'translation', 'reviewed') + expect(c.canEditDirect).toBe(false) + expect(c.mustSuggest).toBe(true) + }) + + it('revisor waits during translation, then edits + resolves during review', () => { + const t = caps('revisor', 'translation') + expect(t).toMatchObject({ canEditDirect: false, mustSuggest: false, canResolveChanges: true }) + + const r = caps('revisor', 'review') + expect(r).toMatchObject({ canEditDirect: true, mustSuggest: false, canResolveChanges: true, canReview: true }) + expect(r.canManage).toBe(false) + }) + + it('only revisor and project_manager can accept/reject changes', () => { + expect(caps('translator', 'review').canResolveChanges).toBe(false) + expect(caps('revisor', 'review').canResolveChanges).toBe(true) + expect(caps('project_manager', 'review').canResolveChanges).toBe(true) + }) + + it('final stage is locked to everyone but a manager', () => { + for (const role of ['translator', 'revisor'] as ProjectRole[]) { + const c = caps(role, 'final') + expect(c.canEditDirect).toBe(false) + expect(c.mustSuggest).toBe(false) + } + expect(caps('project_manager', 'final').canEditDirect).toBe(true) + }) +}) + +describe('effectiveRoleStage — local-only is PM-of-self', () => { + it('grants a manager in translation with no cloud link (zero regression)', () => { + expect(effectiveRoleStage(undefined)).toEqual({ role: 'project_manager', stage: 'translation' }) + const c = workflowCapabilities('project_manager', 'translation', 'draft') + expect(c).toMatchObject({ canEditDirect: true, canResolveChanges: true, canManage: true, mustSuggest: false }) + }) + + it('reads a cloud project’s role and defaults the stage to translation', () => { + expect(effectiveRoleStage({ role: 'translator' })).toEqual({ role: 'translator', stage: 'translation' }) + expect(effectiveRoleStage({ role: 'revisor', stage: 'review' })).toEqual({ role: 'revisor', stage: 'review' }) + }) +}) + +describe('forcesSuggesting', () => { + it('is true only for a translator in the review stage', () => { + expect(forcesSuggesting('translator', 'review')).toBe(true) + expect(forcesSuggesting('translator', 'translation')).toBe(false) + expect(forcesSuggesting('revisor', 'review')).toBe(false) + expect(forcesSuggesting('project_manager', 'review')).toBe(false) + }) +})