Wizzas commited on
Commit
4946331
·
verified ·
1 Parent(s): 46e957e

Deploy migration-compatible private workspace adapter; activation remains opt-in

Browse files
backend/gallery.py CHANGED
@@ -174,7 +174,7 @@ def mount_gallery(app,repo,artifacts,gallery=None,owner=lambda:'local-operator',
174
  ready()
175
  if body.consent is not True:raise HTTPException(422,'Explicit public publication consent is required.')
176
  record=saved(identifier);actor,source,_=keys(identifier)
177
- if record.get('storage')=='supabase':
178
  current=repo.current()
179
  if record.get('owner_id')!=current.user['id']:
180
  raise HTTPException(403,'Only the original staff uploader can publish this inspection.')
@@ -182,7 +182,7 @@ def mount_gallery(app,repo,artifacts,gallery=None,owner=lambda:'local-operator',
182
  previews=[]
183
  for kind,suffix in (('image',''),('heatmap','_heatmap')):
184
  path=Path(artifacts)/f'{identifier}{suffix}.jpg'
185
- if record.get('storage')!='supabase':
186
  if not path.is_file():raise HTTPException(409,'Saved image is unavailable. Nothing was published.')
187
  content=path.read_bytes()
188
  else:
 
174
  ready()
175
  if body.consent is not True:raise HTTPException(422,'Explicit public publication consent is required.')
176
  record=saved(identifier);actor,source,_=keys(identifier)
177
+ if record.get('storage','').startswith('supabase'):
178
  current=repo.current()
179
  if record.get('owner_id')!=current.user['id']:
180
  raise HTTPException(403,'Only the original staff uploader can publish this inspection.')
 
182
  previews=[]
183
  for kind,suffix in (('image',''),('heatmap','_heatmap')):
184
  path=Path(artifacts)/f'{identifier}{suffix}.jpg'
185
+ if not record.get('storage','').startswith('supabase'):
186
  if not path.is_file():raise HTTPException(409,'Saved image is unavailable. Nothing was published.')
187
  content=path.read_bytes()
188
  else:
backend/main.py CHANGED
@@ -145,6 +145,21 @@ def create_app(settings=None, detector=None, workflow=None, repository=None, gal
145
  return {'data':result}
146
  @app.get('/api/stats')
147
  def stats(): return {'data':repo.stats()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  @app.get('/api/samples')
149
  def samples():
150
  return {'data':[{'name':p.stem,'category':p.stem.rsplit('_',1)[0],'url':'/api/samples/'+p.name,
 
145
  return {'data':result}
146
  @app.get('/api/stats')
147
  def stats(): return {'data':repo.stats()}
148
+ @app.get('/api/workspace')
149
+ def workspace_status():
150
+ return {'data':repo.status() if hasattr(repo,'status') else {'personal_enabled':False,'workspace':'local','storage':'local_disk','authenticated':False}}
151
+ class ShareRequest(BaseModel):
152
+ include_conversation:bool=False
153
+ @app.post('/api/inspections/{identifier}/share')
154
+ def share_personal(identifier:str,body:ShareRequest):
155
+ if not re.fullmatch('[a-f0-9]{32}',identifier):raise HTTPException(422,'Invalid inspection ID')
156
+ if not hasattr(repo,'share'):raise HTTPException(409,'Use the existing staff sharing action in this build.')
157
+ return {'data':repo.share(identifier,body.include_conversation)}
158
+ @app.post('/api/inspections/{identifier}/save-personal')
159
+ def save_guest_personal(identifier:str):
160
+ if not re.fullmatch('[a-f0-9]{32}',identifier):raise HTTPException(422,'Invalid inspection ID')
161
+ if not hasattr(repo,'share'):raise HTTPException(409,'Personal cloud storage is not enabled in this build.')
162
+ return {'data':repo.share(identifier,personal_only=True)}
163
  @app.get('/api/samples')
164
  def samples():
165
  return {'data':[{'name':p.stem,'category':p.stem.rsplit('_',1)[0],'url':'/api/samples/'+p.name,
deployment/space/app.py CHANGED
@@ -29,7 +29,7 @@ from backend.calibration import calibrated_card
29
  from backend.highres import HighResolutionEncoder, foreground_mask, score_tokens, restore_map
30
  from backend.vision import sha256, display_map
31
  from backend.storage import now
32
- from deployment.space.sessions import SessionRepository, identity, namespace, NAMESPACE, STAFF_TOKEN, authorize_artifact, capability, remember_staff, stored_staff
33
 
34
  ZERO = os.getenv('SPACES_ZERO_GPU') == '1'
35
  DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
@@ -82,7 +82,8 @@ CLOUD_CONFIG=None
82
  if os.getenv('DEFECTRAG_STAFF_BACKEND')=='1':
83
  from deployment.space.supabase_repository import read_public_config
84
  CLOUD_CONFIG=read_public_config(UI/'config.js')
85
- REPO = SessionRepository(RUNTIME/'sessions',cloud_config=CLOUD_CONFIG,artifacts=ARTIFACTS)
 
86
  from backend.main import create_app
87
  from backend.rag import KnowledgeIndex, EvidenceWorkflow
88
  if os.getenv('DEFECTRAG_LIVE_RAG')=='1':
@@ -122,17 +123,22 @@ async def workspace_access(request, call_next):
122
  if not path.startswith('/api/') or public:
123
  return await call_next(request)
124
  try:
 
 
125
  match = re.fullmatch(r'/api/inspections/([a-f0-9]{32})/(image|heatmap|report)', path)
126
  if match and 'access' in request.query_params:
127
  owner = authorize_artifact(request.query_params['access'], *match.groups())
 
128
  elif path == '/api/export.csv' and 'access' in request.query_params:
129
  owner = authorize_artifact(request.query_params['access'],'workspace','csv')
 
130
  else:
131
  owner = namespace(request.headers.get('X-DefectRAG-Session',''))
132
- context = NAMESPACE.set(owner)
133
  bearer=request.headers.get('authorization','').removeprefix('Bearer ')
134
  if request.headers.get('X-DefectRAG-Session'):
135
  remember_staff(owner,bearer)
 
 
136
  token = STAFF_TOKEN.set(bearer or stored_staff(owner))
137
  except ValueError as exc:
138
  return JSONResponse({'error': {'message': str(exc)}}, status_code=401)
@@ -142,6 +148,7 @@ async def workspace_access(request, call_next):
142
  response.headers['Cache-Control'] = 'private, no-store'
143
  return response
144
  finally:
 
145
  STAFF_TOKEN.reset(token)
146
  NAMESPACE.reset(context)
147
 
@@ -197,19 +204,20 @@ def inspect_one(image_b64, filename, category, batch, request_id=''):
197
 
198
 
199
  @server.api(name='inspect',concurrency_limit=1,concurrency_id='model-work')
200
- def inspect(image_b64: str, filename: str, category: str, batch: str, session: str, token: str='', request_id: str='') -> dict:
201
- with identity(session,token):
 
202
  REPO.current() # Validate signed-in staff membership before consuming GPU.
203
  return inspect_one(image_b64,filename,category,batch,request_id)
204
 
205
 
206
  @server.api(name='assistant',concurrency_limit=1,concurrency_id='model-work')
207
- def assistant(inspection_id: str, question: str, session: str, token: str='') -> dict:
208
  if not 3<=len(question)<=1200 or not re.fullmatch('[a-f0-9]{32}',inspection_id):
209
  raise ValueError('Use a saved inspection and a question of 3–1200 characters.')
210
  if WORKFLOW is None:
211
  raise ValueError('Live evidence generation is not enabled in this deployment yet.')
212
- with identity(session,token):
213
  record=REPO.get(inspection_id)
214
  if record is None:
215
  raise ValueError('Inspection is unavailable in your workspace')
@@ -226,6 +234,7 @@ def health():
226
  'encoder_configured':True,'llm_model':'Qwen3-4B-Instruct-2507' if WORKFLOW and ZERO else 'Qwen2.5:3b (local Ollama)' if WORKFLOW else 'generation migration in progress','zero_gpu':ZERO,
227
  'staff_persistence_enabled':CLOUD_CONFIG is not None,
228
  'community_gallery_enabled':GALLERY is not None,
 
229
  'history':'anonymous browser history is temporary; signed-in approved staff use Supabase' if CLOUD_CONFIG else 'anonymous browser history is temporary; staff backend disabled'}}
230
 
231
 
@@ -233,7 +242,7 @@ def artifact(identifier: str,kind: str):
233
  record=REPO.get(identifier)
234
  if record is None:
235
  raise HTTPException(404,'Inspection not found')
236
- if record.get('storage')=='supabase':
237
  return RedirectResponse(record[kind+'_url'],status_code=307)
238
  return FileResponse(ARTIFACTS/f"{identifier}{'_heatmap' if kind=='heatmap' else ''}.jpg")
239
 
 
29
  from backend.highres import HighResolutionEncoder, foreground_mask, score_tokens, restore_map
30
  from backend.vision import sha256, display_map
31
  from backend.storage import now
32
+ from deployment.space.sessions import SessionRepository, identity, namespace, NAMESPACE, STAFF_TOKEN, WORKSPACE, artifact_workspace, authorize_artifact, capability, remember_staff, stored_staff
33
 
34
  ZERO = os.getenv('SPACES_ZERO_GPU') == '1'
35
  DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
 
82
  if os.getenv('DEFECTRAG_STAFF_BACKEND')=='1':
83
  from deployment.space.supabase_repository import read_public_config
84
  CLOUD_CONFIG=read_public_config(UI/'config.js')
85
+ PERSONAL_ENABLED=os.getenv('DEFECTRAG_PERSONAL_WORKSPACE')=='1' and CLOUD_CONFIG is not None
86
+ REPO = SessionRepository(RUNTIME/'sessions',cloud_config=CLOUD_CONFIG,artifacts=ARTIFACTS,personal_enabled=PERSONAL_ENABLED)
87
  from backend.main import create_app
88
  from backend.rag import KnowledgeIndex, EvidenceWorkflow
89
  if os.getenv('DEFECTRAG_LIVE_RAG')=='1':
 
123
  if not path.startswith('/api/') or public:
124
  return await call_next(request)
125
  try:
126
+ requested_scope=request.headers.get('X-DefectRAG-Workspace','personal')
127
+ if requested_scope not in ('personal','team'):raise ValueError('Invalid workspace')
128
  match = re.fullmatch(r'/api/inspections/([a-f0-9]{32})/(image|heatmap|report)', path)
129
  if match and 'access' in request.query_params:
130
  owner = authorize_artifact(request.query_params['access'], *match.groups())
131
+ requested_scope=artifact_workspace(request.query_params['access'])
132
  elif path == '/api/export.csv' and 'access' in request.query_params:
133
  owner = authorize_artifact(request.query_params['access'],'workspace','csv')
134
+ requested_scope=artifact_workspace(request.query_params['access'])
135
  else:
136
  owner = namespace(request.headers.get('X-DefectRAG-Session',''))
 
137
  bearer=request.headers.get('authorization','').removeprefix('Bearer ')
138
  if request.headers.get('X-DefectRAG-Session'):
139
  remember_staff(owner,bearer)
140
+ context = NAMESPACE.set(owner)
141
+ scope_context=WORKSPACE.set(requested_scope)
142
  token = STAFF_TOKEN.set(bearer or stored_staff(owner))
143
  except ValueError as exc:
144
  return JSONResponse({'error': {'message': str(exc)}}, status_code=401)
 
148
  response.headers['Cache-Control'] = 'private, no-store'
149
  return response
150
  finally:
151
+ WORKSPACE.reset(scope_context)
152
  STAFF_TOKEN.reset(token)
153
  NAMESPACE.reset(context)
154
 
 
204
 
205
 
206
  @server.api(name='inspect',concurrency_limit=1,concurrency_id='model-work')
207
+ def inspect(image_b64: str, filename: str, category: str, batch: str, session: str, token: str='', request_id: str='', workspace: str='personal') -> dict:
208
+ if PERSONAL_ENABLED and workspace!='personal':raise ValueError('New inspections must run in Personal workspace; sharing is a separate action.')
209
+ with identity(session,token,workspace):
210
  REPO.current() # Validate signed-in staff membership before consuming GPU.
211
  return inspect_one(image_b64,filename,category,batch,request_id)
212
 
213
 
214
  @server.api(name='assistant',concurrency_limit=1,concurrency_id='model-work')
215
+ def assistant(inspection_id: str, question: str, session: str, token: str='', workspace: str='personal') -> dict:
216
  if not 3<=len(question)<=1200 or not re.fullmatch('[a-f0-9]{32}',inspection_id):
217
  raise ValueError('Use a saved inspection and a question of 3–1200 characters.')
218
  if WORKFLOW is None:
219
  raise ValueError('Live evidence generation is not enabled in this deployment yet.')
220
+ with identity(session,token,workspace):
221
  record=REPO.get(inspection_id)
222
  if record is None:
223
  raise ValueError('Inspection is unavailable in your workspace')
 
234
  'encoder_configured':True,'llm_model':'Qwen3-4B-Instruct-2507' if WORKFLOW and ZERO else 'Qwen2.5:3b (local Ollama)' if WORKFLOW else 'generation migration in progress','zero_gpu':ZERO,
235
  'staff_persistence_enabled':CLOUD_CONFIG is not None,
236
  'community_gallery_enabled':GALLERY is not None,
237
+ 'personal_workspace_enabled':PERSONAL_ENABLED,
238
  'history':'anonymous browser history is temporary; signed-in approved staff use Supabase' if CLOUD_CONFIG else 'anonymous browser history is temporary; staff backend disabled'}}
239
 
240
 
 
242
  record=REPO.get(identifier)
243
  if record is None:
244
  raise HTTPException(404,'Inspection not found')
245
+ if record.get('storage','').startswith('supabase'):
246
  return RedirectResponse(record[kind+'_url'],status_code=307)
247
  return FileResponse(ARTIFACTS/f"{identifier}{'_heatmap' if kind=='heatmap' else ''}.jpg")
248
 
deployment/space/personal_repository.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Owner-only account persistence. User JWT + RLS; no privileged API credential."""
2
+ import hashlib
3
+ import json
4
+ import httpx
5
+ from urllib.parse import quote
6
+ from .supabase_repository import StaffRepository
7
+
8
+
9
+ class PersonalRepository(StaffRepository):
10
+ table='personal_inspections'
11
+ bucket='personal-inspections'
12
+ notes_table='personal_notes'
13
+ storage_type='supabase_personal'
14
+ workspace='personal'
15
+ workspace_stats_enabled=True
16
+
17
+ def _raw_any(self,identifier):
18
+ rows=self.request('GET','/rest/v1/'+self.table,params={
19
+ 'id':'eq.'+identifier,'owner_id':'eq.'+self.user['id'],'select':'*','limit':'1'})
20
+ return rows[0] if rows else None
21
+
22
+ def raw(self,identifier,archived=False):
23
+ row=self._raw_any(identifier)
24
+ return row if row and bool(row.get('archived_at'))==archived else None
25
+
26
+ def raw_list(self,category='',verdict='',batch='',limit=100,offset=0,archived=False):
27
+ # RLS remains the authority; an explicit owner filter adds defense in depth.
28
+ params={'owner_id':'eq.'+self.user['id'],'select':'*','order':'created_at.desc,id.desc',
29
+ 'archived_at':'not.is.null' if archived else 'is.null','limit':str(limit),'offset':str(offset)}
30
+ for key,value in (('category',category),('verdict',verdict),('batch',batch)):
31
+ if value:params['payload->>'+key]='eq.'+value
32
+ return self.request('GET','/rest/v1/'+self.table,params=params)
33
+
34
+ def _upload(self,bucket,identifier,kind,source):
35
+ content=source.read_bytes()
36
+ destination=f"{self.user['id']}/{identifier}/{kind}-{hashlib.sha256(content).hexdigest()}.jpg"
37
+ # The hash is part of the immutable object name. A replay may encounter
38
+ # an already uploaded object after a failed row insert; never overwrite it.
39
+ self.request('POST','/storage/v1/object/'+bucket+'/'+destination,content=content,
40
+ headers={'Content-Type':'image/jpeg','x-upsert':'false'},ignore_conflict=True)
41
+ return destination
42
+
43
+ @staticmethod
44
+ def _same(existing,record):
45
+ previous=existing['payload']
46
+ if previous.get('request_fingerprint') and record.get('request_fingerprint'):
47
+ return previous['request_fingerprint']==record['request_fingerprint']
48
+ return all(previous.get(k)==record.get(k) for k in ('id','category','batch','score','threshold','model_id'))
49
+
50
+ def save(self,record,conversation=None):
51
+ messages=conversation or []
52
+ if len(json.dumps(messages).encode())>40000:raise ValueError('Saved conversation is too large to import safely.')
53
+ existing=self._raw_any(record['id'])
54
+ if existing:
55
+ if existing.get('archived_at') or not self._same(existing,record):
56
+ raise ValueError('Inspection ID already exists with different data or is archived. No overwrite occurred.')
57
+ return self.decorate(existing)
58
+ paths={kind+'_path':self._upload(self.bucket,record['id'],kind,self.artifacts/f"{record['id']}{suffix}.jpg")
59
+ for kind,suffix in (('image',''),('heatmap','_heatmap'))}
60
+ payload={k:v for k,v in record.items() if not k.endswith('_url') and k not in ('storage','workspace','owner_id')}
61
+ row={'id':record['id'],'owner_id':self.user['id'],'created_at':record['created_at'],
62
+ 'payload':payload,'conversation':messages,'archived_at':None,**paths}
63
+ self.request('POST','/rest/v1/'+self.table,json=row,headers={'Prefer':'return=minimal'},ignore_conflict=True)
64
+ confirmed=self._raw_any(record['id'])
65
+ if not confirmed or not self._same(confirmed,record):
66
+ raise RuntimeError('Personal save could not be verified. No durable success was reported.')
67
+ return self.decorate(confirmed)
68
+
69
+ def add_conversation(self,identifier,question,answer):
70
+ return self.request('POST','/rest/v1/rpc/defectrag_personal_action',json={
71
+ 'p_id':identifier,'p_action':'conversation','p_question':question,'p_answer':answer})
72
+
73
+ def acknowledge(self,identifier):
74
+ return bool(self.request('POST','/rest/v1/rpc/defectrag_personal_action',json={
75
+ 'p_id':identifier,'p_action':'acknowledge'}))
76
+
77
+ def archive(self,category='',verdict='',batch=''):
78
+ ids=[row['id'] for row in self.raw_list(category,verdict,batch,limit=500)]
79
+ changed=self.request('POST','/rest/v1/rpc/defectrag_personal_archive',json={'p_ids':ids,'p_restore':False}) if ids else 0
80
+ return {'archived':changed,'scope':'up to 500 matching personal records; files retained'}
81
+
82
+ def restore(self,identifiers):
83
+ return {'restored':self.request('POST','/rest/v1/rpc/defectrag_personal_archive',json={'p_ids':identifiers,'p_restore':True})}
84
+
85
+ def _read_private_image(self,path):
86
+ # Bound the actual streamed bytes, including responses without a length
87
+ # header. A failed read must never advance to the team-copy RPC.
88
+ try:
89
+ with httpx.Client(timeout=25,trust_env=False) as client:
90
+ with client.stream('GET',self.config['url']+'/storage/v1/object/authenticated/'+self.bucket+'/'+quote(path,safe='/'),headers=self.headers) as response:
91
+ if not response.is_success:
92
+ raise RuntimeError('Private image could not be copied. No team success was reported.')
93
+ content=bytearray()
94
+ for chunk in response.iter_bytes(chunk_size=64*1024):
95
+ if len(content)+len(chunk)>10*1024*1024:
96
+ raise RuntimeError('Private image exceeds the copy limit. No team success was reported.')
97
+ content.extend(chunk)
98
+ if not content:
99
+ raise RuntimeError('Private image is empty. No team success was reported.')
100
+ return bytes(content)
101
+ except httpx.HTTPError:
102
+ raise RuntimeError('Private image transfer failed. Retry sharing when the connection is available.') from None
103
+
104
+ def share(self,identifier,include_conversation=False):
105
+ row=self.raw(identifier)
106
+ if not row:raise ValueError('An active owned personal inspection is required to share.')
107
+ existing=self.request('GET','/rest/v1/shared_inspections',params={'id':'eq.'+identifier,'select':'id,owner_id','limit':'1'})
108
+ if existing:
109
+ if existing[0]['owner_id']!=self.user['id']:raise ValueError('Inspection ID conflict; nothing was shared.')
110
+ return {'alreadyShared':True}
111
+ paths={}
112
+ for kind in ('image','heatmap'):
113
+ # Copy immutable bytes with the same user JWT. Personal object reads
114
+ # remain owner-only; other staff get only the explicit team copy.
115
+ path=row[kind+'_path']
116
+ content=self._read_private_image(path)
117
+ digest=hashlib.sha256(content).hexdigest()
118
+ target=f"{self.user['id']}/{identifier}/{kind}-{digest}.jpg"
119
+ self.request('POST','/storage/v1/object/team-inspections/'+target,content=content,
120
+ headers={'Content-Type':'image/jpeg','x-upsert':'false'},ignore_conflict=True)
121
+ paths[kind]=target
122
+ inserted=self.request('POST','/rest/v1/rpc/defectrag_share_personal',json={
123
+ 'p_id':identifier,'p_image_path':paths['image'],'p_heatmap_path':paths['heatmap'],
124
+ 'p_include_conversation':bool(include_conversation)})
125
+ return {'alreadyShared':not inserted}
deployment/space/sessions.py CHANGED
@@ -13,6 +13,7 @@ from backend.storage import SQLiteRepository
13
 
14
  NAMESPACE = ContextVar('defectrag_namespace', default=None)
15
  STAFF_TOKEN = ContextVar('defectrag_staff_token', default='')
 
16
  SIGNING_KEY = os.environ.get('DEFECTRAG_SIGNING_KEY', '').encode() or os.urandom(32)
17
  _staff_sessions={}
18
  _session_lock=threading.Lock()
@@ -45,20 +46,23 @@ def namespace(session):
45
 
46
 
47
  @contextmanager
48
- def identity(session, token=''):
 
49
  owner=namespace(session)
50
  remember_staff(owner,token)
51
  marker = NAMESPACE.set(owner)
52
  staff = STAFF_TOKEN.set(token)
 
53
  try:
54
  yield
55
  finally:
 
56
  STAFF_TOKEN.reset(staff)
57
  NAMESPACE.reset(marker)
58
 
59
 
60
  def capability(identifier, kind):
61
- text = f'{NAMESPACE.get()}:{identifier}:{kind}:{int(time.time())+3600}'
62
  signature = hmac.new(SIGNING_KEY, text.encode(), 'sha256').hexdigest()
63
  return base64.urlsafe_b64encode(f'{text}:{signature}'.encode()).decode().rstrip('=')
64
 
@@ -66,9 +70,10 @@ def capability(identifier, kind):
66
  def authorize_artifact(access, identifier, kind):
67
  try:
68
  raw = base64.urlsafe_b64decode(access+'='*(-len(access)%4)).decode()
69
- owner, actual_id, actual_kind, expires, signature = raw.split(':')
70
- text = ':'.join((owner, actual_id, actual_kind, expires))
71
  if (not re.fullmatch('[a-f0-9]{64}', owner) or actual_id != identifier or actual_kind != kind
 
72
  or int(expires) < time.time() or not hmac.compare_digest(signature,
73
  hmac.new(SIGNING_KEY, text.encode(), 'sha256').hexdigest())):
74
  raise ValueError()
@@ -77,11 +82,17 @@ def authorize_artifact(access, identifier, kind):
77
  raise ValueError('Image or report access expired. Reopen the saved inspection.') from None
78
 
79
 
 
 
 
 
 
80
  class SessionRepository:
81
- def __init__(self, directory, cloud_config=None, artifacts=None):
82
  self.directory = Path(directory)
83
  self.cloud_config=cloud_config
84
  self.artifacts=artifacts
 
85
 
86
  def current(self):
87
  owner = NAMESPACE.get()
@@ -89,7 +100,14 @@ class SessionRepository:
89
  raise ValueError('Workspace authorization is missing')
90
  if self.cloud_config and STAFF_TOKEN.get():
91
  from deployment.space.supabase_repository import StaffRepository
92
- return StaffRepository(self.cloud_config,STAFF_TOKEN.get(),self.artifacts)
 
 
 
 
 
 
 
93
  return SQLiteRepository(self.directory / owner / 'inspection.sqlite3')
94
 
95
  def local(self):
@@ -101,7 +119,7 @@ class SessionRepository:
101
  result = dict(record)
102
  result.setdefault('storage','browser_session')
103
  for kind in ('image', 'heatmap', 'report'):
104
- if kind!='report' and result.get('storage')=='supabase' and result.get(kind+'_url','').startswith('https://'):
105
  continue
106
  result[kind+'_url'] = f"/api/inspections/{record['id']}/{kind}?access={capability(record['id'], kind)}"
107
  return result
@@ -109,24 +127,32 @@ class SessionRepository:
109
  def save(self, record):
110
  return self.decorate(self.current().save(record))
111
 
 
 
 
 
 
 
 
 
112
  def get(self, identifier):
113
  current=self.current()
114
  record=current.get(identifier)
115
  # Signing in must not invalidate this browser's earlier anonymous upload
116
  # before its explicit Share with staff operation has copied it durably.
117
- if record is None and self.cloud_config and STAFF_TOKEN.get():
118
  record=self.local().get(identifier)
119
  return self.decorate(record)
120
 
121
  def messages(self,identifier):
122
  current=self.current()
123
- if self.cloud_config and STAFF_TOKEN.get() and current.raw(identifier) is None:
124
  return self.local().messages(identifier)
125
  return current.messages(identifier)
126
 
127
  def add_conversation(self,identifier,question,answer):
128
  current=self.current()
129
- if self.cloud_config and STAFF_TOKEN.get() and current.raw(identifier) is None:
130
  return self.local().add_conversation(identifier,question,answer)
131
  return current.add_conversation(identifier,question,answer)
132
 
@@ -135,7 +161,7 @@ class SessionRepository:
135
 
136
  def review_repository(self,identifier):
137
  current=self.current()
138
- if self.cloud_config and STAFF_TOKEN.get() and current.raw(identifier) is None:
139
  return self.local()
140
  return current
141
 
@@ -148,5 +174,36 @@ class SessionRepository:
148
  def review_notes(self,identifier):
149
  return self.review_repository(identifier).review_notes(identifier)
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  def __getattr__(self, name):
152
  return getattr(self.current(), name)
 
13
 
14
  NAMESPACE = ContextVar('defectrag_namespace', default=None)
15
  STAFF_TOKEN = ContextVar('defectrag_staff_token', default='')
16
+ WORKSPACE = ContextVar('defectrag_workspace', default='personal')
17
  SIGNING_KEY = os.environ.get('DEFECTRAG_SIGNING_KEY', '').encode() or os.urandom(32)
18
  _staff_sessions={}
19
  _session_lock=threading.Lock()
 
46
 
47
 
48
  @contextmanager
49
+ def identity(session, token='', workspace='personal'):
50
+ if workspace not in ('personal','team'):raise ValueError('Invalid workspace')
51
  owner=namespace(session)
52
  remember_staff(owner,token)
53
  marker = NAMESPACE.set(owner)
54
  staff = STAFF_TOKEN.set(token)
55
+ scope = WORKSPACE.set(workspace)
56
  try:
57
  yield
58
  finally:
59
+ WORKSPACE.reset(scope)
60
  STAFF_TOKEN.reset(staff)
61
  NAMESPACE.reset(marker)
62
 
63
 
64
  def capability(identifier, kind):
65
+ text = f'{NAMESPACE.get()}:{WORKSPACE.get()}:{identifier}:{kind}:{int(time.time())+3600}'
66
  signature = hmac.new(SIGNING_KEY, text.encode(), 'sha256').hexdigest()
67
  return base64.urlsafe_b64encode(f'{text}:{signature}'.encode()).decode().rstrip('=')
68
 
 
70
  def authorize_artifact(access, identifier, kind):
71
  try:
72
  raw = base64.urlsafe_b64decode(access+'='*(-len(access)%4)).decode()
73
+ owner, scope, actual_id, actual_kind, expires, signature = raw.split(':')
74
+ text = ':'.join((owner, scope, actual_id, actual_kind, expires))
75
  if (not re.fullmatch('[a-f0-9]{64}', owner) or actual_id != identifier or actual_kind != kind
76
+ or scope not in ('personal','team')
77
  or int(expires) < time.time() or not hmac.compare_digest(signature,
78
  hmac.new(SIGNING_KEY, text.encode(), 'sha256').hexdigest())):
79
  raise ValueError()
 
82
  raise ValueError('Image or report access expired. Reopen the saved inspection.') from None
83
 
84
 
85
+ def artifact_workspace(access):
86
+ # Call only AFTER authorize_artifact validates the signed scope.
87
+ return base64.urlsafe_b64decode(access+'='*(-len(access)%4)).decode().split(':')[1]
88
+
89
+
90
  class SessionRepository:
91
+ def __init__(self, directory, cloud_config=None, artifacts=None, personal_enabled=False):
92
  self.directory = Path(directory)
93
  self.cloud_config=cloud_config
94
  self.artifacts=artifacts
95
+ self.personal_enabled=personal_enabled
96
 
97
  def current(self):
98
  owner = NAMESPACE.get()
 
100
  raise ValueError('Workspace authorization is missing')
101
  if self.cloud_config and STAFF_TOKEN.get():
102
  from deployment.space.supabase_repository import StaffRepository
103
+ if self.personal_enabled and WORKSPACE.get()=='personal':
104
+ from deployment.space.personal_repository import PersonalRepository
105
+ return PersonalRepository(self.cloud_config,STAFF_TOKEN.get(),self.artifacts)
106
+ current=StaffRepository(self.cloud_config,STAFF_TOKEN.get(),self.artifacts)
107
+ current.workspace_stats_enabled=self.personal_enabled
108
+ return current
109
+ if self.personal_enabled and WORKSPACE.get()=='team':
110
+ raise ValueError('Sign in with an approved staff account for Team workspace.')
111
  return SQLiteRepository(self.directory / owner / 'inspection.sqlite3')
112
 
113
  def local(self):
 
119
  result = dict(record)
120
  result.setdefault('storage','browser_session')
121
  for kind in ('image', 'heatmap', 'report'):
122
+ if kind!='report' and result.get('storage','').startswith('supabase') and result.get(kind+'_url','').startswith('https://'):
123
  continue
124
  result[kind+'_url'] = f"/api/inspections/{record['id']}/{kind}?access={capability(record['id'], kind)}"
125
  return result
 
127
  def save(self, record):
128
  return self.decorate(self.current().save(record))
129
 
130
+ def guest_fallback(self,current,identifier):
131
+ if not self.cloud_config or not STAFF_TOKEN.get():return False
132
+ if self.personal_enabled and WORKSPACE.get()!='personal':return False
133
+ if current.raw(identifier) is not None:return False
134
+ # An archived cloud record must not reappear through its old guest copy.
135
+ if self.personal_enabled and hasattr(current,'_raw_any') and current._raw_any(identifier) is not None:return False
136
+ return True
137
+
138
  def get(self, identifier):
139
  current=self.current()
140
  record=current.get(identifier)
141
  # Signing in must not invalidate this browser's earlier anonymous upload
142
  # before its explicit Share with staff operation has copied it durably.
143
+ if record is None and self.guest_fallback(current,identifier):
144
  record=self.local().get(identifier)
145
  return self.decorate(record)
146
 
147
  def messages(self,identifier):
148
  current=self.current()
149
+ if self.guest_fallback(current,identifier):
150
  return self.local().messages(identifier)
151
  return current.messages(identifier)
152
 
153
  def add_conversation(self,identifier,question,answer):
154
  current=self.current()
155
+ if self.guest_fallback(current,identifier):
156
  return self.local().add_conversation(identifier,question,answer)
157
  return current.add_conversation(identifier,question,answer)
158
 
 
161
 
162
  def review_repository(self,identifier):
163
  current=self.current()
164
+ if self.guest_fallback(current,identifier):
165
  return self.local()
166
  return current
167
 
 
174
  def review_notes(self,identifier):
175
  return self.review_repository(identifier).review_notes(identifier)
176
 
177
+ def status(self):
178
+ current=self.current()
179
+ staff=getattr(current,'staff',None)
180
+ return {'personal_enabled':self.personal_enabled,'workspace':WORKSPACE.get() if self.personal_enabled else 'team' if staff else 'guest',
181
+ 'authenticated':bool(staff),'role':staff.get('role') if staff else None,
182
+ 'storage':'supabase' if staff else 'temporary_browser','poll_seconds':15}
183
+
184
+ def share(self,identifier,include_conversation=False,personal_only=False):
185
+ if not self.personal_enabled or not self.cloud_config or not STAFF_TOKEN.get():
186
+ raise ValueError('Sign in to the configured Personal workspace before saving or sharing.')
187
+ from deployment.space.personal_repository import PersonalRepository
188
+ personal=PersonalRepository(self.cloud_config,STAFF_TOKEN.get(),self.artifacts)
189
+ if personal.raw(identifier) is None:
190
+ guest=self.local().get(identifier)
191
+ if guest is None:
192
+ raise ValueError('An owned personal inspection or this browser’s guest inspection is required.')
193
+ personal.save(guest,conversation=self.local().messages(identifier))
194
+ # Retain guest review provenance as imported notes, never pretend a guest
195
+ # decision was a newly authenticated human decision. Stable IDs make a
196
+ # retry after a partial import append-safe. These notes are NOT team-shared.
197
+ if self.local().get(identifier):
198
+ import json
199
+ import uuid
200
+ for review in self.local().review_history(identifier):
201
+ note_id=str(uuid.uuid5(uuid.NAMESPACE_URL,personal.user['id']+':'+identifier+':'+review['created_at']))
202
+ body='Imported guest review (original identity unverified): '+json.dumps(review,ensure_ascii=False)
203
+ personal.request('POST','/rest/v1/personal_notes',json={'id':note_id,'inspection_id':identifier,
204
+ 'author_id':personal.user['id'],'body':body[:2000]},ignore_conflict=True)
205
+ if personal_only:return {'saved':True}
206
+ return personal.share(identifier,include_conversation)
207
+
208
  def __getattr__(self, name):
209
  return getattr(self.current(), name)
deployment/space/supabase_repository.py CHANGED
@@ -25,6 +25,12 @@ def read_public_config(path):
25
 
26
 
27
  class StaffRepository:
 
 
 
 
 
 
28
  def __init__(self,config,token,artifacts):
29
  self.config,self.token,self.artifacts=config,token,Path(artifacts)
30
  self.headers={'apikey':config['key'],'Authorization':'Bearer '+token}
@@ -46,15 +52,21 @@ class StaffRepository:
46
  _staff_cache[token]=(time.time()+45,self.user,self.staff)
47
 
48
  def request(self,method,path,**kwargs):
 
49
  headers={**self.headers,**kwargs.pop('headers',{})}
50
- with httpx.Client(timeout=30,trust_env=False) as client:
51
- response=client.request(method,self.config['url']+path,headers=headers,**kwargs)
 
 
 
52
  if not response.is_success:
53
  try:
54
  detail=response.json()
55
  code=detail.get('code',detail.get('error','unknown'))
56
  except (ValueError,AttributeError):
57
  code='unexpected_response'
 
 
58
  if response.status_code in (401,403):
59
  raise ValueError('Staff session expired or access denied. Sign in again.')
60
  if code in ('PGRST202','PGRST205'):
@@ -66,16 +78,17 @@ class StaffRepository:
66
  if not row:
67
  return None
68
  record=dict(row['payload'])
69
- record['storage']='supabase'
 
70
  record['owner_id']=row['owner_id']
71
  for kind in ('image','heatmap'):
72
- result=self.request('POST','/storage/v1/object/sign/team-inspections/'+quote(row[kind+'_path'],safe='/'),json={'expiresIn':600})
73
  signed=result.get('signedURL',result.get('signedUrl'))
74
  record[kind+'_url']=signed if signed.startswith('https://') else self.config['url']+'/storage/v1'+signed
75
  return record
76
 
77
  def raw(self,identifier,archived=False):
78
- rows=self.request('GET','/rest/v1/shared_inspections',params={'id':'eq.'+identifier,'select':'*','limit':'1',
79
  'archived_at':'not.is.null' if archived else 'is.null'})
80
  return rows[0] if rows else None
81
 
@@ -102,7 +115,7 @@ class StaffRepository:
102
  for key,value in (('category',category),('verdict',verdict),('batch',batch)):
103
  if value:
104
  params['payload->>'+key]='eq.'+value
105
- return self.request('GET','/rest/v1/shared_inspections',params=params)
106
 
107
  def list(self,category='',verdict='',batch='',limit=100,offset=0,archived=False):
108
  # Lists need no images until a record is opened. Avoid two storage API
@@ -114,9 +127,11 @@ class StaffRepository:
114
  rows.extend(page)
115
  if len(page)<count:
116
  break
117
- return [{**row['payload'],'storage':'supabase','owner_id':row['owner_id']} for row in rows]
118
 
119
  def stats(self):
 
 
120
  rows=self.list(limit=1000)
121
  counts={kind:sum(row['verdict']==kind for row in rows) for kind in ('Good','Anomalous','Uncertain')}
122
  batches={}
@@ -158,14 +173,14 @@ class StaffRepository:
158
  def add_review(self,identifier,status,decision,note=''):
159
  from backend.reviews import review_body,validate_review
160
  body=review_body(status,decision,note)
161
- rows=self.request('POST','/rest/v1/staff_notes',json={
162
  'inspection_id':identifier,'author_id':self.user['id'],'body':body},
163
  headers={'Prefer':'return=representation'})
164
  return {**validate_review(status,decision,note),'reviewer':self.staff['display_name'],
165
  'reviewer_id':self.user['id'],'created_at':rows[0]['created_at']}
166
 
167
  def review_notes(self,identifier):
168
- rows=self.request('GET','/rest/v1/staff_notes',params={
169
  'inspection_id':'eq.'+identifier,'select':'body,author_id,created_at','order':'created_at.asc'})
170
  people=self.request('GET','/rest/v1/staff_members',params={'select':'user_id,display_name'})
171
  directory={row['user_id']:row['display_name'] for row in people}
 
25
 
26
 
27
  class StaffRepository:
28
+ table='shared_inspections'
29
+ bucket='team-inspections'
30
+ notes_table='staff_notes'
31
+ storage_type='supabase'
32
+ workspace='team'
33
+ workspace_stats_enabled=False
34
  def __init__(self,config,token,artifacts):
35
  self.config,self.token,self.artifacts=config,token,Path(artifacts)
36
  self.headers={'apikey':config['key'],'Authorization':'Bearer '+token}
 
52
  _staff_cache[token]=(time.time()+45,self.user,self.staff)
53
 
54
  def request(self,method,path,**kwargs):
55
+ ignore_conflict=kwargs.pop('ignore_conflict',False)
56
  headers={**self.headers,**kwargs.pop('headers',{})}
57
+ try:
58
+ with httpx.Client(timeout=30,trust_env=False) as client:
59
+ response=client.request(method,self.config['url']+path,headers=headers,**kwargs)
60
+ except httpx.HTTPError:
61
+ raise RuntimeError('Cloud request did not complete. Retry the same submission to verify whether it was saved.') from None
62
  if not response.is_success:
63
  try:
64
  detail=response.json()
65
  code=detail.get('code',detail.get('error','unknown'))
66
  except (ValueError,AttributeError):
67
  code='unexpected_response'
68
+ if ignore_conflict and response.status_code in (400,409) and code in ('23505','Duplicate','ResourceAlreadyExists','KeyAlreadyExists'):
69
+ return None
70
  if response.status_code in (401,403):
71
  raise ValueError('Staff session expired or access denied. Sign in again.')
72
  if code in ('PGRST202','PGRST205'):
 
78
  if not row:
79
  return None
80
  record=dict(row['payload'])
81
+ record['storage']=self.storage_type
82
+ record['workspace']=self.workspace
83
  record['owner_id']=row['owner_id']
84
  for kind in ('image','heatmap'):
85
+ result=self.request('POST','/storage/v1/object/sign/'+self.bucket+'/'+quote(row[kind+'_path'],safe='/'),json={'expiresIn':600})
86
  signed=result.get('signedURL',result.get('signedUrl'))
87
  record[kind+'_url']=signed if signed.startswith('https://') else self.config['url']+'/storage/v1'+signed
88
  return record
89
 
90
  def raw(self,identifier,archived=False):
91
+ rows=self.request('GET','/rest/v1/'+self.table,params={'id':'eq.'+identifier,'select':'*','limit':'1',
92
  'archived_at':'not.is.null' if archived else 'is.null'})
93
  return rows[0] if rows else None
94
 
 
115
  for key,value in (('category',category),('verdict',verdict),('batch',batch)):
116
  if value:
117
  params['payload->>'+key]='eq.'+value
118
+ return self.request('GET','/rest/v1/'+self.table,params=params)
119
 
120
  def list(self,category='',verdict='',batch='',limit=100,offset=0,archived=False):
121
  # Lists need no images until a record is opened. Avoid two storage API
 
127
  rows.extend(page)
128
  if len(page)<count:
129
  break
130
+ return [{**row['payload'],'storage':self.storage_type,'workspace':self.workspace,'owner_id':row['owner_id']} for row in rows]
131
 
132
  def stats(self):
133
+ if self.workspace_stats_enabled:
134
+ return self.request('POST','/rest/v1/rpc/defectrag_workspace_stats',json={'p_scope':self.workspace})
135
  rows=self.list(limit=1000)
136
  counts={kind:sum(row['verdict']==kind for row in rows) for kind in ('Good','Anomalous','Uncertain')}
137
  batches={}
 
173
  def add_review(self,identifier,status,decision,note=''):
174
  from backend.reviews import review_body,validate_review
175
  body=review_body(status,decision,note)
176
+ rows=self.request('POST','/rest/v1/'+self.notes_table,json={
177
  'inspection_id':identifier,'author_id':self.user['id'],'body':body},
178
  headers={'Prefer':'return=representation'})
179
  return {**validate_review(status,decision,note),'reviewer':self.staff['display_name'],
180
  'reviewer_id':self.user['id'],'created_at':rows[0]['created_at']}
181
 
182
  def review_notes(self,identifier):
183
+ rows=self.request('GET','/rest/v1/'+self.notes_table,params={
184
  'inspection_id':'eq.'+identifier,'select':'body,author_id,created_at','order':'created_at.asc'})
185
  people=self.request('GET','/rest/v1/staff_members',params={'select':'user_id,display_name'})
186
  directory={row['user_id']:row['display_name'] for row in people}
frontend/dist/assets/TeamWorkspace-DxIB_iKo.js ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import{c as v,r as n,a as he,b as u,s as fe,R as e,L as Ee,S as ye,A as ve,d as we,e as ge,w as z,p as se,f as be}from"./index-Bi4p7Ozq.js";/**
2
+ * @license lucide-react v0.468.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const Se=v("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);/**
7
+ * @license lucide-react v0.468.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const V=v("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/**
12
+ * @license lucide-react v0.468.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const ke=v("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
17
+ * @license lucide-react v0.468.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const Ne=v("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/**
22
+ * @license lucide-react v0.468.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const _e=v("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
27
+ * @license lucide-react v0.468.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const Ce=v("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
32
+ * @license lucide-react v0.468.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const Re=v("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/**
37
+ * @license lucide-react v0.468.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const Ae=v("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Me({onOpenInspection:G}){var re;const d=n.useRef(0),K=n.useRef(null),k=n.useRef(0),U=n.useRef(null),D=n.useRef(0),[R,le]=n.useState({state:"refreshing"}),[o,Y]=n.useState(null),[c,O]=n.useState(null),[N,T]=n.useState([]),[_,ce]=n.useState({}),[A,oe]=n.useState(""),[Z,J]=n.useState(""),[m,Q]=n.useState(!1),[X,S]=n.useState(""),[w,ie]=n.useState(!1),[s,h]=n.useState(null),[de,x]=n.useState([]),[I,M]=n.useState([]),[j,$]=n.useState(""),[me,ee]=n.useState(!1),[te,ae]=n.useState(""),[ue,F]=n.useState(!1);n.useEffect(()=>{U.current=s},[s]);const H=he();async function p(t){Q(!0),S("");try{await t()}catch(a){S(a.message||"Team request failed.")}finally{Q(!1)}}async function q(){var ne;const t=++k.current,a=d.current,r=(ne=U.current)==null?void 0:ne.id,{client:i,staff:f}=await be();let l=i.from("shared_inspections").select("*").order("created_at",{ascending:!1}).limit(200);l=w?l.not("archived_at","is",null):l.is("archived_at",null);const[{data:g,error:E},{data:L,error:y},W]=await Promise.all([l,i.from("staff_members").select("*"),r?i.from("staff_notes").select("*").eq("inspection_id",r).order("created_at"):{data:[]}]);if(E)throw E;if(y)throw y;if(W.error)throw W.error;if(t===k.current&&(O(f),S(""),T(g||[]),ce(Object.fromEntries((L||[]).map(b=>[b.user_id,b.display_name]))),r&&a===d.current)){const b=(g||[]).find(P=>P.id===r);if(!b)d.current++,h(null),x([]),M([]);else if(h(b),M(W.data||[]),Date.now()-D.current>480*1e3){const P=await Promise.all([b.image_path,b.heatmap_path].map(C=>i.storage.from("team-inspections").createSignedUrl(C,900)));if(t===k.current&&a===d.current){if(P.some(C=>C.error))throw new Error("Shared image links could not refresh.");x(P.map(C=>C.data.signedUrl)),D.current=Date.now()}}}}n.useEffect(()=>{if(!H)return;let t=!1,a;return u().then(async r=>{a=r.auth.onAuthStateChange((f,l)=>{var g;if(!t){const E=((g=l==null?void 0:l.user)==null?void 0:g.id)||null;K.current!==E&&(d.current++,k.current++,h(null),T([]),x([]),M([]),O(null),K.current=E),Y((l==null?void 0:l.user)||null),f==="PASSWORD_RECOVERY"&&ee(!0)}}).data.subscription;const{data:i}=await r.auth.getUser();t||Y(i.user)}).catch(r=>{t||S(r.message)}),()=>{t=!0,d.current++,a==null||a.unsubscribe()}},[H]),n.useEffect(()=>{if(!o)return;const t=fe(q,{onState:a=>{le(a),a.error&&S(a.error)}});return()=>{t.stop(),k.current++}},[o==null?void 0:o.id,w]);async function B(t){const a=++d.current;await p(async()=>{const r=await u(),i=r.storage.from("team-inspections"),[{data:f,error:l},{data:g,error:E}]=await Promise.all([r.from("shared_inspections").select("*").eq("id",t.id).single(),r.from("staff_notes").select("*").eq("inspection_id",t.id).order("created_at")]);if(l)throw l;if(E)throw E;const L=await Promise.all([f.image_path,f.heatmap_path].map(y=>i.createSignedUrl(y,900)));if(L.some(y=>y.error))throw new Error("Private images could not be loaded. Check staff/storage policies.");a===d.current&&(U.current=f,D.current=Date.now(),h(f),x(L.map(y=>y.data.signedUrl)),M(g||[]))})}async function pe(){await p(async()=>{const t=await u(),a=N.filter(r=>r.owner_id===o.id).map(r=>r.id);if(a.length){const{error:r}=await t.rpc("archive_team_inspections",{p_ids:a});if(r)throw r}d.current++,h(null),F(!1),await q(),z()})}return H?e.createElement(e.Fragment,null,e.createElement("section",{className:"card"},e.createElement("div",{className:"section-title"},e.createElement("div",null,e.createElement("h2",null,e.createElement(Ae,{size:21})," Staff workspace"),e.createElement("p",null,"Signed-in staff share saved inspections and review notes. Live AI runs on the connected inspection backend.")),e.createElement("span",{className:"subtle-tag"},e.createElement(V,{size:13})," SUPABASE")),X&&e.createElement("div",{className:"error",role:"alert"},X),o?e.createElement(e.Fragment,null,e.createElement("div",{className:"team-toolbar"},e.createElement("div",null,e.createElement(ye,{size:18}),e.createElement("strong",null,(c==null?void 0:c.display_name)||o.email),e.createElement("span",{className:"subtle-tag"},(c==null?void 0:c.role)||"CHECKING MEMBERSHIP")),e.createElement("button",{className:"secondary",disabled:m,onClick:()=>p(q)},e.createElement(Ce,{size:16})," Refresh"),e.createElement("button",{className:"secondary",onClick:()=>p(async()=>{await(await u()).auth.signOut(),T([]),h(null),O(null)})},e.createElement(_e,{size:16})," Sign out")),me&&e.createElement("form",{className:"login-form",onSubmit:t=>{t.preventDefault(),p(async()=>{const a=await u(),{error:r}=await a.auth.updateUser({password:te});if(r)throw r;ae(""),ee(!1)})}},e.createElement("label",{className:"field"},"Set a new password",e.createElement("input",{type:"password",minLength:12,autoComplete:"new-password",value:te,onChange:t=>ae(t.target.value),required:!0})),e.createElement("button",{className:"primary",disabled:m},"Save password")),e.createElement("div",{className:"team-toolbar"},e.createElement("span",{role:"status"},"Team Workspace · latest ",N.length," shared records · ",R.state==="synced"?"synchronized at "+new Date(R.at).toLocaleTimeString():R.state==="offline"?"offline; data may be stale":R.state==="stale"?"synchronization failed; data may be stale":"refreshing…"," · polls every 15 seconds"),(c==null?void 0:c.role)==="developer"&&e.createElement("button",{className:"secondary",onClick:()=>{ie(!w),h(null)}},e.createElement(Se,{size:16}),w?"Active history":"Developer recovery"),!w&&e.createElement("button",{className:"secondary danger",disabled:m||!N.some(t=>t.owner_id===o.id),onClick:()=>F(!0)},e.createElement(ve,{size:16})," Archive my visible history")),ue&&e.createElement("div",{className:"note"},e.createElement("div",null,e.createElement("strong",null,"Archive your visible records?"),e.createElement("p",null,"They will leave the shared active history. Original files and conversations remain recoverable by a developer. Other staff members’ records will stay active."),e.createElement("div",{className:"button-row"},e.createElement("button",{className:"primary",disabled:m,onClick:pe},"Archive my records"),e.createElement("button",{className:"secondary",onClick:()=>F(!1)},"Cancel")))),e.createElement("div",{className:"table-wrap"},e.createElement("table",null,e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Inspection"),e.createElement("th",null,"Product"),e.createElement("th",null,"Result"),e.createElement("th",null,"Shared by"),e.createElement("th",null,"Saved"),e.createElement("th",null))),e.createElement("tbody",null,N.map(t=>{var a;return e.createElement("tr",{key:t.id},e.createElement("td",null,e.createElement("strong",null,t.id.slice(0,8))),e.createElement("td",null,t.payload.category),e.createElement("td",null,e.createElement("span",{className:"badge "+((a=t.payload.verdict)==null?void 0:a.toLowerCase())},t.payload.verdict)),e.createElement("td",null,_[t.owner_id]||"Staff member"),e.createElement("td",null,new Date(t.created_at).toLocaleString()),e.createElement("td",null,e.createElement("button",{className:"text-button",onClick:()=>B(t)},"Review"),w&&(c==null?void 0:c.role)==="developer"&&e.createElement("button",{className:"text-button",disabled:m,onClick:()=>p(async()=>{const r=await u(),{error:i}=await r.rpc("restore_team_inspections",{p_ids:[t.id]});if(i)throw i;await q(),z()})},"Restore")))}))),!N.length&&e.createElement("div",{className:"empty"},e.createElement(V,{size:30}),e.createElement("p",null,w?"No archived records to recover.":"No shared inspections yet. Open an inspection result and select Share with staff.")))):e.createElement("form",{className:"login-form",onSubmit:t=>{t.preventDefault(),p(async()=>{const a=await u(),{error:r}=await a.auth.signInWithPassword({email:A,password:Z});if(r)throw r;J("")})}},e.createElement("label",{className:"field"},"Work email",e.createElement("input",{type:"email",autoComplete:"username",value:A,onChange:t=>oe(t.target.value),required:!0})),e.createElement("label",{className:"field"},"Password",e.createElement("input",{type:"password",autoComplete:"current-password",value:Z,onChange:t=>J(t.target.value),required:!0})),e.createElement("button",{className:"primary",disabled:m},m?e.createElement(Ee,{className:"spin",size:17}):e.createElement(Ne,{size:17})," Sign in"),e.createElement("button",{type:"button",className:"text-button",disabled:!A||m,onClick:()=>p(async()=>{const t=await u(),{error:a}=await t.auth.resetPasswordForEmail(A,{redirectTo:location.origin+location.pathname});if(a)throw a;S("Password reset requested. Check your email.")})},"Reset password"),e.createElement("p",{className:"caption"},"Accounts must be invited and approved by your workspace developer. Signing up alone does not grant staff access."))),o&&s&&e.createElement("section",{className:"card"},e.createElement("div",{className:"section-title"},e.createElement("div",null,e.createElement("h2",null,"Shared inspection · ",s.id.slice(0,8)),e.createElement("p",null,"Saved snapshot from ",_[s.owner_id]||"a colleague",". This page does not run a new prediction.")),e.createElement("div",{className:"button-row"},G&&!s.archived_at&&e.createElement("button",{className:"secondary",onClick:()=>G(s)},"Open inspection & assistant"),e.createElement("button",{className:"text-button",onClick:()=>{d.current++,h(null)}},"Close"))),e.createElement("div",{className:"shared-images"},de.map((t,a)=>e.createElement("img",{key:t,src:t,alt:a?"Saved anomaly heatmap":"Saved inspected product"}))),e.createElement("div",{className:"observation"},e.createElement("strong",null,"SAVED MEASUREMENTS"),e.createElement("span",null,s.payload.verdict," · score ",Number(s.payload.score).toFixed(5)," · threshold ",Number(s.payload.threshold).toFixed(5))),e.createElement("h3",{className:"section-gap"},"Recorded evidence"),(re=s.conversation)!=null&&re.length?s.conversation.map((t,a)=>e.createElement("p",{className:"cloud-message",key:a},e.createElement("strong",null,t.role==="user"?"Inspector":"Evidence Assistant",": "),t.question||t.answer)):e.createElement("p",{className:"caption"},"No conversation was included when this inspection was shared."),!s.archived_at&&e.createElement(we,{key:s.id+String(I.length),current:I.map(t=>se(t,_)).filter(Boolean).at(-1),disabled:m,onSave:async t=>{const a=await u(),{error:r}=await a.from("staff_notes").insert({inspection_id:s.id,author_id:o.id,body:ge(t.status,t.decision,t.note)});if(r)throw r;await B(s),z()}}),e.createElement("h3",{className:"section-gap"},"Staff review notes"),I.filter(t=>!se(t,_)).map(t=>e.createElement("div",{className:"cloud-message",key:t.id},e.createElement("strong",null,_[t.author_id]||"Staff member"),e.createElement("p",null,t.body),e.createElement("small",null,new Date(t.created_at).toLocaleString()))),!s.archived_at&&e.createElement("form",{className:"question-form",onSubmit:t=>{t.preventDefault(),p(async()=>{const a=await u(),{error:r}=await a.from("staff_notes").insert({inspection_id:s.id,author_id:o.id,body:j.trim()});if(r)throw r;$(""),await B(s),z()})}},e.createElement("input",{"aria-label":"Staff review note",maxLength:2e3,placeholder:"Add a review note for your colleagues…",value:j,onChange:t=>$(t.target.value)}),e.createElement("button",{className:"primary",disabled:m||!j.trim()},e.createElement(Re,{size:16})," Add note")))):e.createElement("section",{className:"card cloud-setup"},e.createElement("div",{className:"setup-icon"},e.createElement(V,{size:32})),e.createElement("span",{className:"eyebrow"},"TEAM WORKSPACE"),e.createElement("h2",null,"One shared view of inspection."),e.createElement("p",null,"The staff workspace is ready to connect to your own Supabase project. No cloud project or account has been created for you."),e.createElement("div",{className:"setup-grid"},[["01","Create a free project","Use your Supabase account and select an eligible Free plan."],["02","Set up staff access","Run the supplied schema, add your developer account and invite colleagues."],["03","Connect this dashboard","Add the project URL and publishable key to config.js, then reload."]].map(([t,a,r])=>e.createElement("div",{key:t},e.createElement("b",null,t),e.createElement("h3",null,a),e.createElement("p",null,r)))),e.createElement("a",{className:"primary",href:"https://supabase.com/dashboard",target:"_blank",rel:"noreferrer"},"Open Supabase ",e.createElement(ke,{size:16})),e.createElement("p",{className:"caption"},"Setup files: deployment/SUPABASE_SETUP.md and deployment/supabase.sql. Never place a service-role key in the browser. Local inspection works without cloud setup."))}export{Me as default};
frontend/dist/assets/index-Bi4p7Ozq.js ADDED
The diff for this file is too large to render. See raw diff
 
frontend/dist/index.html CHANGED
@@ -1,3 +1,3 @@
1
- <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/><meta name="theme-color" content="#132e32"/><meta name="description" content="Local visual anomaly inspection with traceable evidence."/><title>DefectRAG · Inspection intelligence</title><link rel="icon" type="image/svg+xml" href="./logo.svg"><script src="./config.js"></script> <script type="module" crossorigin src="./assets/index-pHIVzc7G.js"></script>
2
  <link rel="stylesheet" crossorigin href="./assets/index-Bn4HF2vD.css">
3
  </head><body><div id="root"></div></body></html>
 
1
+ <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/><meta name="theme-color" content="#132e32"/><meta name="description" content="Local visual anomaly inspection with traceable evidence."/><title>DefectRAG · Inspection intelligence</title><link rel="icon" type="image/svg+xml" href="./logo.svg"><script src="./config.js"></script> <script type="module" crossorigin src="./assets/index-Bi4p7Ozq.js"></script>
2
  <link rel="stylesheet" crossorigin href="./assets/index-Bn4HF2vD.css">
3
  </head><body><div id="root"></div></body></html>