File size: 5,748 Bytes
115b94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""Saved work and opaque UI drafts; real backend, synthetic model, no VM/model dispatch."""
import io
import json
import time
import unittest
import zipfile
from pathlib import Path
from fastapi.testclient import TestClient
from src.apps.workbench.engine import LocalWorkbench
from src.apps.workbench.web import create_web
from src.modules.skill.domain.models import digest
from src.tests.runtime.fixtures import setup,workspace

PAGE='''<!doctype html><html><head><style>body{font:18px sans-serif}</style></head><body>
<h1>订单界面草稿</h1><button id="see" onclick="document.getElementById('result').textContent='界面按钮已响应;接口未连接'">查看界面响应</button>
<p id="result">订单接口仍待测试</p><p id="isolation"></p><script>
try { parent.document.body; document.getElementById('isolation').textContent='隔离失败'; }
catch(e) { document.getElementById('isolation').textContent='父页面访问已隔离'; }
</script></body></html>'''
FILES={'src/main/java/demo/App.java':'package demo; public class App {}','website/index.html':PAGE}


class SavedWorkTests(unittest.TestCase):
    def setUp(self):
        folder=Path(self.enterContext(workspace()))
        _,_,self.model,_=setup(folder/'model')
        self.e=LocalWorkbench(folder/'web',[self.model],start_worker=False,recover_incomplete=False,resource_limited=False)
        self.e.identity.seed_demo_users()
        self.e.runtimes['business-app'].sandbox.preflight=lambda:None
        self.c=self.enterContext(TestClient(create_web(self.e,preview_port=8791)))
        self.c.headers['Origin']='http://127.0.0.1:8789'
        auth=self.c.post('/api/session/login',json={'username':'programmer','password':'VibeCoding@2026'}).json()
        self.c.headers['X-CSRF-Token']=auth['csrf']
        actor=self.e.identity.actor(auth['actor']['user_id']) if 'actor' in auth else self.e.identity.actor(self.c.get('/api/session').json()['actor']['user_id'])
        self.actor=actor
        self.rid=self.e.submit(actor,'business-app','订单查询,未找到显示提示。','saved-work-test')['id']

    def candidate(self):
        def save(r):
            node=next(n for n in r['release']['draft']['graph']['nodes'] if (n.get('operation_ref') or '').startswith('AO06@'))
            r['outputs'][node['id']]={'source':{'files':FILES,'source_digest':digest(FILES)}}
            r.update(status='running',claim='saved-work-test',claim_started_at=time.time(),lease_until=time.time()+900)
        self.e.store.mutate(self.rid,save)
        with self.e.store.connect() as db:db.execute("UPDATE web_jobs SET state='working' WHERE id=?",(self.rid,))

    def archive(self):
        r=self.c.get('/api/jobs/'+self.rid+'/snapshot');self.assertEqual(r.status_code,200,r.text[:150] if r.status_code!=200 else '')
        return zipfile.ZipFile(io.BytesIO(r.content))

    def test_before_source_download_preserves_requirement_and_marks_missing_code(self):
        with self.archive() as z:
            m=json.loads(z.read('snapshot-manifest.json'))
            self.assertIsNone(m['source_digest']);self.assertFalse(m['verified'])
            self.assertIn('订单查询',z.read('docs/requirements.md').decode())
            self.assertFalse(any(p.endswith('.java') for p in z.namelist()))
        self.assertEqual(self.model.count,0)

    def test_testing_and_cancelled_snapshots_preserve_exact_source(self):
        self.candidate()
        with self.archive() as z:
            self.assertEqual(z.read('website/index.html').decode(),PAGE)
            self.assertFalse(json.loads(z.read('snapshot-manifest.json'))['verified'])
        # Client cancellation preserves all outputs and accounting; no worker is running.
        self.e.store.mutate(self.rid,lambda r:r.update(status='queued'))
        cancelled=self.c.post('/api/jobs/'+self.rid+'/cancel',json={})
        self.assertEqual(cancelled.status_code,200);self.assertEqual(cancelled.json()['status'],'cancelled')
        with self.archive() as z:
            self.assertEqual(z.read('src/main/java/demo/App.java').decode(),FILES['src/main/java/demo/App.java'])
            self.assertEqual(json.loads(z.read('snapshot-manifest.json'))['status'],'cancelled')
        self.assertEqual(self.model.count,0)

    def test_unknown_reservation_untouched_and_no_replay(self):
        self.candidate()
        cid=self.e.store.reserve(self.rid,'simulated','prompt',4321)
        self.e.store.settle(cid,'unknown')
        self.e.store.mutate(self.rid,lambda r:r.update(status='unknown',error='MODEL_RESULT_UNKNOWN'))
        before=self.e.store.calls(self.rid)
        self.archive().close()
        self.assertEqual(self.e.store.calls(self.rid),before);self.assertEqual(self.model.count,0)

    def test_draft_is_ui_only_sandboxed_and_cannot_start_full_preview(self):
        self.candidate()
        preview=self.enterContext(TestClient(create_web(self.e,8791,workbench_port=8789,preview_only=True,owns_engine=False)))
        preview.cookies.update(self.c.cookies)
        r=preview.get('/draft-preview/'+self.rid+'/')
        self.assertEqual(r.status_code,200);self.assertIn('界面草稿 · 未验收',r.text)
        self.assertIn('sandbox="allow-scripts"',r.text);self.assertNotIn('allow-same-origin',r.text)
        self.assertIn("connect-src 'none'",r.headers['Content-Security-Policy'])
        self.assertEqual(self.c.post('/api/preview',json={'kind':'run','reference':self.rid}).status_code,409)
        self.assertEqual(self.model.count,0)
        preview.cookies.clear();self.assertEqual(preview.get('/draft-preview/'+self.rid+'/').status_code,401)
        self.c.cookies.clear();self.assertEqual(self.c.get('/api/jobs/'+self.rid+'/snapshot').status_code,401)


if __name__=='__main__':unittest.main()