Tengo Gzirishvili Claude Opus 4.8 commited on
Commit
1ee54b6
Β·
1 Parent(s): 29f4874

Unified "My designs" hub: save every tool, not just CRISPR

Browse files

"My designs" was CRISPR-only; plasmids lived in a separate list and primer/
evolution results couldn't be saved. Now it's one hub with a section per tool.

Backend:
- migration 0006_primer_analyses.sql (user runs it) β€” per-user table mirroring
crispr_designs (owner-only RLS, 90-day expires_at).
- auth.py: save/list/get/delete_primer_analysis (+ lazy cleanup); list_libraries
and library_csv_url (signed, owner-checked) reusing the existing public.libraries
+ Storage bucket from DE auto-save.
- server.py: /api/primers/{save,analyses,analyses/<id> GET+DELETE} and per-user
/api/library + /api/library/<id>/download β€” all sign-in gated + owner-guarded.

Frontend:
- New #savedModal unified hub (Plasmids Β· CRISPR Β· Primer sets Β· Evolution
libraries); each tool registers a reopen fn on window.TDSaved. navMyDesigns,
the CRISPR "My designs" button, and the Plasmid "My plasmids" button all open it.
- Primer Analysis gains a Save button; evolution libraries list with Download CSV
(signed URL) β€” full variant re-render deferred per plan.
- Reopen routes to the tool's view then rehydrates (CRISPR _loadDesign, plasmid
openSaved, primer render). Sections lazy-load in parallel; 403 β†’ sign-in modal.

Verified: 10 endpoint checks (Flask test client, auth/DB stubbed) + live preview
(all four sections render, reopen routes correctly, mobile reflow, zero console
errors). tests/test_primer_save.py added for the pytest suite. Bump cache-busters
to v=20260605-saved.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

dee/auth.py CHANGED
@@ -1165,6 +1165,228 @@ def _do_cleanup_expired_plasmids(user_id: str) -> None:
1165
  logger.warning("plasmids cleanup failed for %s: %s", user_id, exc)
1166
 
1167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1168
  def _anon_fingerprint() -> str:
