cmvr-visual/backend/tests/test_editor_modes.py

547 lines
19 KiB
Python
Raw Permalink Normal View History

from test_editors import spec
from sqlalchemy import select
from app.models import WorkflowDraft, WorkflowRun
async def test_mode_switch_cas_guards_and_roundtrip(system, other_client):
c = system.client
d = (
await c.post(
"/api/stories",
json={
"name": "Mode",
"spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]},
},
)
).json()
id = d["id"]
url = f"/api/editors/{id}"
initial = await c.get(url)
assert initial.json()["editing_mode"] == "manual"
switched = await c.post(
url + "/mode",
json={"expected_version": 1, "mode": "auto"},
headers={"Idempotency-Key": "enable"},
)
assert switched.status_code == 200, switched.text
assert switched.json()["editing_mode"] == "auto"
assert (
await other_client.post(
url + "/mode",
json={"expected_version": 2, "mode": "manual"},
headers={"Idempotency-Key": "foreign"},
)
).status_code == 404
manual = await c.post(
url + "/mode",
json={"expected_version": 2, "mode": "manual"},
headers={"Idempotency-Key": "manual"},
)
assert manual.status_code == 200, manual.text
assert manual.json()["editing_mode"] == "manual"
blocked = await c.post(
url + "/save",
json={"expected_version": 3, "manifest": manual.json()["manifest"]},
headers={"Idempotency-Key": "blocked"},
)
assert blocked.status_code == 409
changed = await c.patch(
f"/api/stories/{id}", json={"name": "Renamed"}, headers={"If-Match": "3"}
)
assert changed.status_code == 200, changed.text
assert changed.json()["editing_mode"] == "manual"
again = await c.post(
url + "/mode",
json={"expected_version": 4, "mode": "auto"},
headers={"Idempotency-Key": "again"},
)
assert again.status_code == 200, again.text
assert again.json()["manifest"]["spec"] == manual.json()["manifest"]["spec"]
assert (
await c.post(
url + "/mode",
json={"expected_version": 1, "mode": "manual"},
headers={"Idempotency-Key": "stale"},
)
).status_code == 409
async def test_active_run_blocks_mode_switch(system):
c = system.client
d = (
await c.post(
"/api/stories",
json={
"name": "Busy",
"spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]},
},
)
).json()
id = d["id"]
async with system.app.state.db.session() as s:
draft = await s.get(WorkflowDraft, id)
s.add(
WorkflowRun(
owner_id=draft.owner_id,
draft_id=id,
draft_revision=1,
spec_snapshot=draft.spec,
spec_hash="a" * 64,
)
)
await s.commit()
r = await c.post(
f"/api/editors/{id}/mode",
json={"expected_version": 1, "mode": "auto"},
headers={"Idempotency-Key": "busy"},
)
assert r.status_code == 409, r.text
assert r.json()["detail"]["code"] == "mode_switch_busy"
async def test_manual_projection_selection_refs_and_narration_roundtrip(system, monkeypatch):
from test_story_studio import prepare_manual_frame
from app.models import ShotSelection, ShotCandidate, AssetReference
c = system.client
d, candidate, _ = await prepare_manual_frame(system, monkeypatch)
id = d["id"]
url = f"/api/editors/{id}"
m = (await c.get(url)).json()["manifest"]
m["bindings"]["frame:" + ("1" * 32)] = {
"asset_id": candidate["asset"]["id"],
"kind": "image",
"source": "manual",
}
m["audio"]["voice"] = "zm_yunxi"
m["audio"]["segments"][0]["text"] = "保留的旁白"
m["audio"]["mode"] = "generated_narration"
m["captions"]["mode"] = "manual"
m["captions"]["cues"] = [
{
"id": "a" * 32,
"anchor": "shot",
"shot_id": "1" * 32,
"start_frame": 0,
"end_frame": 24,
"text": "旧字幕",
"text_override": True,
"timing_override": True,
}
]
saved = await c.post(
url + "/save",
json={"expected_version": 1, "manifest": m},
headers={"Idempotency-Key": "save"},
)
assert saved.status_code == 200, saved.text
manual = await c.post(
url + "/mode",
json={"expected_version": 2, "mode": "manual"},
headers={"Idempotency-Key": "manual"},
)
assert manual.status_code == 200, manual.text
assert manual.json()["story"]["spec"]["render"]["subtitles"][0]["text"] == "旧字幕"
async with system.app.state.db.session() as s:
assert not (await s.scalars(select(ShotSelection))).all()
rows = (await s.scalars(select(ShotCandidate).where(ShotCandidate.draft_id == id))).all()
assert len(rows) == 1 # 原有相同asset/hash的ready候选直接复用
projected = manual.json()["story"]["spec"]
projected["shots"][0]["name"] = "手工编辑"
projected["render"]["subtitles"][0]["text"] = "手工字幕"
patched = await c.patch(
f"/api/stories/{id}", json={"spec": projected}, headers={"If-Match": "3"}
)
assert patched.status_code == 200, patched.text
assert patched.json()["editor_manifest"]["audio"]["segments"][0]["text"] == "保留的旁白"
selected = await c.post(
f"/api/stories/{id}/selections",
json={
"expected_version": 4,
"shot_id": "1" * 32,
"kind": "frame",
"candidate_id": candidate["id"],
},
headers={"Idempotency-Key": "select"},
)
assert selected.status_code == 200, selected.text
assert selected.json()["editor_manifest"]["bindings"]["frame:" + ("1" * 32)]["locked"]
cleared = await c.post(
f"/api/stories/{id}/selections/clear",
json={"expected_version": 5, "shot_id": "1" * 32, "kind": "frame"},
headers={"Idempotency-Key": "clear"},
)
assert cleared.status_code == 200, cleared.text
assert "frame:" + ("1" * 32) not in cleared.json()["editor_manifest"]["bindings"]
auto = await c.post(
url + "/mode",
json={"expected_version": 6, "mode": "auto"},
headers={"Idempotency-Key": "auto"},
)
assert auto.status_code == 200, auto.text
m = auto.json()["manifest"]
assert m["audio"]["voice"] == "zm_yunxi" and m["audio"]["segments"][0]["text"] == "保留的旁白"
assert m["captions"]["cues"][0]["text"] == "手工字幕"
assert m["spec"]["render"]["subtitles"] == [] and m["spec"]["render"]["audio"] is None
async def test_mode_csrf_and_candidate_batch_execution_guards(system):
from app.models import ShotCandidate, Batch, BatchItem, Job, Execution
c = system.client
d = (
await c.post(
"/api/stories",
json={
"name": "Mode",
"spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]},
},
)
).json()
id = d["id"]
url = f"/api/editors/{id}/mode"
body = {"expected_version": 1, "mode": "auto"}
assert (
await c.post(url, json=body, headers={"X-CSRF-Token": "bad", "Idempotency-Key": "csrf"})
).status_code == 403
async with system.app.state.db.session() as s:
draft = await s.get(WorkflowDraft, id)
candidate = ShotCandidate(
owner_id=draft.owner_id,
draft_id=id,
shot_id="1" * 32,
kind="frame",
source_kind="manual",
context_hash="a" * 64,
generation_hash="b" * 64,
created_revision=1,
state="queued",
)
s.add(candidate)
await s.flush()
cid = candidate.id
owner = draft.owner_id
await s.commit()
async def switch(key):
return await c.post(url, json=body, headers={"Idempotency-Key": key})
assert (await switch("candidate")).status_code == 409
async with system.app.state.db.session() as s:
(await s.get(ShotCandidate, cid)).state = "failed"
batch = Batch(owner_id=owner, name="pending", state="queued")
s.add(batch)
await s.flush()
bid = batch.id
s.add(BatchItem(batch_id=bid, item_index=0, target_kind="candidate", target_id=cid))
await s.commit()
assert (await switch("batch")).status_code == 409
async with system.app.state.db.session() as s:
(await s.get(Batch, bid)).state = "succeeded"
job = Job(
owner_id=owner,
task_type="image.generate",
state="failed",
phase="failed",
input_json={},
parameters={},
request_hash="a" * 64,
upstream_key="mode-execution",
)
s.add(job)
await s.flush()
jid = job.id
(await s.get(ShotCandidate, cid)).job_id = jid
ex = Execution(
job_id=jid,
ordinal=1,
phase_key="gpu",
resource_pool="new_gpu",
fence_token="a" * 32,
state="unknown",
)
s.add(ex)
await s.flush()
eid = ex.id
await s.commit()
assert (await switch("execution")).status_code == 409
async with system.app.state.db.session() as s:
(await s.get(Execution, eid)).state = "exited"
await s.commit()
final = await switch("drained")
assert final.status_code == 200, final.text
async def test_mode_real_session_and_auto_mode_cannot_be_forged(system):
import pytest
from fastapi import HTTPException
from app.models import Session
from app.core.security import Actor
from app.schemas.editors import EditorMode
from app.services.editor_modes import change_mode
c = system.client
d = (
await c.post(
"/api/stories",
json={
"name": "Mode",
"spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]},
},
)
).json()
id = d["id"]
url = f"/api/editors/{id}"
m = (await c.get(url)).json()["manifest"]
m["editing_mode"] = "manual"
forged = await c.post(
url + "/save",
json={"expected_version": 1, "manifest": m},
headers={"Idempotency-Key": "forge"},
)
assert forged.status_code == 409
async with system.app.state.db.session() as s:
row = await s.scalar(select(Session))
draft = await s.get(WorkflowDraft, id)
actor = Actor(
draft.owner_id, "admin", "Admin", "admin", "csrf", row.token_hash, auth_kind="bearer"
)
with pytest.raises(HTTPException) as exc:
await change_mode(
system.app.state, actor, id, EditorMode(expected_version=1, mode="auto"), "bearer"
)
assert exc.value.status_code == 403
actor.auth_kind = "session"
async with system.app.state.db.session() as s:
await s.delete(await s.scalar(select(Session)))
await s.commit()
with pytest.raises(HTTPException) as exc:
await change_mode(
system.app.state, actor, id, EditorMode(expected_version=1, mode="auto"), "revoked"
)
assert exc.value.status_code == 401
async def test_manual_removing_shot_cleans_only_deleted_anchors(system):
c = system.client
d = (
await c.post(
"/api/stories",
json={
"name": "Two",
"spec": {
"schema_version": 3,
"shots": [
{"id": "1" * 32, "visual_prompt": "tree"},
{"id": "2" * 32, "visual_prompt": "river"},
],
},
},
)
).json()
id = d["id"]
url = f"/api/editors/{id}"
m = (await c.get(url)).json()["manifest"]
removed = m["audio"]["segments"][1]["id"]
m["captions"]["mode"] = "manual"
m["captions"]["cues"] = [
dict(
id="a" * 32,
anchor="shot",
shot_id="2" * 32,
start_frame=0,
end_frame=24,
text="gone",
text_override=True,
timing_override=True,
),
dict(
id="b" * 32,
anchor="absolute",
start_frame=0,
end_frame=24,
text="kept",
text_override=True,
timing_override=True,
),
]
saved = await c.post(
url + "/save",
json={"expected_version": 1, "manifest": m},
headers={"Idempotency-Key": "save"},
)
assert saved.status_code == 200, saved.text
manual = await c.post(
url + "/mode",
json={"expected_version": 2, "mode": "manual"},
headers={"Idempotency-Key": "manual"},
)
assert manual.status_code == 200, manual.text
projected = manual.json()["story"]["spec"]
projected["shots"] = projected["shots"][:1]
projected["render"]["total_frames"] = 120
# 保持旧字幕投影不变;被删镜头锚点由桥接层按原稳定ID清理。
projected["render"]["subtitles"] = [
x for x in projected["render"]["subtitles"] if x["start_frame"] < 120
]
patched = await c.patch(
f"/api/stories/{id}", json={"spec": projected}, headers={"If-Match": "3"}
)
assert patched.status_code == 200, patched.text
auto = await c.post(
url + "/mode",
json={"expected_version": 4, "mode": "auto"},
headers={"Idempotency-Key": "auto"},
)
assert auto.status_code == 200, auto.text
result = auto.json()["manifest"]
assert len(result["audio"]["segments"]) == 1 and result["audio"]["segments"][0]["id"] != removed
assert len(result["captions"]["cues"]) == 1 and result["captions"]["cues"][0]["id"] == "b" * 32
plan = await c.post(url + "/plan", json={"expected_version": 5, "output_goal": "film"})
assert plan.status_code == 200, plan.text
assert not any(x["code"].startswith("orphan") for x in plan.json()["issues"])
async def test_completed_run_with_pending_parent_batch_blocks_switch(system):
from app.models import Batch, BatchItem
c = system.client
d = (
await c.post(
"/api/stories",
json={
"name": "Batch",
"spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]},
},
)
).json()
id = d["id"]
async with system.app.state.db.session() as s:
draft = await s.get(WorkflowDraft, id)
run = WorkflowRun(
owner_id=draft.owner_id,
draft_id=id,
draft_revision=1,
spec_snapshot=draft.spec,
spec_hash="a" * 64,
state="succeeded",
)
s.add(run)
await s.flush()
batch = Batch(owner_id=draft.owner_id, name="paused", state="paused")
s.add(batch)
await s.flush()
s.add(BatchItem(batch_id=batch.id, item_index=0, target_kind="run", target_id=run.id))
await s.commit()
r = await c.post(
f"/api/editors/{id}/mode",
json={"expected_version": 1, "mode": "auto"},
headers={"Idempotency-Key": "pending-parent"},
)
assert r.status_code == 409 and r.json()["detail"]["code"] == "mode_switch_busy"
async def test_deleted_unlaunched_candidate_does_not_block_mode(system):
from app.models import ShotCandidate
c = system.client
d = (
await c.post(
"/api/stories",
json={
"name": "Deleted plan",
"spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]},
},
)
).json()
id = d["id"]
created = await c.post(
f"/api/stories/{id}/candidates",
json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"},
headers={"Idempotency-Key": "candidate"},
)
assert created.status_code == 202, created.text
candidate = created.json()["candidates"][0]
async with system.app.state.db.session() as s:
row = await s.get(ShotCandidate, candidate["id"])
assert row.state == "queued" and row.job_id is None
deleted = await c.delete(
f"/api/stories/{id}/candidates/{candidate['id']}",
headers={"If-Match": str(candidate["version"])},
)
assert deleted.status_code == 200, deleted.text
switched = await c.post(
f"/api/editors/{id}/mode",
json={"expected_version": 1, "mode": "auto"},
headers={"Idempotency-Key": "mode"},
)
assert switched.status_code == 200, switched.text
async def test_deleted_candidate_still_fences_unfinished_execution(system):
from app.models import ShotCandidate, Job, Execution
c = system.client
d = (
await c.post(
"/api/stories",
json={
"name": "Deleted execution",
"spec": {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "tree"}]},
},
)
).json()
id = d["id"]
created = await c.post(
f"/api/stories/{id}/candidates",
json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"},
headers={"Idempotency-Key": "candidate"},
)
assert created.status_code == 202, created.text
candidate = created.json()["candidates"][0]
deleted = await c.delete(
f"/api/stories/{id}/candidates/{candidate['id']}",
headers={"If-Match": str(candidate["version"])},
)
assert deleted.status_code == 200, deleted.text
async with system.app.state.db.session() as s:
row = await s.get(ShotCandidate, candidate["id"])
assert row.deleted_at is not None and row.state == "queued"
job = Job(
owner_id=row.owner_id,
task_type="image.generate",
state="failed",
phase="failed",
input_json={},
parameters={},
request_hash="a" * 64,
upstream_key="deleted-mode-execution",
)
s.add(job)
await s.flush()
row.job_id = job.id
execution = Execution(
job_id=job.id,
ordinal=1,
phase_key="gpu",
resource_pool="new_gpu",
fence_token="a" * 32,
state="unknown",
)
s.add(execution)
await s.flush()
eid = execution.id
await s.commit()
body = {"expected_version": 1, "mode": "auto"}
blocked = await c.post(
f"/api/editors/{id}/mode", json=body, headers={"Idempotency-Key": "blocked"}
)
assert blocked.status_code == 409 and blocked.json()["detail"]["code"] == "mode_switch_busy"
async with system.app.state.db.session() as s:
(await s.get(Execution, eid)).state = "exited"
await s.commit()
drained = await c.post(
f"/api/editors/{id}/mode", json=body, headers={"Idempotency-Key": "drained"}
)
assert drained.status_code == 200, drained.text