1169
  """Stable-ish hash of IP + UA, salted with ANON_SECRET. Used only to
1170
  rough-deduplicate anonymous runs in analytics. Not identity-grade β€”
 
1165
  logger.warning("plasmids cleanup failed for %s: %s", user_id, exc)
1166
 
1167
 
1168
+ # ─── Primer Analysis: per-user saved sets (unified "My designs" hub) ──
1169
+ # Mirrors the crispr_designs CRUD. Table: public.primer_analyses
1170
+ # (migration 0006). The full analyze result is stored as JSONB so a saved
1171
+ # set re-renders without re-running the in-silico PCR.
1172
+
1173
+ _PRIMER_ANALYSES_LIST_LIMIT = 100 # max sets returned by the list call
1174
+ _PRIMER_RESULT_MAX_BYTES = 600_000 # cap the stored result JSON (~0.6 MB)
1175
+
1176
+
1177
+ def save_primer_analysis(
1178
+ user_id: Optional[str], *,
1179
+ label: str, organism: Optional[str],
1180
+ template_len: Optional[int], n_primers: Optional[int],
1181
+ result: Dict[str, Any],
1182
+ ) -> Dict[str, Any]:
1183
+ """Insert a saved primer set. Returns {ok, id} or {ok:False, error}."""
1184
+ if not user_id:
1185
+ return {"ok": False, "error": "Sign in to save primer sets."}
1186
+ if not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
1187
+ return {"ok": False, "error": "Saving isn't configured on this server."}
1188
+ # Guard against an oversized result blob (a runaway off-target product
1189
+ # list): keep the ranked primers, drop the bulk.
1190
+ try:
1191
+ if len(json.dumps(result or {})) > _PRIMER_RESULT_MAX_BYTES:
1192
+ result = {"primers": (result or {}).get("primers", [])}
1193
+ except Exception: # noqa: BLE001
1194
+ result = {}
1195
+ from datetime import datetime, timezone, timedelta
1196
+ expires_at = (None if has_pro_plan(user_id) else
1197
+ (datetime.now(timezone.utc) + timedelta(days=FREE_LIBRARY_TTL_DAYS)).isoformat())
1198
+ payload = {
1199
+ "user_id": user_id,
1200
+ "label": (label or "Untitled primer set")[:120],
1201
+ "organism": organism or None,
1202
+ "template_len": template_len,
1203
+ "n_primers": n_primers,
1204
+ "result": result or {},
1205
+ "expires_at": expires_at,
1206
+ }
1207
+ import urllib.request
1208
+ import urllib.error
1209
+ try:
1210
+ req = urllib.request.Request(
1211
+ f"{SUPABASE_URL}/rest/v1/primer_analyses",
1212
+ data=json.dumps(payload).encode("utf-8"),
1213
+ method="POST",
1214
+ headers=_supabase_headers({"Content-Type": "application/json",
1215
+ "Prefer": "return=representation"}),
1216
+ )
1217
+ with urllib.request.urlopen(req, timeout=8.0) as resp:
1218
+ rows = json.loads(resp.read().decode("utf-8"))
1219
+ new_id = (rows[0] or {}).get("id") if isinstance(rows, list) and rows else None
1220
+ return {"ok": True, "id": new_id}
1221
+ except urllib.error.HTTPError as exc:
1222
+ body = ""
1223
+ try:
1224
+ body = exc.read().decode("utf-8")[:200]
1225
+ except Exception: # noqa: BLE001
1226
+ pass
1227
+ logger.warning("primer_analyses insert HTTP %s: %s", exc.code, body)
1228
+ if exc.code in (404, 406) or "PGRST" in body:
1229
+ return {"ok": False, "error": "Saved primer sets aren't enabled yet (database migration pending)."}
1230
+ return {"ok": False, "error": "Couldn't save the primer set. Please try again."}
1231
+ except Exception as exc: # noqa: BLE001
1232
+ logger.warning("primer_analyses insert failed: %s", exc)
1233
+ return {"ok": False, "error": "Couldn't save the primer set. Please try again."}
1234
+
1235
+
1236
+ def list_primer_analyses(user_id: Optional[str]) -> list:
1237
+ """The user's saved primer sets (metadata only, newest first). [] on error."""
1238
+ if not user_id or not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
1239
+ return []
1240
+ import urllib.request
1241
+ try:
1242
+ url = (f"{SUPABASE_URL}/rest/v1/primer_analyses"
1243
+ f"?user_id=eq.{user_id}"
1244
+ f"&select=id,label,created_at,expires_at,organism,template_len,n_primers"
1245
+ f"&order=created_at.desc&limit={_PRIMER_ANALYSES_LIST_LIMIT}")
1246
+ req = urllib.request.Request(url, method="GET", headers=_supabase_headers())
1247
+ with urllib.request.urlopen(req, timeout=6.0) as resp:
1248
+ return json.loads(resp.read().decode("utf-8")) or []
1249
+ except Exception as exc: # noqa: BLE001
1250
+ logger.warning("primer_analyses list failed for %s: %s", user_id, exc)
1251
+ return []
1252
+
1253
+
1254
+ def get_primer_analysis(user_id: Optional[str], analysis_id: str) -> Optional[Dict[str, Any]]:
1255
+ """One full saved primer set incl. result, enforcing ownership server-side."""
1256
+ import re as _re
1257
+ if not user_id or not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
1258
+ return None
1259
+ if not _re.match(r"^[0-9a-fA-F-]{36}$", analysis_id or ""):
1260
+ return None
1261
+ import urllib.request
1262
+ try:
1263
+ url = (f"{SUPABASE_URL}/rest/v1/primer_analyses"
1264
+ f"?id=eq.{analysis_id}&user_id=eq.{user_id}&select=*&limit=1")
1265
+ req = urllib.request.Request(url, method="GET", headers=_supabase_headers())
1266
+ with urllib.request.urlopen(req, timeout=6.0) as resp:
1267
+ rows = json.loads(resp.read().decode("utf-8"))
1268
+ return rows[0] if isinstance(rows, list) and rows else None
1269
+ except Exception as exc: # noqa: BLE001
1270
+ logger.warning("primer_analyses get failed: %s", exc)
1271
+ return None
1272
+
1273
+
1274
+ def delete_primer_analysis(user_id: Optional[str], analysis_id: str) -> Dict[str, Any]:
1275
+ """Delete one saved primer set, owner-enforced."""
1276
+ import re as _re
1277
+ if not user_id or not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
1278
+ return {"ok": False, "error": "Not configured."}
1279
+ if not _re.match(r"^[0-9a-fA-F-]{36}$", analysis_id or ""):
1280
+ return {"ok": False, "error": "Bad id."}
1281
+ import urllib.request
1282
+ try:
1283
+ url = (f"{SUPABASE_URL}/rest/v1/primer_analyses"
1284
+ f"?id=eq.{analysis_id}&user_id=eq.{user_id}")
1285
+ req = urllib.request.Request(url, method="DELETE",
1286
+ headers=_supabase_headers({"Prefer": "return=minimal"}))
1287
+ with urllib.request.urlopen(req, timeout=6.0):
1288
+ return {"ok": True}
1289
+ except Exception as exc: # noqa: BLE001
1290
+ logger.warning("primer_analyses delete failed: %s", exc)
1291
+ return {"ok": False, "error": "Couldn't delete."}
1292
+
1293
+
1294
+ def cleanup_expired_primer_analyses_async(user_id: Optional[str]) -> None:
1295
+ """Fire-and-forget delete of this user's expired primer sets (lazy sweep)."""
1296
+ if not user_id or not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
1297
+ return
1298
+ import threading
1299
+ threading.Thread(target=_do_cleanup_expired_primer_analyses,
1300
+ args=(user_id,), daemon=True).start()
1301
+
1302
+
1303
+ def _do_cleanup_expired_primer_analyses(user_id: str) -> None:
1304
+ import urllib.request
1305
+ try:
1306
+ url = (f"{SUPABASE_URL}/rest/v1/primer_analyses"
1307
+ f"?user_id=eq.{user_id}&expires_at=lt.now()")
1308
+ req = urllib.request.Request(url, method="DELETE",
1309
+ headers=_supabase_headers({"Prefer": "return=minimal"}))
1310
+ with urllib.request.urlopen(req, timeout=4.0):
1311
+ pass
1312
+ except Exception as exc: # noqa: BLE001
1313
+ logger.warning("primer_analyses cleanup failed for %s: %s", user_id, exc)
1314
+
1315
+
1316
+ # ─── Directed-Evolution libraries: per-user list + signed download ────
1317
+ # DE runs already persist to public.libraries + the `libraries` Storage
1318
+ # bucket (see _do_save_library). These surface them in the unified hub β€”
1319
+ # list metadata + mint a short-lived signed URL for the CSV download.
1320
+
1321
+ _LIBRARIES_LIST_LIMIT = 100
1322
+
1323
+
1324
+ def list_libraries(user_id: Optional[str]) -> list:
1325
+ """The user's saved DE libraries (metadata, newest first, non-expired)."""
1326
+ if not user_id or not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
1327
+ return []
1328
+ import urllib.request
1329
+ try:
1330
+ url = (f"{SUPABASE_URL}/rest/v1/libraries"
1331
+ f"?user_id=eq.{user_id}"
1332
+ f"&select=id,name,created_at,expires_at,n_variants,top_fitness,csv_size_bytes"
1333
+ f"&or=(expires_at.gte.now,expires_at.is.null)"
1334
+ f"&order=created_at.desc&limit={_LIBRARIES_LIST_LIMIT}")
1335
+ req = urllib.request.Request(url, method="GET", headers=_supabase_headers())
1336
+ with urllib.request.urlopen(req, timeout=6.0) as resp:
1337
+ return json.loads(resp.read().decode("utf-8")) or []
1338
+ except Exception as exc: # noqa: BLE001
1339
+ logger.warning("libraries list failed for %s: %s", user_id, exc)
1340
+ return []
1341
+
1342
+
1343
+ def library_csv_url(user_id: Optional[str], library_id: str) -> Optional[str]:
1344
+ """Signed, time-limited download URL for a library's CSV, owner-enforced.
1345
+ Returns an absolute URL or None. Never exposes the service key."""
1346
+ import re as _re
1347
+ if not user_id or not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
1348
+ return None
1349
+ if not _re.match(r"^[0-9a-fA-F-]{36}$", library_id or ""):
1350
+ return None
1351
+ import urllib.request
1352
+ # 1. Fetch the row to confirm ownership and get the storage_path.
1353
+ try:
1354
+ url = (f"{SUPABASE_URL}/rest/v1/libraries"
1355
+ f"?id=eq.{library_id}&user_id=eq.{user_id}&select=storage_path&limit=1")
1356
+ req = urllib.request.Request(url, method="GET", headers=_supabase_headers())
1357
+ with urllib.request.urlopen(req, timeout=6.0) as resp:
1358
+ rows = json.loads(resp.read().decode("utf-8"))
1359
+ storage_path = (rows[0] if isinstance(rows, list) and rows else {}).get("storage_path")
1360
+ if not storage_path:
1361
+ return None
1362
+ except Exception as exc: # noqa: BLE001
1363
+ logger.warning("library_csv_url lookup failed: %s", exc)
1364
+ return None
1365
+ # 2. Mint a signed URL (valid 5 min) from Storage.
1366
+ try:
1367
+ sign_url = f"{SUPABASE_URL}/storage/v1/object/sign/libraries/{storage_path}"
1368
+ req = urllib.request.Request(
1369
+ sign_url,
1370
+ data=json.dumps({"expiresIn": 300}).encode("utf-8"),
1371
+ method="POST",
1372
+ headers=_supabase_headers({"Content-Type": "application/json"}),
1373
+ )
1374
+ with urllib.request.urlopen(req, timeout=6.0) as resp:
1375
+ data = json.loads(resp.read().decode("utf-8"))
1376
+ signed = (data or {}).get("signedURL") or (data or {}).get("signedUrl")
1377
+ if not signed:
1378
+ return None
1379
+ if signed.startswith("http"):
1380
+ return signed
1381
+ if not signed.startswith("/"):
1382
+ signed = "/" + signed
1383
+ # Storage returns "/object/sign/libraries/<path>?token=…" β†’ prefix /storage/v1.
1384
+ return f"{SUPABASE_URL}{signed}" if signed.startswith("/storage/") else f"{SUPABASE_URL}/storage/v1{signed}"
1385
+ except Exception as exc: # noqa: BLE001
1386
+ logger.warning("library sign failed: %s", exc)
1387
+ return None
1388
+
1389
+
1390
  def _anon_fingerprint() -> str:
1391
  """Stable-ish hash of IP + UA, salted with ANON_SECRET. Used only to
1392
  rough-deduplicate anonymous runs in analytics. Not identity-grade β€”
dee/server.py CHANGED
@@ -1825,6 +1825,95 @@ def create_app() -> Flask:
1825
  return jsonify({"ok": False, "error": "Design not found."}), 404
1826
  return jsonify({"ok": True, "design": design})
1827
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1828
  @app.post("/api/crispr/download")
1829
  def crispr_download() -> Response:
1830
  """Return the CSV body for a fresh design. We re-design from the
 
1825
  return jsonify({"ok": False, "error": "Design not found."}), 404
1826
  return jsonify({"ok": True, "design": design})
1827
 
1828
+ # ── Primer Analysis: saved sets (unified "My designs" hub) ──
1829
+ # Static routes win over /api/primers/<job_id> in Werkzeug, so no clash.
1830
+ @app.post("/api/primers/save")
1831
+ def primers_save() -> Response:
1832
+ """Save the current primer analysis to the signed-in user's library."""
1833
+ auth = _auth.get_auth()
1834
+ if auth.anonymous:
1835
+ return jsonify({"ok": False, "error": "signin_required",
1836
+ "kind": "signin_required",
1837
+ "signup_url": "https://turingdna.com/signin/?from=primers"}), 403
1838
+ body = request.get_json(force=True, silent=True) or {}
1839
+ result_obj = body.get("result")
1840
+ if not isinstance(result_obj, dict) or not result_obj.get("primers"):
1841
+ return jsonify({"ok": False, "error": "Nothing to save β€” analyse some primers first."}), 400
1842
+ try:
1843
+ template_len = int(body.get("template_len") or 0)
1844
+ except (TypeError, ValueError):
1845
+ template_len = 0
1846
+ try:
1847
+ n_primers = int(body.get("n_primers") or len(result_obj.get("primers") or []))
1848
+ except (TypeError, ValueError):
1849
+ n_primers = len(result_obj.get("primers") or [])
1850
+ result = _auth.save_primer_analysis(
1851
+ auth.user_id,
1852
+ label=str(body.get("label", ""))[:120],
1853
+ organism=str(body.get("organism", ""))[:32] or None,
1854
+ template_len=template_len,
1855
+ n_primers=n_primers,
1856
+ result=result_obj,
1857
+ )
1858
+ _auth.cleanup_expired_primer_analyses_async(auth.user_id) # lazy sweep
1859
+ return jsonify(result), (200 if result.get("ok") else 502)
1860
+
1861
+ @app.get("/api/primers/analyses")
1862
+ def primers_analyses_list() -> Response:
1863
+ """The signed-in user's saved primer sets (metadata only)."""
1864
+ auth = _auth.get_auth()
1865
+ if auth.anonymous:
1866
+ return jsonify({"ok": False, "error": "signin_required",
1867
+ "kind": "signin_required"}), 403
1868
+ return jsonify({"ok": True, "analyses": _auth.list_primer_analyses(auth.user_id)})
1869
+
1870
+ @app.get("/api/primers/analyses/<analysis_id>")
1871
+ def primers_analysis_get(analysis_id: str) -> Response:
1872
+ """One saved primer set incl. result (owner-only, server-enforced)."""
1873
+ auth = _auth.get_auth()
1874
+ if auth.anonymous:
1875
+ return jsonify({"ok": False, "error": "signin_required",
1876
+ "kind": "signin_required"}), 403
1877
+ analysis = _auth.get_primer_analysis(auth.user_id, analysis_id)
1878
+ if analysis is None:
1879
+ return jsonify({"ok": False, "error": "Primer set not found."}), 404
1880
+ return jsonify({"ok": True, "analysis": analysis})
1881
+
1882
+ @app.delete("/api/primers/analyses/<analysis_id>")
1883
+ def primers_analysis_delete(analysis_id: str) -> Response:
1884
+ """Delete one saved primer set (owner-only)."""
1885
+ auth = _auth.get_auth()
1886
+ if auth.anonymous:
1887
+ return jsonify({"ok": False, "error": "signin_required",
1888
+ "kind": "signin_required"}), 403
1889
+ return jsonify(_auth.delete_primer_analysis(auth.user_id, analysis_id))
1890
+
1891
+ # ── Directed-Evolution libraries: per-user list + signed CSV download ──
1892
+ # Per-user, RLS-safe replacement for the shared-filesystem /api/library
1893
+ # removed in audit C2 β€” reads public.libraries filtered by the JWT user.
1894
+ @app.get("/api/library")
1895
+ def library_list() -> Response:
1896
+ """The signed-in user's saved DE libraries (metadata only)."""
1897
+ auth = _auth.get_auth()
1898
+ if auth.anonymous:
1899
+ return jsonify({"ok": False, "error": "signin_required",
1900
+ "kind": "signin_required"}), 403
1901
+ return jsonify({"ok": True, "libraries": _auth.list_libraries(auth.user_id)})
1902
+
1903
+ @app.get("/api/library/<library_id>/download")
1904
+ def library_download(library_id: str) -> Response:
1905
+ """Return a short-lived signed URL for the library CSV (owner-only).
1906
+ The browser fetches the CSV straight from Storage; the service key
1907
+ never leaves the server."""
1908
+ auth = _auth.get_auth()
1909
+ if auth.anonymous:
1910
+ return jsonify({"ok": False, "error": "signin_required",
1911
+ "kind": "signin_required"}), 403
1912
+ url = _auth.library_csv_url(auth.user_id, library_id)
1913
+ if not url:
1914
+ return jsonify({"ok": False, "error": "Library not found."}), 404
1915
+ return jsonify({"ok": True, "url": url})
1916
+
1917
  @app.post("/api/crispr/download")
1918
  def crispr_download() -> Response:
1919
  """Return the CSV body for a fresh design. We re-design from the
dee/static/app.css CHANGED
@@ -5663,3 +5663,69 @@ h3, h4 {
5663
  @media (max-width: 540px) {
5664
  .workbench-links { grid-template-columns: 1fr; }
5665
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5663
  @media (max-width: 540px) {
5664
  .workbench-links { grid-template-columns: 1fr; }
5665
  }
5666
+
5667
+ /* ── Primer results header (Save) ─────────────────────────────────────── */
5668
+ .primer-results-head {
5669
+ display: flex;
5670
+ align-items: center;
5671
+ justify-content: space-between;
5672
+ gap: 12px;
5673
+ margin-bottom: 12px;
5674
+ }
5675
+ .primer-results-title {
5676
+ font-family: var(--font-mono);
5677
+ font-size: 11px;
5678
+ letter-spacing: 0.12em;
5679
+ text-transform: uppercase;
5680
+ color: var(--ink-faint);
5681
+ }
5682
+
5683
+ /* ── Unified saved-work hub ("My designs") ────────────────────────────── */
5684
+ .saved-body { max-height: 70vh; overflow-y: auto; }
5685
+ .saved-section { margin: 0 0 22px; }
5686
+ .saved-section:last-child { margin-bottom: 4px; }
5687
+ .saved-sec-title {
5688
+ font-family: var(--font-mono);
5689
+ font-size: 11px;
5690
+ letter-spacing: 0.12em;
5691
+ text-transform: uppercase;
5692
+ color: var(--ink-faint);
5693
+ margin: 0 0 8px;
5694
+ padding-bottom: 6px;
5695
+ border-bottom: 1px solid var(--line);
5696
+ }
5697
+ .saved-list { display: flex; flex-direction: column; gap: 1px; }
5698
+ .saved-row {
5699
+ display: flex;
5700
+ align-items: center;
5701
+ justify-content: space-between;
5702
+ gap: 12px;
5703
+ min-height: 44px;
5704
+ padding: 10px 12px;
5705
+ border-radius: var(--r-2);
5706
+ background: transparent;
5707
+ transition: background var(--t-fast) var(--ease);
5708
+ }
5709
+ .saved-row[role="button"] { cursor: pointer; }
5710
+ .saved-row[role="button"]:hover,
5711
+ .saved-row[role="button"]:focus-visible { background: var(--bg-hover); outline: none; }
5712
+ .saved-row-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
5713
+ .saved-row-label { font-size: 14px; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
5714
+ .saved-row[role="button"]:hover .saved-row-label { color: var(--brand-deep); }
5715
+ .saved-row-meta { font-size: 12px; color: var(--ink-faint); }
5716
+ .saved-dl {
5717
+ flex: none;
5718
+ font-family: var(--font-mono);
5719
+ font-size: 11px;
5720
+ letter-spacing: 0.06em;
5721
+ padding: 7px 12px;
5722
+ min-height: 44px;
5723
+ border: 1px solid var(--brand);
5724
+ color: var(--brand-deep);
5725
+ background: transparent;
5726
+ border-radius: var(--r-2);
5727
+ cursor: pointer;
5728
+ transition: background var(--t-fast) var(--ease);
5729
+ }
5730
+ .saved-dl:hover { background: var(--bg-hover); }
5731
+ .saved-dl:disabled { opacity: 0.6; cursor: default; }
dee/static/app.js CHANGED
@@ -345,12 +345,9 @@ showRoute(currentRoute());
345
  const navMyDesigns = document.getElementById('navMyDesigns');
346
  if (!navMyDesigns) return;
347
  function open() {
348
- showRoute('crispr');
349
- if (location.hash !== '#crispr') {
350
- try { history.replaceState(null, '', '#crispr'); } catch (_) { location.hash = 'crispr'; }
351
- }
352
- const btn = document.getElementById('crisprDesignsBtn');
353
- if (btn) btn.click();
354
  }
355
  navMyDesigns.addEventListener('click', open);
356
  navMyDesigns.addEventListener('keydown', (e) => {
@@ -5165,34 +5162,9 @@ if (_quitBtn) {
5165
  }
5166
  });
5167
 
5168
- if (designsBtn) designsBtn.addEventListener('click', async () => {
5169
- if (!designsModal) return;
5170
- designsModal.hidden = false;
5171
- if (designsList) designsList.innerHTML = '<p class="muted">Loading…</p>';
5172
- try {
5173
- const res = await fetch('/api/crispr/designs');
5174
- const data = await res.json();
5175
- if (res.status === 403 && data.kind === 'signin_required') { designsModal.hidden = true; _openSigninModal(); return; }
5176
- const designs = (data && data.designs) || [];
5177
- if (!designs.length) {
5178
- if (designsList) designsList.innerHTML = '<p class="muted">No saved designs yet. Run a design and click &ldquo;Save design&rdquo;.</p>';
5179
- return;
5180
- }
5181
- if (designsList) {
5182
- designsList.innerHTML = designs.map((d) => {
5183
- const when = d.created_at ? new Date(d.created_at).toLocaleDateString() : '';
5184
- const tag = d.mode === 'base_edit' ? 'base edit' : 'knockout';
5185
- return `<button type="button" class="crispr-design-row" data-design-id="${escapeHtml(d.id)}">
5186
- <span class="crispr-design-label">${escapeHtml(d.label || 'Untitled design')}</span>
5187
- <span class="crispr-design-meta">${escapeHtml(tag)} Β· ${d.n_guides || 0} guides Β· ${escapeHtml(when)}</span>
5188
- </button>`;
5189
- }).join('');
5190
- designsList.querySelectorAll('.crispr-design-row').forEach((row) =>
5191
- row.addEventListener('click', () => _loadDesign(row.getAttribute('data-design-id'))));
5192
- }
5193
- } catch (err) {
5194
- if (designsList) designsList.innerHTML = `<p class="muted">${escapeHtml(err.message || 'Could not load your designs.')}</p>`;
5195
- }
5196
  });
5197
 
5198
  async function _loadDesign(id) {
@@ -5228,6 +5200,10 @@ if (_quitBtn) {
5228
  }
5229
  }
5230
 
 
 
 
 
5231
  function _renderResults(data, _isRerender) {
5232
  resCard.hidden = false;
5233
 
@@ -5856,6 +5832,7 @@ function runOracle(opts){
5856
  const prodEl = document.getElementById('primerProducts');
5857
  const listEl = document.getElementById('primerList');
5858
  let pollHandle = null;
 
5859
 
5860
  // The organism selector only matters when the specificity scan is on.
5861
  if (scanEl && orgRow) {
@@ -5927,6 +5904,7 @@ function runOracle(opts){
5927
 
5928
  let _hasTemplate = false;
5929
  function render(data) {
 
5930
  const r = data.result || {};
5931
  _hasTemplate = !!r.has_template;
5932
  resCard.hidden = false;
@@ -6081,6 +6059,56 @@ function runOracle(opts){
6081
  'ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGACCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAAGACCCGCGCCGAGGTGAAGTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAGGGCATCGACTTCAAGGAGGACGGCAACATCCTGGGGCACAAGCTGGAGTACAACTACAACAGCCACAACGTCTATATCATGGCCGACAAGCAGAAGAACGGCATCAAGGTGAACTTCAAGATCCGCCACAACATCGAGGACGGCAGCGTGCAGCTCGCCGACCACTACCAGCAGAACACCCCCATCGGCGACGGCCCCGTGCTGCTGCCCGACAACCACTACCTGAGCACCCAGTCCGCCCTGAGCAAAGACCCCAACGAGAAGCGCGATCACATGGTCCTGCTGGAGTTCGTGACCGCCGCCGGGATCACTCTCGGCATGGACGAGCTGTACAAGTAA';
6082
  if (scanEl) scanEl.checked = false;
6083
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6084
  })();
6085
 
6086
  // ============================================================ PLASMID STUDIO
@@ -6484,7 +6512,14 @@ function runOracle(opts){
6484
  $('plasmidDigestBtn').addEventListener('click', doDigest);
6485
  $('plasmidClearEnz').addEventListener('click', () => { selected.clear(); renderEnzymes(); renderMap(); gelEl.hidden = true; gelEl.innerHTML = ''; });
6486
  $('plasmidSave').addEventListener('click', doSave);
6487
- $('plasmidLibraryBtn').addEventListener('click', openLibrary);
 
 
 
 
 
 
 
6488
  if (libModal) {
6489
  libModal.querySelectorAll('[data-plasmid-lib-close]').forEach((el) => el.addEventListener('click', closeLibrary));
6490
  libList.addEventListener('click', (e) => {
@@ -6915,3 +6950,109 @@ function runOracle(opts){
6915
  if (t) { t.scrollIntoView({ behavior: 'smooth', block: 'center' }); t.focus(); }
6916
  });
6917
  })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  const navMyDesigns = document.getElementById('navMyDesigns');
346
  if (!navMyDesigns) return;
347
  function open() {
348
+ // Unified saved-work hub (all four tools). Registered by the
349
+ // saved-hub controller below.
350
+ if (window.TDSaved && window.TDSaved.open) window.TDSaved.open();
 
 
 
351
  }
352
  navMyDesigns.addEventListener('click', open);
353
  navMyDesigns.addEventListener('keydown', (e) => {
 
5162
  }
5163
  });
5164
 
5165
+ // "My designs" button β†’ unified saved-work hub (all four tools).
5166
+ if (designsBtn) designsBtn.addEventListener('click', () => {
5167
+ if (window.TDSaved && window.TDSaved.open) window.TDSaved.open();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5168
  });
5169
 
5170
  async function _loadDesign(id) {
 
5200
  }
5201
  }
5202
 
5203
+ // Expose reopen to the unified saved-work hub.
5204
+ window.TDSaved = window.TDSaved || {};
5205
+ window.TDSaved.crispr = _loadDesign;
5206
+
5207
  function _renderResults(data, _isRerender) {
5208
  resCard.hidden = false;
5209
 
 
5832
  const prodEl = document.getElementById('primerProducts');
5833
  const listEl = document.getElementById('primerList');
5834
  let pollHandle = null;
5835
+ let lastData = null; // last analyze response β€” for Save + reopen
5836
 
5837
  // The organism selector only matters when the specificity scan is on.
5838
  if (scanEl && orgRow) {
 
5904
 
5905
  let _hasTemplate = false;
5906
  function render(data) {
5907
+ lastData = data;
5908
  const r = data.result || {};
5909
  _hasTemplate = !!r.has_template;
5910
  resCard.hidden = false;
 
6059
  'ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGACCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAAGACCCGCGCCGAGGTGAAGTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAGGGCATCGACTTCAAGGAGGACGGCAACATCCTGGGGCACAAGCTGGAGTACAACTACAACAGCCACAACGTCTATATCATGGCCGACAAGCAGAAGAACGGCATCAAGGTGAACTTCAAGATCCGCCACAACATCGAGGACGGCAGCGTGCAGCTCGCCGACCACTACCAGCAGAACACCCCCATCGGCGACGGCCCCGTGCTGCTGCCCGACAACCACTACCTGAGCACCCAGTCCGCCCTGAGCAAAGACCCCAACGAGAAGCGCGATCACATGGTCCTGCTGGAGTTCGTGACCGCCGCCGGGATCACTCTCGGCATGGACGAGCTGTACAAGTAA';
6060
  if (scanEl) scanEl.checked = false;
6061
  });
6062
+
6063
+ // ── Save & reopen (unified "My designs" hub) ──
6064
+ const saveBtn = document.getElementById('primerSaveBtn');
6065
+ function _primerLabel() {
6066
+ const n = ((lastData && lastData.result && lastData.result.primers) || []).length;
6067
+ const bits = [n + ' primer' + (n === 1 ? '' : 's')];
6068
+ if (scanEl && scanEl.checked && orgEl && orgEl.value) bits.push(ORG_LABEL[orgEl.value] || orgEl.value);
6069
+ return bits.join(' Β· ');
6070
+ }
6071
+ if (saveBtn) saveBtn.addEventListener('click', async () => {
6072
+ const r = (lastData && lastData.result) || null;
6073
+ if (!r || !(r.primers && r.primers.length)) { showErr('Analyse some primers first, then save.'); return; }
6074
+ const orig = saveBtn.textContent;
6075
+ saveBtn.disabled = true; saveBtn.textContent = 'Saving…';
6076
+ try {
6077
+ const tmpl = ((templateEl && templateEl.value) || '').replace(/\s+/g, '');
6078
+ const res = await fetch('/api/primers/save', {
6079
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
6080
+ body: JSON.stringify({
6081
+ label: _primerLabel(),
6082
+ organism: (scanEl && scanEl.checked && orgEl) ? orgEl.value : '',
6083
+ template_len: tmpl.length,
6084
+ n_primers: r.primers.length,
6085
+ result: r,
6086
+ }),
6087
+ });
6088
+ const data = await res.json();
6089
+ if (res.status === 403 && data.kind === 'signin_required') { window.dispatchEvent(new Event('td:signin-required')); return; }
6090
+ if (!data.ok) { showErr(data.error || 'Could not save the primer set.'); return; }
6091
+ saveBtn.textContent = 'Saved βœ“';
6092
+ setTimeout(() => { saveBtn.textContent = orig; }, 1600);
6093
+ } catch (e) { showErr(e.message || 'Could not save the primer set.'); }
6094
+ finally { saveBtn.disabled = false; if (saveBtn.textContent === 'Saving…') saveBtn.textContent = orig; }
6095
+ });
6096
+
6097
+ async function _loadPrimerSet(id) {
6098
+ try {
6099
+ const res = await fetch('/api/primers/analyses/' + encodeURIComponent(id));
6100
+ const data = await res.json();
6101
+ if (res.status === 403 && data.kind === 'signin_required') { window.dispatchEvent(new Event('td:signin-required')); return; }
6102
+ if (!data.ok || !data.analysis) { showErr('Could not open that primer set.'); return; }
6103
+ const a = data.analysis;
6104
+ if (location.hash !== '#primers') location.hash = '#primers';
6105
+ if (orgEl && a.organism) orgEl.value = a.organism;
6106
+ render({ result: a.result || {} });
6107
+ if (resCard) resCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
6108
+ } catch (e) { showErr('Could not open that primer set.'); }
6109
+ }
6110
+ window.TDSaved = window.TDSaved || {};
6111
+ window.TDSaved.primer = _loadPrimerSet;
6112
  })();
6113
 
6114
  // ============================================================ PLASMID STUDIO
 
6512
  $('plasmidDigestBtn').addEventListener('click', doDigest);
6513
  $('plasmidClearEnz').addEventListener('click', () => { selected.clear(); renderEnzymes(); renderMap(); gelEl.hidden = true; gelEl.innerHTML = ''; });
6514
  $('plasmidSave').addEventListener('click', doSave);
6515
+ // "My plasmids" now opens the unified saved-work hub (falls back to the
6516
+ // legacy per-tool modal if the hub isn't registered yet).
6517
+ $('plasmidLibraryBtn').addEventListener('click', () => {
6518
+ if (window.TDSaved && window.TDSaved.open) window.TDSaved.open(); else openLibrary();
6519
+ });
6520
+ // Expose plasmid reopen to the unified hub.
6521
+ window.TDSaved = window.TDSaved || {};
6522
+ window.TDSaved.plasmid = openSaved;
6523
  if (libModal) {
6524
  libModal.querySelectorAll('[data-plasmid-lib-close]').forEach((el) => el.addEventListener('click', closeLibrary));
6525
  libList.addEventListener('click', (e) => {
 
6950
  if (t) { t.scrollIntoView({ behavior: 'smooth', block: 'center' }); t.focus(); }
6951
  });
6952
  })();
6953
+
6954
+ // ════════════════════════════════════════════════ UNIFIED SAVED-WORK HUB
6955
+ // One "My designs" panel listing everything saved across all four tools.
6956
+ // Each tool controller registers its reopen fn on window.TDSaved (above);
6957
+ // here we render the sections and dispatch row clicks. Backed by
6958
+ // /api/plasmid/library, /api/crispr/designs, /api/primers/analyses, /api/library.
6959
+ (function initSavedHub() {
6960
+ const modal = document.getElementById('savedModal');
6961
+ if (!modal) return;
6962
+ const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
6963
+ const fmtDate = (s) => { try { return s ? new Date(s).toLocaleDateString() : ''; } catch (_) { return ''; } };
6964
+ window.TDSaved = window.TDSaved || {};
6965
+ const KIND_HASH = { plasmid: '#plasmid', crispr: '#crispr', primer: '#primers' };
6966
+
6967
+ function close() { modal.hidden = true; document.body.style.overflow = ''; }
6968
+ function open() { modal.hidden = false; document.body.style.overflow = 'hidden'; loadAll(); }
6969
+ modal.querySelectorAll('[data-saved-close]').forEach((el) => el.addEventListener('click', close));
6970
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !modal.hidden) close(); });
6971
+
6972
+ // signin_required from any section β†’ close + surface the sign-in modal once.
6973
+ let _signinFired = false;
6974
+ function _maybeSignin(res, data) {
6975
+ if (res.status === 403 && data && data.kind === 'signin_required') {
6976
+ if (!_signinFired) { _signinFired = true; close(); window.dispatchEvent(new Event('td:signin-required')); }
6977
+ return true;
6978
+ }
6979
+ return false;
6980
+ }
6981
+
6982
+ function reopen(kind, id) {
6983
+ close();
6984
+ const h = KIND_HASH[kind];
6985
+ if (h && location.hash !== h) location.hash = h; // navigate to the tool first
6986
+ const fn = window.TDSaved[kind];
6987
+ if (typeof fn === 'function') fn(id);
6988
+ }
6989
+
6990
+ async function downloadLibrary(id, btn) {
6991
+ const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Preparing…';
6992
+ try {
6993
+ const res = await fetch('/api/library/' + encodeURIComponent(id) + '/download');
6994
+ const data = await res.json();
6995
+ if (_maybeSignin(res, data)) return;
6996
+ if (data.ok && data.url) window.open(data.url, '_blank', 'noopener');
6997
+ } catch (_) { /* ignore */ }
6998
+ finally { btn.disabled = false; btn.textContent = orig; }
6999
+ }
7000
+
7001
+ function savedRow(kind, id, label, meta, opts) {
7002
+ opts = opts || {};
7003
+ const action = opts.download
7004
+ ? `<button type="button" class="saved-dl" data-dl="${esc(id)}">Download CSV</button>` : '';
7005
+ const interactive = opts.download ? '' : ' role="button" tabindex="0"';
7006
+ return `<div class="saved-row" data-kind="${kind}" data-id="${esc(id)}"${interactive}>` +
7007
+ `<span class="saved-row-main"><span class="saved-row-label">${esc(label)}</span>` +
7008
+ `<span class="saved-row-meta">${esc(meta)}</span></span>${action}</div>`;
7009
+ }
7010
+
7011
+ async function loadSection(elId, url, key, render, emptyMsg) {
7012
+ const el = document.getElementById(elId);
7013
+ if (!el) return;
7014
+ el.innerHTML = '<p class="muted">Loading…</p>';
7015
+ try {
7016
+ const res = await fetch(url);
7017
+ const data = await res.json();
7018
+ if (_maybeSignin(res, data)) return;
7019
+ const items = (data && data[key]) || [];
7020
+ el.innerHTML = items.length ? items.map(render).join('') : `<p class="muted">${esc(emptyMsg)}</p>`;
7021
+ } catch (_) { el.innerHTML = '<p class="muted">Couldn’t load these.</p>'; }
7022
+ }
7023
+
7024
+ function loadAll() {
7025
+ _signinFired = false;
7026
+ loadSection('savedPlasmids', '/api/plasmid/library', 'plasmids',
7027
+ (p) => savedRow('plasmid', p.id, p.name || 'plasmid',
7028
+ `${(p.length || 0).toLocaleString()} bp Β· ${p.topology || ''}${p.gc != null ? ' Β· GC ' + p.gc + '%' : ''}`),
7029
+ 'No saved plasmids yet. Import one and hit Save.');
7030
+ loadSection('savedCrispr', '/api/crispr/designs', 'designs',
7031
+ (d) => savedRow('crispr', d.id, d.label || 'Untitled design',
7032
+ `${d.mode === 'base_edit' ? 'base edit' : 'knockout'} Β· ${d.n_guides || 0} guides Β· ${fmtDate(d.created_at)}`),
7033
+ 'No saved CRISPR designs yet. Run a design and click Save.');
7034
+ loadSection('savedPrimers', '/api/primers/analyses', 'analyses',
7035
+ (a) => savedRow('primer', a.id, a.label || 'Primer set',
7036
+ `${a.n_primers || 0} primers${a.template_len ? ' Β· ' + a.template_len.toLocaleString() + ' bp template' : ''} Β· ${fmtDate(a.created_at)}`),
7037
+ 'No saved primer sets yet. Analyse primers and click Save.');
7038
+ loadSection('savedLibraries', '/api/library', 'libraries',
7039
+ (l) => savedRow('library', l.id, l.name || 'Library',
7040
+ `${(l.n_variants || 0).toLocaleString()} variants${l.top_fitness != null ? ' Β· top ' + Number(l.top_fitness).toFixed(2) : ''} Β· ${fmtDate(l.created_at)}`,
7041
+ { download: true }),
7042
+ 'No saved evolution libraries yet. Run the engine while signed in.');
7043
+ }
7044
+
7045
+ modal.addEventListener('click', (e) => {
7046
+ const dl = e.target.closest('.saved-dl');
7047
+ if (dl) { e.stopPropagation(); downloadLibrary(dl.getAttribute('data-dl'), dl); return; }
7048
+ const row = e.target.closest('.saved-row[role="button"]');
7049
+ if (row) reopen(row.getAttribute('data-kind'), row.getAttribute('data-id'));
7050
+ });
7051
+ modal.addEventListener('keydown', (e) => {
7052
+ if (e.key !== 'Enter' && e.key !== ' ') return;
7053
+ const row = e.target.closest && e.target.closest('.saved-row[role="button"]');
7054
+ if (row) { e.preventDefault(); reopen(row.getAttribute('data-kind'), row.getAttribute('data-id')); }
7055
+ });
7056
+
7057
+ window.TDSaved.open = open;
7058
+ })();
dee/static/index.html CHANGED
@@ -22,7 +22,7 @@
22
  <!-- ?v= query bumps invalidate browser + iframe asset caches when app.css /
23
  app.js change. Bump these numbers whenever you ship a frontend update β€”
24
  without them, users keep getting the stale file for up to a week. -->
25
- <link rel="stylesheet" href="/static/app.css?v=20260604-hub" />
26
  <link rel="icon" type="image/svg+xml" href="/static/favicon.svg?v=2" />
27
  <link rel="apple-touch-icon" href="/static/favicon.svg?v=2" />
28
  <!-- Mol* (PDBe) viewer for AlphaFold structure embed. Loaded async; the
@@ -909,6 +909,10 @@
909
  </section>
910
 
911
  <section class="card primer-results-card" id="primerResultsCard" hidden>
 
 
 
 
912
  <div class="primer-scan-status" id="primerScanStatus" hidden></div>
913
  <div class="primer-best" id="primerBest"></div>
914
  <div class="primer-amplicons" id="primerAmplicons"></div>
@@ -1322,6 +1326,42 @@
1322
  </div>
1323
  </div>
1324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1325
  <!-- BLAST consent modal β€” fires the first time per-session that the
1326
  user clicks "Identify via NCBI BLAST". Per-session sessionStorage
1327
  flag means the user only sees this once per browser session.
@@ -1500,6 +1540,6 @@
1500
  <!-- Cloning reference data must load before app.js so the Designer
1501
  can read VECTORS / ENZYMES / CLONING_METHODS / TAGS / LINKERS. -->
1502
  <script src="/static/cloning_db.js?v=20260530-ui-polish" defer></script>
1503
- <script src="/static/app.js?v=20260604-hub" defer></script>
1504
  </body>
1505
  </html>
 
22
  <!-- ?v= query bumps invalidate browser + iframe asset caches when app.css /
23
  app.js change. Bump these numbers whenever you ship a frontend update β€”
24
  without them, users keep getting the stale file for up to a week. -->
25
+ <link rel="stylesheet" href="/static/app.css?v=20260605-saved" />
26
  <link rel="icon" type="image/svg+xml" href="/static/favicon.svg?v=2" />
27
  <link rel="apple-touch-icon" href="/static/favicon.svg?v=2" />
28
  <!-- Mol* (PDBe) viewer for AlphaFold structure embed. Loaded async; the
 
909
  </section>
910
 
911
  <section class="card primer-results-card" id="primerResultsCard" hidden>
912
+ <div class="primer-results-head">
913
+ <span class="primer-results-title">Ranked primers</span>
914
+ <button class="ghost" type="button" id="primerSaveBtn">Save</button>
915
+ </div>
916
  <div class="primer-scan-status" id="primerScanStatus" hidden></div>
917
  <div class="primer-best" id="primerBest"></div>
918
  <div class="primer-amplicons" id="primerAmplicons"></div>
 
1326
  </div>
1327
  </div>
1328
 
1329
+ <!-- Unified saved-work hub (2026-06-05). One panel listing everything the
1330
+ signed-in user has saved across all four tools, each reopenable β€”
1331
+ replaces the per-tool "My plasmids" list and the CRISPR-only "My
1332
+ designs". Sections lazy-load in parallel; each degrades independently. -->
1333
+ <div class="modal" id="savedModal" hidden role="dialog" aria-labelledby="savedTitle" aria-modal="true">
1334
+ <div class="modal-backdrop" data-saved-close></div>
1335
+ <div class="modal-panel" role="document">
1336
+ <header class="modal-header">
1337
+ <div>
1338
+ <p class="modal-sub">&sect; Library</p>
1339
+ <h2 id="savedTitle">My designs</h2>
1340
+ <p class="modal-sub">Everything you&rsquo;ve saved &mdash; kept for 90 days. Click one to reopen it.</p>
1341
+ </div>
1342
+ <button class="modal-close" aria-label="Close" data-saved-close>&times;</button>
1343
+ </header>
1344
+ <div class="modal-body saved-body">
1345
+ <section class="saved-section">
1346
+ <h3 class="saved-sec-title">Plasmids</h3>
1347
+ <div id="savedPlasmids" class="saved-list"><p class="muted">Loading…</p></div>
1348
+ </section>
1349
+ <section class="saved-section">
1350
+ <h3 class="saved-sec-title">CRISPR designs</h3>
1351
+ <div id="savedCrispr" class="saved-list"><p class="muted">Loading…</p></div>
1352
+ </section>
1353
+ <section class="saved-section">
1354
+ <h3 class="saved-sec-title">Primer sets</h3>
1355
+ <div id="savedPrimers" class="saved-list"><p class="muted">Loading…</p></div>
1356
+ </section>
1357
+ <section class="saved-section">
1358
+ <h3 class="saved-sec-title">Evolution libraries</h3>
1359
+ <div id="savedLibraries" class="saved-list"><p class="muted">Loading…</p></div>
1360
+ </section>
1361
+ </div>
1362
+ </div>
1363
+ </div>
1364
+
1365
  <!-- BLAST consent modal β€” fires the first time per-session that the
1366
  user clicks "Identify via NCBI BLAST". Per-session sessionStorage
1367
  flag means the user only sees this once per browser session.
 
1540
  <!-- Cloning reference data must load before app.js so the Designer
1541
  can read VECTORS / ENZYMES / CLONING_METHODS / TAGS / LINKERS. -->
1542
  <script src="/static/cloning_db.js?v=20260530-ui-polish" defer></script>
1543
+ <script src="/static/app.js?v=20260605-saved" defer></script>
1544
  </body>
1545
  </html>
supabase/migrations/0006_primer_analyses.sql ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- 0006_primer_analyses.sql β€” per-user saved Primer Analysis results
2
+ --
3
+ -- Run this in the Supabase SQL editor (Dashboard β†’ SQL β†’ New query β†’ Run)
4
+ -- BEFORE the unified "My designs" hub can save primer sets. Idempotent:
5
+ -- safe to run more than once.
6
+ --
7
+ -- Mirrors public.crispr_designs / public.libraries: owner-only Row Level
8
+ -- Security, a 90-day TTL via expires_at (NULL = keep forever, for future
9
+ -- pro plans), and indexes for the list query + the lazy expiry sweep. The
10
+ -- TuringDNA Space backend writes/reads with the service-role key (which
11
+ -- bypasses RLS) and enforces ownership in code by filtering on user_id;
12
+ -- the RLS policies below are the defense-in-depth layer for any direct,
13
+ -- anon-key client access.
14
+
15
+ create table if not exists public.primer_analyses (
16
+ id uuid primary key default gen_random_uuid(),
17
+ user_id uuid not null references auth.users (id) on delete cascade,
18
+ created_at timestamptz not null default now(),
19
+ expires_at timestamptz, -- NULL = never expires
20
+ label text not null default 'Untitled primer set',
21
+ organism text, -- specificity-check organism
22
+ template_len integer, -- length of the PCR template
23
+ n_primers integer, -- candidate primers analysed
24
+ result jsonb not null default '{}'::jsonb -- full analyze payload (for re-render)
25
+ );
26
+
27
+ comment on table public.primer_analyses is
28
+ 'User-saved Primer Analysis results. 90-day TTL (expires_at); owner-only RLS.';
29
+
30
+ alter table public.primer_analyses enable row level security;
31
+
32
+ -- Owner-only access. (Backend uses the service-role key and additionally
33
+ -- filters by user_id; these policies guard any direct client access.)
34
+ drop policy if exists "primer_analyses_select_own" on public.primer_analyses;
35
+ create policy "primer_analyses_select_own"
36
+ on public.primer_analyses for select
37
+ using (auth.uid() = user_id);
38
+
39
+ drop policy if exists "primer_analyses_insert_own" on public.primer_analyses;
40
+ create policy "primer_analyses_insert_own"
41
+ on public.primer_analyses for insert
42
+ with check (auth.uid() = user_id);
43
+
44
+ drop policy if exists "primer_analyses_delete_own" on public.primer_analyses;
45
+ create policy "primer_analyses_delete_own"
46
+ on public.primer_analyses for delete
47
+ using (auth.uid() = user_id);
48
+
49
+ -- List query: a user's saved primer sets, newest first.
50
+ create index if not exists primer_analyses_user_created_idx
51
+ on public.primer_analyses (user_id, created_at desc);
52
+
53
+ -- Lazy expiry sweep target.
54
+ create index if not exists primer_analyses_expires_idx
55
+ on public.primer_analyses (expires_at)
56
+ where expires_at is not null;
tests/test_primer_save.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Endpoint tests for the unified saved-work hub:
2
+ - Primer Analysis persistence (/api/primers/{save,analyses,analyses/<id>})
3
+ - Directed-Evolution library list + signed download (/api/library …)
4
+ Flask test client; the auth + DB layer is stubbed (no network, no DB)."""
5
+ import types
6
+
7
+ import pytest
8
+
9
+ from dee import server
10
+
11
+ GOOD_RESULT = {
12
+ "primers": [{"name": "F1", "fitness": 0.8}, {"name": "R1", "fitness": 0.7}],
13
+ "has_template": True,
14
+ }
15
+
16
+
17
+ @pytest.fixture
18
+ def client():
19
+ app = server.create_app()
20
+ app.config.update(TESTING=True)
21
+ return app.test_client()
22
+
23
+
24
+ def _signed_in(monkeypatch):
25
+ monkeypatch.setattr(server._auth, "get_auth",
26
+ lambda: types.SimpleNamespace(anonymous=False, user_id="u1",
27
+ email="x@y.z", plan="free"))
28
+ # Lazy sweep is fire-and-forget; stub it so tests never touch the network.
29
+ monkeypatch.setattr(server._auth, "cleanup_expired_primer_analyses_async",
30
+ lambda *a, **k: None)
31
+
32
+
33
+ def _anon(monkeypatch):
34
+ monkeypatch.setattr(server._auth, "get_auth",
35
+ lambda: types.SimpleNamespace(anonymous=True, user_id=None,
36
+ email=None, plan="anon"))
37
+
38
+
39
+ # ─────────────────────────── Primer save ───────────────────────────
40
+ def test_primer_save_requires_signin(client, monkeypatch):
41
+ _anon(monkeypatch)
42
+ r = client.post("/api/primers/save", json={"result": GOOD_RESULT})
43
+ assert r.status_code == 403
44
+ assert r.get_json()["kind"] == "signin_required"
45
+
46
+
47
+ def test_primer_save_rejects_empty(client, monkeypatch):
48
+ _signed_in(monkeypatch)
49
+ r = client.post("/api/primers/save", json={"result": {"primers": []}})
50
+ assert r.status_code == 400
51
+
52
+
53
+ def test_primer_save_passes_through(client, monkeypatch):
54
+ _signed_in(monkeypatch)
55
+ captured = {}
56
+
57
+ def fake_save(user_id, **kw):
58
+ captured["user_id"] = user_id
59
+ captured.update(kw)
60
+ return {"ok": True, "id": "abc"}
61
+
62
+ monkeypatch.setattr(server._auth, "save_primer_analysis", fake_save)
63
+ r = client.post("/api/primers/save", json={
64
+ "label": "my set", "organism": "human", "template_len": 700,
65
+ "n_primers": 2, "result": GOOD_RESULT})
66
+ assert r.status_code == 200
67
+ assert r.get_json() == {"ok": True, "id": "abc"}
68
+ assert captured["user_id"] == "u1" # server-supplied, not client
69
+ assert captured["n_primers"] == 2
70
+ assert captured["result"]["primers"] # result forwarded intact
71
+
72
+
73
+ # ─────────────────────── Primer list / get / delete ───────────────────────
74
+ def test_primer_list_requires_signin(client, monkeypatch):
75
+ _anon(monkeypatch)
76
+ assert client.get("/api/primers/analyses").status_code == 403
77
+
78
+
79
+ def test_primer_list(client, monkeypatch):
80
+ _signed_in(monkeypatch)
81
+ monkeypatch.setattr(server._auth, "list_primer_analyses",
82
+ lambda uid: [{"id": "1", "label": "set A", "n_primers": 3}])
83
+ r = client.get("/api/primers/analyses")
84
+ assert r.status_code == 200
85
+ assert r.get_json()["analyses"][0]["label"] == "set A"
86
+
87
+
88
+ def test_primer_get_and_404(client, monkeypatch):
89
+ _signed_in(monkeypatch)
90
+ monkeypatch.setattr(server._auth, "get_primer_analysis",
91
+ lambda uid, aid: ({"id": aid, "result": GOOD_RESULT}
92
+ if aid == "ok" else None))
93
+ assert client.get("/api/primers/analyses/ok").status_code == 200
94
+ assert client.get("/api/primers/analyses/missing").status_code == 404
95
+
96
+
97
+ def test_primer_delete(client, monkeypatch):
98
+ _signed_in(monkeypatch)
99
+ monkeypatch.setattr(server._auth, "delete_primer_analysis",
100
+ lambda uid, aid: {"ok": True})
101
+ r = client.delete("/api/primers/analyses/xyz")
102
+ assert r.status_code == 200 and r.get_json()["ok"] is True
103
+
104
+
105
+ # ───────────────── DE library list + signed download ─────────────────
106
+ def test_library_list_requires_signin(client, monkeypatch):
107
+ _anon(monkeypatch)
108
+ assert client.get("/api/library").status_code == 403
109
+
110
+
111
+ def test_library_list(client, monkeypatch):
112
+ _signed_in(monkeypatch)
113
+ monkeypatch.setattr(server._auth, "list_libraries",
114
+ lambda uid: [{"id": "L1", "name": "lib", "n_variants": 96}])
115
+ r = client.get("/api/library")
116
+ assert r.status_code == 200
117
+ assert r.get_json()["libraries"][0]["n_variants"] == 96
118
+
119
+
120
+ def test_library_download_signed_url(client, monkeypatch):
121
+ _signed_in(monkeypatch)
122
+ monkeypatch.setattr(server._auth, "library_csv_url",
123
+ lambda uid, lid: ("https://example.test/signed.csv"
124
+ if lid == "L1" else None))
125
+ ok = client.get("/api/library/L1/download")
126
+ assert ok.status_code == 200 and ok.get_json()["url"].endswith("signed.csv")
127
+ assert client.get("/api/library/nope/download").status_code == 404
128
+
129
+
130
+ # ───────────────── Graceful degradation (no Supabase configured) ─────────────────
131
+ def test_save_primer_analysis_unconfigured_is_graceful(monkeypatch):
132
+ monkeypatch.setattr(server._auth, "SUPABASE_URL", "", raising=False)
133
+ monkeypatch.setattr(server._auth, "SUPABASE_SERVICE_KEY", "", raising=False)
134
+ out = server._auth.save_primer_analysis(
135
+ "u1", label="x", organism=None, template_len=10, n_primers=1,
136
+ result={"primers": [{"name": "F"}]})
137
+ assert out["ok"] is False and "error" in out