opensees-cli 0.2.6__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/PKG-INFO +2 -2
  2. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/README.md +1 -1
  3. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/pyproject.toml +1 -1
  4. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/__init__.py +1 -1
  5. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/auth.py +90 -10
  6. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/files.py +198 -17
  7. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/main.py +4 -3
  8. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/run.py +119 -48
  9. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli.egg-info/PKG-INFO +2 -2
  10. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/tests/test_files_commands.py +8 -3
  11. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/tests/test_main_commands.py +1 -1
  12. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/tests/test_run_commands.py +104 -8
  13. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/setup.cfg +0 -0
  14. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/__main__.py +0 -0
  15. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/api.py +0 -0
  16. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/config.py +0 -0
  17. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/path_setup.py +0 -0
  18. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli/version.py +0 -0
  19. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli.egg-info/SOURCES.txt +0 -0
  20. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli.egg-info/dependency_links.txt +0 -0
  21. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli.egg-info/entry_points.txt +0 -0
  22. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli.egg-info/requires.txt +0 -0
  23. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/src/opensees_cli.egg-info/top_level.txt +0 -0
  24. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/tests/test_api.py +0 -0
  25. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/tests/test_auth_commands.py +0 -0
  26. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/tests/test_config.py +0 -0
  27. {opensees_cli-0.2.6 → opensees_cli-0.3.1}/tests/test_version_commands.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: opensees_cli
3
- Version: 0.2.6
3
+ Version: 0.3.1
4
4
  Summary: Run OpenSees simulations in the cloud from the command line.
5
5
  Author: Minjie Zhu
6
6
  License: Proprietary
@@ -115,7 +115,7 @@ ops run help
115
115
  ### `run submit` options
116
116
 
117
117
  - `file` (required positional): local path to a `.py` file (uploaded if the path exists under its filename), or a cloud path such as `model.py` or `lab/model.py`
118
- - `--timeout`, `-t`: max wall time per task in seconds (default `120`). The API requires your **monthly runtime remaining** ≥ `timeout ×` number of tasks. Runs above **900s** use Fargate when configured; otherwise the **900s** Lambda limit applies.
118
+ - `--timeout`, `-t`: max wall time per task in seconds (default `120`). Monthly usage must cover `timeout ×` number of tasks `×` RAM. Runs above **900s** use Fargate when configured; otherwise the **900s** Lambda limit applies.
119
119
  - `--wait`, `-w`: wait and stream output until completion (default: return immediately with the analysis ID on stdout; progress on stderr)
120
120
 
121
121
  Validation enforced by CLI (local uploads):
@@ -92,7 +92,7 @@ ops run help
92
92
  ### `run submit` options
93
93
 
94
94
  - `file` (required positional): local path to a `.py` file (uploaded if the path exists under its filename), or a cloud path such as `model.py` or `lab/model.py`
95
- - `--timeout`, `-t`: max wall time per task in seconds (default `120`). The API requires your **monthly runtime remaining** ≥ `timeout ×` number of tasks. Runs above **900s** use Fargate when configured; otherwise the **900s** Lambda limit applies.
95
+ - `--timeout`, `-t`: max wall time per task in seconds (default `120`). Monthly usage must cover `timeout ×` number of tasks `×` RAM. Runs above **900s** use Fargate when configured; otherwise the **900s** Lambda limit applies.
96
96
  - `--wait`, `-w`: wait and stream output until completion (default: return immediately with the analysis ID on stdout; progress on stderr)
97
97
 
98
98
  Validation enforced by CLI (local uploads):
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "opensees_cli"
7
- version = "0.2.6"
7
+ version = "0.3.1"
8
8
  description = "Run OpenSees simulations in the cloud from the command line."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,3 +1,3 @@
1
1
  """OpenSees CLI — run structural simulations in the cloud."""
2
2
 
3
- __version__ = "0.2.6"
3
+ __version__ = "0.3.1"
@@ -268,13 +268,35 @@ def _fmt_bytes_precise(n: float) -> str:
268
268
  return f"{n:.2f} GB"
269
269
 
270
270
 
271
+ def _fmt_usage(n: float) -> str:
272
+ n = float(n or 0)
273
+ if abs(n - round(n)) < 0.05:
274
+ return str(int(round(n)))
275
+ return f"{n:.1f}"
276
+
277
+
278
+ def _usage_parts(q: dict) -> tuple:
279
+ maximum = q.get("max_monthly_usage")
280
+ if maximum is None:
281
+ maximum = q.get("max_monthly_runtime", 0)
282
+ used = q.get("monthly_usage_used")
283
+ if used is None:
284
+ used = q.get("monthly_runtime_used", 0)
285
+ reserved = q.get("monthly_usage_reserved")
286
+ if reserved is None:
287
+ reserved = q.get("monthly_runtime_reserved", 0)
288
+ remaining = q.get("monthly_usage_remaining")
289
+ if remaining is None:
290
+ remaining = q.get("monthly_runtime_remaining")
291
+ if remaining is None:
292
+ remaining = max(0, float(maximum or 0) - float(used or 0) - float(reserved or 0))
293
+ return maximum or 0, used or 0, reserved or 0, remaining
294
+
295
+
271
296
  def print_quota(q: dict) -> None:
272
297
  """Print quota info to the console."""
273
- max_rt = q.get("max_monthly_runtime", 0)
274
- used = q.get("monthly_runtime_used", 0)
275
- reserved = q.get("monthly_runtime_reserved", 0)
298
+ max_rt, used, reserved, remaining = _usage_parts(q)
276
299
  committed = used + reserved
277
- remaining = q.get("monthly_runtime_remaining", 0)
278
300
  pct = (committed / max_rt * 100) if max_rt else 0
279
301
  rt_color = "green" if pct < 75 else ("yellow" if pct < 90 else "red")
280
302
 
@@ -284,37 +306,75 @@ def print_quota(q: dict) -> None:
284
306
  st_pct = (st_used / max_st * 100) if max_st else 0
285
307
  st_color = "green" if st_pct < 75 else ("yellow" if st_pct < 90 else "red")
286
308
 
309
+ shared_by = _shared_by_phrase(q.get("shared_by") or [])
310
+ share = _share_phrase(q.get("share") or "")
311
+ if shared_by:
312
+ console.print(f" {shared_by}")
313
+ elif share:
314
+ console.print(f" {share}")
287
315
  console.print(f" Concurrent tasks: {q.get('max_concurrent_runs', '-')}")
288
316
  console.print(f" Tasks/analysis: {q.get('max_tasks_per_analysis', '-')}")
289
317
  console.print(f" Max task timeout: {_fmt_duration(q['max_task_timeout']) if q.get('max_task_timeout') else '-'}")
318
+ console.print(f" Max RAM: {_fmt_bytes((q.get('max_ram_mb') or 1024) * 1024 * 1024)}")
290
319
  console.print(f" Max storage/task: {_fmt_bytes(q['max_storage_per_task']) if q.get('max_storage_per_task') else '-'}")
291
320
  if reserved > 0:
292
321
  console.print(
293
- f" Monthly runtime: [{rt_color}]{_fmt_duration(used)} settled"
294
- f" + {_fmt_duration(reserved)} in-flight[/{rt_color}]"
295
- f" / {_fmt_duration(max_rt)} ({pct:.0f}% committed)"
322
+ f" Monthly usage: [{rt_color}]{_fmt_usage(used)} settled"
323
+ f" + {_fmt_usage(reserved)} in-flight[/{rt_color}]"
324
+ f" / {_fmt_usage(max_rt)} ({pct:.0f}% committed)"
296
325
  )
297
326
  else:
298
- console.print(f" Monthly runtime: [{rt_color}]{_fmt_duration(used)}[/{rt_color}] / {_fmt_duration(max_rt)} ({pct:.0f}% used)")
299
- console.print(f" Runtime left: {_fmt_duration(remaining)}")
327
+ console.print(f" Monthly usage: [{rt_color}]{_fmt_usage(used)}[/{rt_color}] / {_fmt_usage(max_rt)} ({pct:.0f}% used)")
328
+ console.print(f" Usage left: {_fmt_usage(remaining)}")
300
329
  if q.get("next_reset_at"):
301
330
  console.print(f" Next cycle: {_to_local_date(q['next_reset_at'])}")
302
331
  else:
303
332
  console.print(" Next cycle: [dim]—[/dim]")
304
- console.print(f" Storage: [{st_color}]{_fmt_bytes(st_used)}[/{st_color}] / {_fmt_bytes(max_st)} ({st_pct:.0f}% used)")
333
+ members = q.get("storage_members") or []
334
+ if members:
335
+ sharing = ", ".join(
336
+ f"{member.get('email') or 'user'} {_fmt_bytes(member.get('storage_used') or 0)}"
337
+ for member in members
338
+ )
339
+ console.print(f" Sharing users: {sharing}")
340
+ console.print(f" Own storage: {_fmt_bytes(q.get('storage_own') or 0)}")
341
+ console.print(f" Total storage: [{st_color}]{_fmt_bytes(st_used)}[/{st_color}] / {_fmt_bytes(max_st)} ({st_pct:.0f}% used)")
342
+ else:
343
+ console.print(f" Storage: [{st_color}]{_fmt_bytes(st_used)}[/{st_color}] / {_fmt_bytes(max_st)} ({st_pct:.0f}% used)")
305
344
  st_left_str = _fmt_bytes(st_remaining)
306
345
  if st_left_str == _fmt_bytes(max_st) and st_remaining < max_st:
307
346
  st_left_str = _fmt_bytes_precise(st_remaining)
308
347
  console.print(f" Storage left: {st_left_str}")
348
+ dropbox = q.get("dropbox") or {}
349
+ if dropbox.get("linked"):
350
+ used_bytes = int(dropbox.get("used") or 0)
351
+ allocated = int(dropbox.get("allocated") or 0)
352
+ if dropbox.get("space_error"):
353
+ console.print(f" Dropbox: [yellow]{dropbox['space_error']}[/yellow]")
354
+ elif allocated:
355
+ console.print(f" Dropbox: {_fmt_bytes(used_bytes)} / {_fmt_bytes(allocated)}")
356
+ else:
357
+ console.print(f" Dropbox: {_fmt_bytes(used_bytes)} used")
358
+ if dropbox.get("folder_error"):
359
+ console.print(f" Files on Dropbox: [yellow]{dropbox['folder_error']}[/yellow]")
360
+ elif "folder_bytes" in dropbox:
361
+ console.print(f" Files on Dropbox: {_fmt_bytes(int(dropbox.get('folder_bytes') or 0))}")
309
362
 
310
363
 
311
364
  def quota_to_json_obj(q: dict) -> Dict[str, Any]:
312
365
  """Quota fields as a plain dict (shared by ``ops status --json``)."""
313
366
  return {
367
+ "share": _share_phrase(q.get("share") or ""),
368
+ "shared_by": _shared_by_phrase(q.get("shared_by") or []),
314
369
  "max_concurrent_runs": q.get("max_concurrent_runs"),
315
370
  "max_tasks_per_analysis": q.get("max_tasks_per_analysis"),
316
371
  "max_task_timeout": q.get("max_task_timeout"),
372
+ "max_ram_mb": q.get("max_ram_mb") if q.get("max_ram_mb") is not None else 1024,
317
373
  "max_storage_per_task": q.get("max_storage_per_task"),
374
+ "max_monthly_usage": _usage_parts(q)[0],
375
+ "monthly_usage_used": _usage_parts(q)[1],
376
+ "monthly_usage_reserved": _usage_parts(q)[2],
377
+ "monthly_usage_remaining": _usage_parts(q)[3],
318
378
  "max_monthly_runtime": q.get("max_monthly_runtime"),
319
379
  "monthly_runtime_used": q.get("monthly_runtime_used"),
320
380
  "monthly_runtime_reserved": q.get("monthly_runtime_reserved"),
@@ -322,7 +382,10 @@ def quota_to_json_obj(q: dict) -> Dict[str, Any]:
322
382
  "next_reset_at": _to_local_date(q["next_reset_at"]) if q.get("next_reset_at") else None,
323
383
  "max_monthly_storage": q.get("max_monthly_storage"),
324
384
  "storage_used": q.get("storage_used"),
385
+ "storage_own": q.get("storage_own"),
386
+ "storage_members": q.get("storage_members") or [],
325
387
  "storage_remaining": max(0, (q.get("max_monthly_storage") or 0) - (q.get("storage_used") or 0)),
388
+ "dropbox": q.get("dropbox") or {"linked": False},
326
389
  }
327
390
 
328
391
 
@@ -331,6 +394,17 @@ def format_quota_json(q: dict) -> str:
331
394
  return json.dumps(quota_to_json_obj(q), indent=2) + "\n"
332
395
 
333
396
 
397
+ def _share_phrase(email: str) -> str:
398
+ """``Share email's quota`` when this account spends someone else's quota."""
399
+ return f"Share {email}'s quota" if email else ""
400
+
401
+
402
+ def _shared_by_phrase(emails) -> str:
403
+ """``Shared by a, b`` when other accounts spend this primary's quota."""
404
+ names = [str(email) for email in emails if email]
405
+ return "Shared by " + ", ".join(names) if names else ""
406
+
407
+
334
408
  def print_me(
335
409
  r: Dict[str, Any],
336
410
  *,
@@ -344,6 +418,8 @@ def print_me(
344
418
  console.print(f" Email: [bold]{r.get('email', '')}[/bold]")
345
419
  console.print(f" Admin: {'[yellow]yes[/yellow]' if r.get('is_admin') else 'no'}")
346
420
  console.print(f" Enabled: {'[green]yes[/green]' if r.get('is_enabled') else '[red]no[/red]'}")
421
+ console.print(f" Org: {r.get('org') or ''}")
422
+ console.print(f" Primary: {'yes' if r.get('is_primary') else 'no'}")
347
423
  signup_raw = r.get("signup_at") or r.get("created_at")
348
424
  if signup_raw:
349
425
  console.print(f" Signup time: {_to_local(signup_raw)}")
@@ -368,6 +444,8 @@ def format_status_plain(
368
444
  f"email: {r.get('email', '')}",
369
445
  f"admin: {'yes' if r.get('is_admin') else 'no'}",
370
446
  f"enabled: {'yes' if r.get('is_enabled') else 'no'}",
447
+ f"org: {r.get('org') or ''}",
448
+ f"primary: {'yes' if r.get('is_primary') else 'no'}",
371
449
  ]
372
450
  signup_raw = r.get("signup_at") or r.get("created_at")
373
451
  lines.append(f"signup_time: {_to_local(signup_raw) if signup_raw else ''}")
@@ -393,6 +471,8 @@ def format_status_json(
393
471
  "email": r.get("email") or "",
394
472
  "admin": bool(r.get("is_admin")),
395
473
  "enabled": bool(r.get("is_enabled")),
474
+ "org": r.get("org") or "",
475
+ "primary": bool(r.get("is_primary")),
396
476
  "signup_time": _to_local(signup_raw) if signup_raw else None,
397
477
  "last_login": _to_local(r["last_login_at"]) if r.get("last_login_at") else None,
398
478
  "last_active": _to_local(r["last_activity_at"]) if r.get("last_activity_at") else None,
@@ -65,7 +65,7 @@ def list_files(
65
65
  is_flag=True,
66
66
  ),
67
67
  ):
68
- """List files. With FOLDER, only show files under that path. Prints nothing when empty (non-JSON)."""
68
+ """List files. With FOLDER, only show files under that path. An empty list still prints the table."""
69
69
  try:
70
70
  items = _files_list_items(folder)
71
71
  # Older APIs ignore ?folder= — filter locally so the CLI still works.
@@ -95,9 +95,6 @@ def list_files(
95
95
  typer.echo(json.dumps(obj, indent=2).rstrip("\n"))
96
96
  return
97
97
 
98
- if not items:
99
- return
100
-
101
98
  table = Table(show_header=True)
102
99
  table.add_column("Path")
103
100
  table.add_column("Size", justify="right")
@@ -143,8 +140,8 @@ def _collect_upload_targets(local_path: Path, folder: Optional[str]) -> List[Tup
143
140
  return []
144
141
 
145
142
 
146
- def _upload_one(local: Path, remote: str) -> int:
147
- """Upload a single file. Returns bytes uploaded."""
143
+ def _upload_one(local: Path, remote: str) -> bool:
144
+ """Upload a single file. True when the bytes were written to the cloud library."""
148
145
  import httpx
149
146
  file_size = local.stat().st_size
150
147
  content_type = "text/x-python" if remote.endswith(".py") else "application/octet-stream"
@@ -155,16 +152,36 @@ def _upload_one(local: Path, remote: str) -> int:
155
152
  raise
156
153
 
157
154
  file_bytes = local.read_bytes()
158
- resp = httpx.put(
159
- r["upload_url"],
160
- content=file_bytes,
161
- headers={"Content-Type": content_type},
162
- timeout=60.0,
163
- follow_redirects=True,
164
- )
155
+ ticket = r.get("dropbox_upload")
156
+ if ticket:
157
+ import json as _json
158
+ arg = _json.dumps({
159
+ "path": ticket["path"],
160
+ "mode": "overwrite",
161
+ "autorename": False,
162
+ "mute": True,
163
+ })
164
+ resp = httpx.post(
165
+ ticket["url"],
166
+ content=file_bytes,
167
+ headers={
168
+ "Authorization": f"Bearer {ticket['token']}",
169
+ "Dropbox-API-Arg": arg,
170
+ "Content-Type": "application/octet-stream",
171
+ },
172
+ timeout=120.0,
173
+ )
174
+ else:
175
+ resp = httpx.put(
176
+ r["upload_url"],
177
+ content=file_bytes,
178
+ headers={"Content-Type": content_type},
179
+ timeout=60.0,
180
+ follow_redirects=True,
181
+ )
165
182
  if not (200 <= resp.status_code < 300):
166
183
  raise api.ApiError(f"Upload failed (HTTP {resp.status_code})", resp.status_code)
167
- return len(file_bytes)
184
+ return ticket is None
168
185
 
169
186
 
170
187
  def _resolve_download_targets(files: List[dict], pattern: str) -> List[dict]:
@@ -199,9 +216,9 @@ def _resolve_download_targets(files: List[dict], pattern: str) -> List[dict]:
199
216
  @app.command()
200
217
  def upload(
201
218
  local_paths: List[Path] = typer.Argument(..., help="Local file(s) or folder(s) to upload (globs are expanded by the shell)"),
202
- folder: Optional[str] = typer.Option(None, "--folder", "-f", help="Remote folder to upload into (e.g. --folder inputs)"),
219
+ folder: Optional[str] = typer.Option(None, "--folder", "-f", help="Remote folder to upload into (required unless every file is already under a folder)"),
203
220
  ):
204
- """Upload a file or folder to the cloud file system."""
221
+ """Upload a file or folder. Every file must land inside a cloud folder."""
205
222
  missing = [p for p in local_paths if not p.exists()]
206
223
  if missing:
207
224
  for p in missing:
@@ -214,6 +231,11 @@ def upload(
214
231
  if not targets:
215
232
  console.print("[red]Nothing to upload.[/red]")
216
233
  raise typer.Exit(1)
234
+ root_files = [remote for _, remote in targets if "/" not in remote]
235
+ if root_files:
236
+ console.print("[red]Upload into a folder.[/red]")
237
+ console.print(" [dim]ops files upload model.py --folder lab[/dim]")
238
+ raise typer.Exit(1)
217
239
 
218
240
  try:
219
241
  listed = api.get("/files/list")
@@ -242,6 +264,7 @@ def upload(
242
264
 
243
265
  total_bytes = sum(f.stat().st_size for f, _ in targets)
244
266
  multi = len(targets) > 1
267
+ wrote_cloud = False
245
268
 
246
269
  with Progress(
247
270
  "[progress.description]{task.description}",
@@ -256,7 +279,8 @@ def upload(
256
279
  fsize = local.stat().st_size
257
280
  task = progress.add_task(remote, total=fsize)
258
281
  try:
259
- _upload_one(local, remote)
282
+ if _upload_one(local, remote):
283
+ wrote_cloud = True
260
284
  progress.advance(task, fsize)
261
285
  if overall is not None:
262
286
  progress.advance(overall, fsize)
@@ -266,6 +290,13 @@ def upload(
266
290
  raise typer.Exit(1)
267
291
  continue
268
292
 
293
+ if wrote_cloud:
294
+ try:
295
+ api.post("/files/complete", {})
296
+ except api.ApiError as e:
297
+ console.print(f"[red]Uploaded, but storage was not updated: {e.message}[/red]")
298
+ raise typer.Exit(1)
299
+
269
300
  if multi:
270
301
  console.print(f"[green]Uploaded {len(targets)} files ({_fmt_bytes(total_bytes)})[/green]")
271
302
  else:
@@ -427,3 +458,153 @@ def delete(
427
458
  console.print(f"[green]Deleted {targets[0]['path']}[/green]")
428
459
  else:
429
460
  console.print(f"[green]Deleted {deleted}/{total} file(s)[/green]")
461
+
462
+
463
+ dropbox_app = typer.Typer(help="Link a Dropbox account. Files and results are saved in Apps/OpenSeesCloud.")
464
+ app.add_typer(dropbox_app, name="dropbox")
465
+
466
+
467
+ def _listen_for_dropbox_code(redirect_uri: str, open_url: str, timeout: float = 180.0) -> dict:
468
+ """Listen on the callback, then open Dropbox so the redirect is not missed."""
469
+ import threading
470
+ import webbrowser
471
+ from http.server import BaseHTTPRequestHandler, HTTPServer
472
+ from urllib.parse import parse_qs, urlparse
473
+
474
+ parsed = urlparse(redirect_uri)
475
+ host = parsed.hostname or "127.0.0.1"
476
+ port = parsed.port or 53682
477
+ path = parsed.path or "/callback"
478
+ box: dict = {}
479
+
480
+ class _Handler(BaseHTTPRequestHandler):
481
+ def do_GET(self): # noqa: N802
482
+ incoming = urlparse(self.path)
483
+ if incoming.path != path:
484
+ self.send_error(404)
485
+ return
486
+ box["query"] = parse_qs(incoming.query)
487
+ body = b"<html><body><p>Dropbox linked. You can close this window.</p></body></html>"
488
+ self.send_response(200)
489
+ self.send_header("Content-Type", "text/html")
490
+ self.send_header("Content-Length", str(len(body)))
491
+ self.end_headers()
492
+ self.wfile.write(body)
493
+
494
+ def log_message(self, fmt: str, *args) -> None:
495
+ return
496
+
497
+ try:
498
+ server = HTTPServer((host, port), _Handler)
499
+ except OSError as exc:
500
+ raise api.ApiError(f"Could not listen on {host}:{port} ({exc})") from exc
501
+ thread = threading.Thread(target=server.handle_request, daemon=True)
502
+ thread.start()
503
+ webbrowser.open(open_url)
504
+ thread.join(timeout)
505
+ server.server_close()
506
+ return box.get("query") or {}
507
+
508
+
509
+ @dropbox_app.command("link")
510
+ def dropbox_link():
511
+ """Open Dropbox login and copy the existing library into Apps/OpenSeesCloud."""
512
+ try:
513
+ started = api.post("/files/dropbox/start", {})
514
+ except api.ApiError as e:
515
+ console.print(f"[red]{e.message}[/red]")
516
+ raise typer.Exit(1)
517
+
518
+ console.print("Opening Dropbox. Approve access to the OpenSeesCloud folder.")
519
+ console.print(f"[dim]{started['authorize_url']}[/dim]")
520
+ try:
521
+ query = _listen_for_dropbox_code(started["redirect_uri"], started["authorize_url"])
522
+ except api.ApiError as e:
523
+ console.print(f"[red]{e.message}[/red]")
524
+ raise typer.Exit(1)
525
+ error = (query.get("error_description") or query.get("error") or [""])[0]
526
+ code = (query.get("code") or [""])[0]
527
+ state = (query.get("state") or [""])[0]
528
+ if error or not code:
529
+ console.print(f"[red]Dropbox login did not finish.{(' ' + error) if error else ''}[/red]")
530
+ raise typer.Exit(1)
531
+ if state and state != started.get("state"):
532
+ console.print("[red]Dropbox login did not match this session.[/red]")
533
+ raise typer.Exit(1)
534
+ try:
535
+ done = api.post("/files/dropbox/finish", {"code": code, "state": started["state"]})
536
+ except api.ApiError as e:
537
+ console.print(f"[red]{e.message}[/red]")
538
+ raise typer.Exit(1)
539
+
540
+ if done.get("copy_error"):
541
+ console.print(f"[yellow]Linked. The copy stopped: {done['copy_error']}[/yellow]")
542
+ console.print("[dim]Run ops files dropbox copy to try the remaining files.[/dim]")
543
+ else:
544
+ console.print(f"[green]Linked. Copied {done.get('copied', 0)} file(s) to Dropbox.[/green]")
545
+
546
+ total = int(done.get("total") or 0)
547
+ if total <= 0:
548
+ return
549
+ delete_cloud = typer.confirm("Delete the cloud copies of these existing files?", default=False)
550
+ try:
551
+ api.post("/files/dropbox/cloud", {"keep": not delete_cloud})
552
+ except api.ApiError as e:
553
+ console.print(f"[red]{e.message}[/red]")
554
+ raise typer.Exit(1)
555
+ if delete_cloud:
556
+ console.print("[green]Cloud copies deleted. They no longer count toward storage.[/green]")
557
+ else:
558
+ console.print("[dim]Cloud copies kept. They count toward storage.[/dim]")
559
+
560
+
561
+ @dropbox_app.command("copy")
562
+ def dropbox_copy():
563
+ """Copy the cloud library into Dropbox again. Existing Dropbox files are overwritten."""
564
+ try:
565
+ done = api.post("/files/dropbox/copy", {})
566
+ except api.ApiError as e:
567
+ console.print(f"[red]{e.message}[/red]")
568
+ raise typer.Exit(1)
569
+ console.print(f"[green]Copied {done.get('copied', 0)} file(s) to Dropbox.[/green]")
570
+
571
+
572
+ @dropbox_app.command("status")
573
+ def dropbox_status():
574
+ """Show Dropbox plan space and the bytes stored in Apps/OpenSeesCloud."""
575
+ try:
576
+ info = api.get("/files/dropbox")
577
+ except api.ApiError as e:
578
+ console.print(f"[red]{e.message}[/red]")
579
+ raise typer.Exit(1)
580
+ if not info.get("linked"):
581
+ console.print("Dropbox is not linked.")
582
+ console.print("[dim]ops files dropbox link[/dim]")
583
+ return
584
+ if info.get("space_error"):
585
+ console.print(f"[yellow]{info['space_error']}[/yellow]")
586
+ else:
587
+ used = int(info.get("used") or 0)
588
+ allocated = int(info.get("allocated") or 0)
589
+ if allocated:
590
+ console.print(f"Dropbox: {_fmt_bytes(used)} / {_fmt_bytes(allocated)}")
591
+ else:
592
+ console.print(f"Dropbox: {_fmt_bytes(used)} used")
593
+ if info.get("folder_error"):
594
+ console.print(f"[yellow]{info['folder_error']}[/yellow]")
595
+ elif "folder_bytes" in info:
596
+ console.print(f"Files on Dropbox: {_fmt_bytes(int(info.get('folder_bytes') or 0))}")
597
+
598
+
599
+ @dropbox_app.command("unlink")
600
+ def dropbox_unlink():
601
+ """Disconnect Dropbox. Files already in Dropbox stay there."""
602
+ if not typer.confirm("Disconnect Dropbox? Files already there stay in Dropbox.", default=False):
603
+ console.print("[dim]Cancelled.[/dim]")
604
+ raise typer.Exit(0)
605
+ try:
606
+ api.post("/files/dropbox/unlink", {})
607
+ except api.ApiError as e:
608
+ console.print(f"[red]{e.message}[/red]")
609
+ raise typer.Exit(1)
610
+ console.print("[green]Dropbox disconnected. New files and results stay in the cloud.[/green]")
@@ -67,7 +67,7 @@ def _open_sees_py_version_str() -> str:
67
67
 
68
68
  app = typer.Typer(
69
69
  name="ops",
70
- help="Run OpenSees simulations in the cloud.",
70
+ help=f"Run OpenSees simulations in the cloud. CLI {__version__}.",
71
71
  add_completion=False,
72
72
  invoke_without_command=True,
73
73
  context_settings={"help_option_names": ["-h", "--help"]},
@@ -110,7 +110,7 @@ def _print_help() -> None:
110
110
  console.print(" [bold]ops status[/bold] Account details and quota (--json / -j for JSON output)")
111
111
  console.print()
112
112
  console.print("[bold]ops run[/bold]\n")
113
- console.print(" [bold]submit[/bold] <file> Submit an analysis (--count N for parallel)")
113
+ console.print(" [bold]submit[/bold] <file> Submit an analysis (local file needs --folder)")
114
114
  console.print(" [bold]follow[/bold] <id> Stream live output from a running task")
115
115
  console.print(" [bold]list[/bold] List recent analyses")
116
116
  console.print(" [bold]status[/bold] <id> [range] Analysis summary or per-task status")
@@ -118,13 +118,14 @@ def _print_help() -> None:
118
118
  console.print(" [bold]stats[/bold] <id> [range] Task execution stats (runtime, RAM)")
119
119
  console.print(" [bold]data[/bold] <id> [range] List or download task data files")
120
120
  console.print(" [bold]cancel[/bold] <id> Cancel an analysis or task")
121
- console.print(" [bold]clear[/bold] [id] Delete analysis data (by ID or time range)")
121
+ console.print(" [bold]clear[/bold] [id] Remove the saved output log (by ID or time range)")
122
122
  console.print()
123
123
  console.print("[bold]ops files[/bold]\n")
124
124
  console.print(" [bold]list[/bold] List uploaded files (--json / -j)")
125
125
  console.print(" [bold]upload[/bold] <path> Upload a file or folder")
126
126
  console.print(" [bold]download[/bold] <path> Download file(s) or folder; quote globs: '*.csv'")
127
127
  console.print(" [bold]delete[/bold] <path> Delete a file or folder")
128
+ console.print(" [bold]dropbox[/bold] Link Dropbox, show space, or disconnect")
128
129
  console.print()
129
130
  console.print("[bold]ops auth[/bold]\n")
130
131
  console.print(" [bold]change-password[/bold] Change your password")
@@ -1,5 +1,7 @@
1
1
  """Simulation analysis CLI commands."""
2
2
 
3
+ from __future__ import annotations
4
+
3
5
  import json
4
6
  import random
5
7
  import re
@@ -58,10 +60,12 @@ Use --count to run multiple tasks in parallel.
58
60
 
59
61
  \b
60
62
  Examples:
61
- ops run submit model.py Submit (returns analysis ID immediately)
62
- ops run submit model.py --wait Wait and stream output until completion
63
- ops run submit model.py --count 100 100-task parallel analysis
64
- ops run submit model.py -t 300 Set 300s timeout
63
+ ops run submit model.py --folder lab Upload model.py to lab/, then submit
64
+ ops run submit model.py --folder lab --wait
65
+ ops run submit model.py --folder lab --count 100
66
+ ops run submit model.py --folder lab -t 300
67
+ ops run submit model.py --folder lab --ram 2G
68
+ ops run submit lab/model.py Submit a file already in the cloud
65
69
  ops run follow abc12345 Follow analysis until done (progress only; then use output)
66
70
  ops run list List this month's analyses (auto-expands if empty)
67
71
  ops run list --week This week's analyses
@@ -484,18 +488,41 @@ def _parse_params(
484
488
  return merged or None
485
489
 
486
490
 
491
+ def _parse_timeout_seconds(value: str) -> int:
492
+ """Parse a submit timeout. A bare number is seconds. Units: m, h, d, w."""
493
+ text = str(value).strip().lower().replace(" ", "")
494
+ if not text:
495
+ raise ValueError("Invalid timeout. Use seconds, or 30m, 2h, 1d, 1w.")
496
+ mult = {"w": 7 * 24 * 3600, "d": 24 * 3600, "h": 3600, "m": 60, "s": 1}
497
+ if re.fullmatch(r"\d+(?:\.\d+)?", text):
498
+ seconds = int(round(float(text)))
499
+ else:
500
+ parts = list(re.finditer(r"(\d+(?:\.\d+)?)([wdhms])", text))
501
+ if not parts or "".join(part.group(0) for part in parts) != text:
502
+ raise ValueError("Invalid timeout. Use seconds, or 30m, 2h, 1d, 1w.")
503
+ seconds = int(round(sum(float(part.group(1)) * mult[part.group(2)] for part in parts)))
504
+ if seconds < 1:
505
+ raise ValueError("timeout must be at least 1 second.")
506
+ return seconds
507
+
508
+
509
+ def _print_adjustment(submit_response: dict, key: str, *, notices_to_stderr: bool = False) -> None:
510
+ """Print a server notice when a requested limit was reduced to the account maximum."""
511
+ msg = (submit_response.get(key) or {}).get("message")
512
+ if not msg:
513
+ return
514
+ if notices_to_stderr:
515
+ Console(stderr=True).print(f"[yellow]{msg}[/yellow]")
516
+ else:
517
+ console.print(f"[yellow]{msg}[/yellow]")
518
+
519
+
487
520
  def _effective_task_timeout(
488
521
  submit_response: dict, requested: int, *, notices_to_stderr: bool = False
489
522
  ) -> int:
490
523
  """Use server effective per-task timeout when quota caps the request; print notice."""
491
- adj = submit_response.get("timeout_adjustment") or {}
492
- msg = adj.get("message")
493
- if msg:
494
- if notices_to_stderr:
495
- Console(stderr=True).print(f"[yellow]{msg}[/yellow]")
496
- else:
497
- console.print(f"[yellow]{msg}[/yellow]")
498
- eff = adj.get("effective")
524
+ _print_adjustment(submit_response, "timeout_adjustment", notices_to_stderr=notices_to_stderr)
525
+ eff = (submit_response.get("timeout_adjustment") or {}).get("effective")
499
526
  if eff is not None:
500
527
  return int(eff)
501
528
  return requested
@@ -507,11 +534,17 @@ def submit(
507
534
  ...,
508
535
  help="Local .py path (uploaded if present) or cloud path (e.g. model.py or lab/model.py)",
509
536
  ),
510
- timeout: int = typer.Option(
511
- 120,
537
+ timeout: str = typer.Option(
538
+ "120",
512
539
  "--timeout",
513
540
  "-t",
514
- help="Max runtime per task in seconds (may be capped to your per-task quota; monthly runtime still applies)",
541
+ help="Max runtime per task. A number is seconds. Also 30m, 2h, 1d, 1w. Capped to your per-task quota.",
542
+ ),
543
+ ram: str = typer.Option(
544
+ "1G",
545
+ "--ram",
546
+ "-r",
547
+ help="RAM for this run (1G, 512M, or megabytes). Capped to your account maximum. Default: 1G",
515
548
  ),
516
549
  count: int = typer.Option(1, "--count", "-n", help="Number of parallel tasks (default 1)"),
517
550
  wait: bool = typer.Option(
@@ -522,29 +555,43 @@ def submit(
522
555
  ),
523
556
  param: Optional[List[str]] = typer.Option(None, "--param", "-p", help="Parameter as key=value (repeatable). Script: from openseespy.cli_params import cli_params"),
524
557
  params_file: Optional[Path] = typer.Option(None, "--params-file", help="JSON file with parameters (object of key-value pairs)."),
558
+ folder: Optional[str] = typer.Option(
559
+ None,
560
+ "--folder",
561
+ "-f",
562
+ help="Cloud folder for a local file (required). The file is uploaded there before the run.",
563
+ ),
525
564
  ):
526
565
  """Submit a simulation analysis.
527
566
 
528
567
  \b
529
- If a local path exists, it is uploaded under its filename (e.g. ``model.py``).
530
- Otherwise the path is treated as an existing cloud file path.
568
+ A local file must be given with --folder. It is uploaded to that cloud
569
+ folder, then the run uses that cloud path.
570
+ A path that is not a local file is an existing cloud path, and that path
571
+ must include a folder (for example ``lab/model.py``).
531
572
  Use --count to run multiple tasks in parallel for parameter studies.
532
573
  By default returns immediately (prints bare analysis ID to stdout). Use --wait / -w to stream until completion.
533
574
  Use -p to pass parameters; load in script with: from openseespy.cli_params import cli_params
534
575
 
535
576
  \b
536
577
  Examples:
537
- ops run submit model.py Local upload, or cloud file if not local
538
- ops run submit model.py --wait Wait and stream until completion
539
- ops run submit model.py --count 100 100-task parallel analysis
540
- ops run submit model.py -t 300 Set 300s timeout
541
- ops run submit model.py -p E=3000 -p A=10.0
542
- ops run submit model.py --params-file study.json
543
- ops run submit lab/model.py Cloud path (no local file)
578
+ ops run submit model.py --folder lab Upload model.py to lab/, then run it
579
+ ops run submit model.py --folder lab --wait
580
+ ops run submit model.py --folder lab --count 100
581
+ ops run submit model.py --folder lab -t 300
582
+ ops run submit model.py --folder lab --ram 2G
583
+ ops run submit model.py --folder lab -p E=3000 -p A=10.0
584
+ ops run submit model.py --folder lab --params-file study.json
585
+ ops run submit lab/model.py Cloud path (already uploaded)
544
586
  """
545
587
  if count < 1:
546
588
  console.print("[red]--count must be at least 1.[/red]")
547
589
  raise typer.Exit(1)
590
+ try:
591
+ timeout_seconds = _parse_timeout_seconds(timeout)
592
+ except ValueError as exc:
593
+ console.print(f"[red]{exc}[/red]")
594
+ raise typer.Exit(1)
548
595
 
549
596
  # When not waiting, human-readable output goes to stderr so that
550
597
  # capturing stdout (e.g. rid=$(ops run submit ...)) gives only the ID.
@@ -561,22 +608,40 @@ def submit(
561
608
  if not local.name.endswith(".py"):
562
609
  out.print("[red]Only .py files are supported.[/red]")
563
610
  raise typer.Exit(1)
564
- entry_filename = local.name
565
- out.print(f"Uploading [bold]{local}[/bold] as [bold]{entry_filename}[/bold]...")
611
+ cloud_folder = (folder or "").strip().strip("/")
612
+ if not cloud_folder or any(part in ("", ".", "..") for part in cloud_folder.split("/")):
613
+ out.print("[red]A folder is required for a local file.[/red]")
614
+ out.print(" [dim]ops run submit model.py --folder lab[/dim]")
615
+ raise typer.Exit(1)
616
+ entry_filename = f"{cloud_folder}/{local.name}"
617
+ out.print(f"Uploading [bold]{local}[/bold] to [bold]{entry_filename}[/bold]...")
618
+ from opensees_cli.files import _upload_one
566
619
  try:
567
- upload = api.post("/files/upload", {"path": entry_filename, "content_type": "text/x-python"})
568
- api.upload_file(upload["upload_url"], local.read_bytes(), content_type="text/x-python")
620
+ wrote_cloud = _upload_one(local, entry_filename)
569
621
  except api.ApiError as e:
570
- out.print(f"[red]Upload failed: {e.message}[/red]")
622
+ if str(e.message).startswith("Upload failed"):
623
+ out.print(f"[red]{e.message}[/red]")
624
+ raise typer.Exit(1)
625
+ if wrote_cloud:
626
+ try:
627
+ api.post("/files/complete", {})
628
+ except api.ApiError as e:
629
+ out.print(f"[red]Uploaded, but storage was not updated: {e.message}[/red]")
630
+ raise typer.Exit(1)
631
+ else:
632
+ entry_filename = entry_filename.strip().strip("/")
633
+ if "/" not in entry_filename or any(part in ("", ".", "..") for part in entry_filename.split("/")):
634
+ out.print("[red]A cloud file must be inside a folder.[/red]")
635
+ out.print(" [dim]ops run submit lab/model.py[/dim]")
571
636
  raise typer.Exit(1)
572
637
  if not entry_filename.endswith(".py"):
573
638
  out.print("[red]Only .py files are supported.[/red]")
574
639
  raise typer.Exit(1)
575
640
 
576
641
  count_label = f", {count} tasks" if count > 1 else ""
577
- out.print(f"Submitting [bold]{entry_filename}[/bold] (timeout {timeout}s{count_label})...")
642
+ out.print(f"Submitting [bold]{entry_filename}[/bold] (timeout {timeout_seconds}s, ram {ram}{count_label})...")
578
643
 
579
- submit_body: dict = {"filename": entry_filename, "timeout": timeout}
644
+ submit_body: dict = {"filename": entry_filename, "timeout": timeout_seconds, "ram": ram}
580
645
  if count > 1:
581
646
  submit_body["count"] = count
582
647
  if cli_params:
@@ -614,7 +679,8 @@ def submit(
614
679
  out.print(f"[red]{e.message}[/red]")
615
680
  raise typer.Exit(1)
616
681
 
617
- effective_timeout = _effective_task_timeout(r, timeout, notices_to_stderr=not wait)
682
+ effective_timeout = _effective_task_timeout(r, timeout_seconds, notices_to_stderr=not wait)
683
+ _print_adjustment(r, "ram_adjustment", notices_to_stderr=not wait)
618
684
 
619
685
  analysis_id = r.get("analysis_id") or r.get("run_id", "")
620
686
  task_id = r.get("task_id") or r.get("run_id", "")
@@ -949,24 +1015,25 @@ def clear(
949
1015
  after: Optional[str] = typer.Option(None, "--after", "-a", help="Clear analyses created after this date (YYYY-MM-DD or ISO 8601)"),
950
1016
  yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation prompt"),
951
1017
  ):
952
- """Delete completed analyses and their data.
1018
+ """Remove the saved output log for completed runs.
953
1019
 
954
1020
  \b
955
- Clear a single analysis by ID, or clear analyses in a time range.
1021
+ The run stays in the list. The short stdout tail and the result stay.
1022
+ Script files in Dropbox stay. A linked run's combined log is removed too.
956
1023
 
957
1024
  Examples:
958
- ops run clear abc12345 Clear an analysis (all tasks)
959
- ops run clear --before 2025-01-01 Clear analyses before a date
960
- ops run clear --after 2025-06-01 Clear analyses after a date
1025
+ ops run clear abc12345 Clear one run's output log
1026
+ ops run clear --before 2025-01-01 Clear logs before a date
1027
+ ops run clear --after 2025-06-01 Clear logs after a date
961
1028
  ops run clear --before 2025-03-01 --after 2025-01-01
962
1029
  ops run clear --before 2025-01-01 -y Skip confirmation
963
1030
  """
964
1031
  if not id and not before and not after:
965
1032
  console.print("Provide an analysis/task ID, --before, --after, or a combination.\n")
966
1033
  console.print("[dim]Examples:[/dim]")
967
- console.print(" [dim]ops run clear abc12345[/dim] Clear an analysis")
968
- console.print(" [dim]ops run clear --before 2025-01-01[/dim] Clear before a date")
969
- console.print(" [dim]ops run clear --after 2025-06-01[/dim] Clear after a date")
1034
+ console.print(" [dim]ops run clear abc12345[/dim] Clear one run's output log")
1035
+ console.print(" [dim]ops run clear --before 2025-01-01[/dim] Clear logs before a date")
1036
+ console.print(" [dim]ops run clear --after 2025-06-01[/dim] Clear logs after a date")
970
1037
  console.print(" [dim]ops run clear --before 2025-03-01 --after 2025-01-01[/dim]")
971
1038
  console.print(" [dim]ops run clear --before 2025-01-01 -y[/dim] Skip confirmation")
972
1039
  raise typer.Exit(0)
@@ -987,7 +1054,7 @@ def clear(
987
1054
  desc = f"analysis {id[:8]} ({total_tasks} task{'s' if total_tasks > 1 else ''})" if total_tasks > 1 else f"task {id[:8]}"
988
1055
 
989
1056
  if not yes:
990
- if not typer.confirm(f"\nClear {desc}? This cannot be undone"):
1057
+ if not typer.confirm(f"\nClear the output log for {desc}? The run stays in the list"):
991
1058
  console.print("[dim]Cancelled.[/dim]")
992
1059
  raise typer.Exit(0)
993
1060
 
@@ -998,7 +1065,7 @@ def clear(
998
1065
  raise typer.Exit(1)
999
1066
 
1000
1067
  cleared = r.get("cleared", 0)
1001
- console.print(f"[green]Cleared {cleared} task{'s' if cleared != 1 else ''}.[/green]")
1068
+ console.print(f"[green]Cleared the output log for {cleared} run{'s' if cleared != 1 else ''}.[/green]")
1002
1069
  return
1003
1070
 
1004
1071
  # Time range
@@ -1023,7 +1090,7 @@ def clear(
1023
1090
  console.print("[dim]No analyses matched.[/dim]")
1024
1091
  raise typer.Exit(0)
1025
1092
 
1026
- table = Table(show_header=True, title=f"Analyses to clear ({len(targets)})")
1093
+ table = Table(show_header=True, title=f"Output logs to clear ({len(targets)})")
1027
1094
  table.add_column("Analysis", style="dim", max_width=8)
1028
1095
  table.add_column("Status")
1029
1096
  table.add_column("File")
@@ -1040,7 +1107,7 @@ def clear(
1040
1107
  console.print(table)
1041
1108
 
1042
1109
  if not yes:
1043
- if not typer.confirm(f"\nClear {len(targets)} analysis/analyses? This cannot be undone"):
1110
+ if not typer.confirm(f"\nClear the output log for {len(targets)} run(s)? The runs stay in the list"):
1044
1111
  console.print("[dim]Cancelled.[/dim]")
1045
1112
  raise typer.Exit(0)
1046
1113
 
@@ -1055,7 +1122,7 @@ def clear(
1055
1122
  except api.ApiError:
1056
1123
  pass
1057
1124
 
1058
- console.print(f"[green]Cleared {total_cleared} task{'s' if total_cleared != 1 else ''}.[/green]")
1125
+ console.print(f"[green]Cleared the output log for {total_cleared} run{'s' if total_cleared != 1 else ''}.[/green]")
1059
1126
 
1060
1127
 
1061
1128
  def _week_range(week: int) -> tuple[datetime, datetime]:
@@ -1822,7 +1889,7 @@ def list_analyses(
1822
1889
  table.add_column("File")
1823
1890
  table.add_column("Tasks")
1824
1891
  table.add_column("Runtime", justify="right")
1825
- table.add_column("Size", justify="right")
1892
+ table.add_column("Output size", justify="right")
1826
1893
  table.add_column("Created")
1827
1894
 
1828
1895
  for a in items:
@@ -2017,7 +2084,7 @@ def _print_status(r: dict) -> None:
2017
2084
  f"[dim](total across all tasks)[/dim]"
2018
2085
  )
2019
2086
  if r.get("size"):
2020
- console.print(f" Size: {_fmt_bytes(r['size'])}")
2087
+ console.print(f" Output size: {_fmt_bytes(r['size'])}")
2021
2088
  if r.get("created_at"):
2022
2089
  console.print(f" Created: {_to_local(r['created_at'])}")
2023
2090
 
@@ -2035,7 +2102,7 @@ def _print_status(r: dict) -> None:
2035
2102
  rt = t.get("runtime_seconds")
2036
2103
  if rt is not None and rt >= 0:
2037
2104
  line += f" {rt:.2f}s"
2038
- err = t.get("error_message")
2105
+ err = t.get("error_message") or t.get("dropbox_notice")
2039
2106
  if err:
2040
2107
  line += f" [red]{err[:50]}[/red]"
2041
2108
  console.print(line)
@@ -2068,10 +2135,14 @@ def _print_status(r: dict) -> None:
2068
2135
  rt = r.get("runtime_seconds")
2069
2136
  if rt is not None and rt >= 0:
2070
2137
  console.print(f" Runtime: {rt:.2f}s")
2138
+ if r.get("size"):
2139
+ console.print(f" Output size: {_fmt_bytes(r['size'])}")
2071
2140
  if r.get("return_code") is not None:
2072
2141
  console.print(f" Return: {r['return_code']}")
2073
2142
  if r.get("error_message"):
2074
2143
  console.print(f" Error: [red]{r['error_message']}[/red]")
2144
+ if r.get("dropbox_notice"):
2145
+ console.print(f" Dropbox: [yellow]{r['dropbox_notice']}[/yellow]")
2075
2146
 
2076
2147
 
2077
2148
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: opensees_cli
3
- Version: 0.2.6
3
+ Version: 0.3.1
4
4
  Summary: Run OpenSees simulations in the cloud from the command line.
5
5
  Author: Minjie Zhu
6
6
  License: Proprietary
@@ -115,7 +115,7 @@ ops run help
115
115
  ### `run submit` options
116
116
 
117
117
  - `file` (required positional): local path to a `.py` file (uploaded if the path exists under its filename), or a cloud path such as `model.py` or `lab/model.py`
118
- - `--timeout`, `-t`: max wall time per task in seconds (default `120`). The API requires your **monthly runtime remaining** ≥ `timeout ×` number of tasks. Runs above **900s** use Fargate when configured; otherwise the **900s** Lambda limit applies.
118
+ - `--timeout`, `-t`: max wall time per task in seconds (default `120`). Monthly usage must cover `timeout ×` number of tasks `×` RAM. Runs above **900s** use Fargate when configured; otherwise the **900s** Lambda limit applies.
119
119
  - `--wait`, `-w`: wait and stream output until completion (default: return immediately with the analysis ID on stdout; progress on stderr)
120
120
 
121
121
  Validation enforced by CLI (local uploads):
@@ -53,7 +53,7 @@ class TestFilesUpload:
53
53
  "upload_url": "https://s3.example.com/presigned-put?sig=abc"
54
54
  })
55
55
  mock_router.add_any_url("PUT", status=200)
56
- result = cli_runner.invoke(app, ["files", "upload", str(tmp_file)])
56
+ result = cli_runner.invoke(app, ["files", "upload", str(tmp_file), "--folder", "lab"])
57
57
  assert result.exit_code == 0
58
58
  assert "Uploaded" in result.output
59
59
 
@@ -64,12 +64,17 @@ class TestFilesUpload:
64
64
 
65
65
  def test_upload_overwrite_declined(self, cli_runner, logged_in_creds, patch_httpx, mock_router, tmp_file):
66
66
  mock_router.add("GET", "/prod/files/list", json={
67
- "files": [{"path": tmp_file.name, "size": 100, "last_modified": "2025-01-01T00:00:00Z"}]
67
+ "files": [{"path": f"lab/{tmp_file.name}", "size": 100, "last_modified": "2025-01-01T00:00:00Z"}]
68
68
  })
69
- result = cli_runner.invoke(app, ["files", "upload", str(tmp_file)], input="n\n")
69
+ result = cli_runner.invoke(app, ["files", "upload", str(tmp_file), "--folder", "lab"], input="n\n")
70
70
  assert result.exit_code == 0
71
71
  assert "Cancelled" in result.output
72
72
 
73
+ def test_upload_requires_folder(self, cli_runner, logged_in_creds, patch_httpx, mock_router, tmp_file):
74
+ result = cli_runner.invoke(app, ["files", "upload", str(tmp_file)])
75
+ assert result.exit_code == 1
76
+ assert "folder" in result.output.lower()
77
+
73
78
 
74
79
  class TestFilesDownload:
75
80
  def test_download_single_file(self, cli_runner, logged_in_creds, patch_httpx, mock_router, tmp_path):
@@ -56,7 +56,7 @@ class TestStatus:
56
56
  assert "OpenSeesPy:" in out
57
57
  assert "CLI version:" not in out
58
58
  assert "Concurrent tasks" in out
59
- assert "Monthly runtime" in out
59
+ assert "Monthly usage" in out
60
60
 
61
61
  def test_status_json(self, cli_runner, logged_in_creds, patch_httpx, mock_router):
62
62
  mock_router.add("GET", "/prod/run/version", json={"open_sees_py_version": "3.7.0.0"})
@@ -1,5 +1,6 @@
1
1
  """Tests for ops run subcommands + quota/submit-lock scenarios."""
2
2
 
3
+ import json
3
4
  from unittest.mock import patch
4
5
 
5
6
  import pytest
@@ -21,7 +22,7 @@ class TestSubmit:
21
22
  "stdout_url": "",
22
23
  "result_url": "",
23
24
  })
24
- result = cli_runner.invoke(app, ["run", "submit", "Truss.py"])
25
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py"])
25
26
  assert result.exit_code == 0
26
27
  assert "aaa11111-0000-0000-0000-000000000000" in result.stdout
27
28
  assert "Submitting" in result.output
@@ -38,26 +39,121 @@ class TestSubmit:
38
39
  "message": "Per-task timeout was reduced from 120s to 20s (your account maximum is 20s).",
39
40
  },
40
41
  })
41
- result = cli_runner.invoke(app, ["run", "submit", "Truss.py"])
42
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py"])
42
43
  assert result.exit_code == 0
43
44
  assert "reduced from 120s to 20s" in result.output
44
45
  assert "aaa44444" in result.stdout
45
46
 
47
+ def test_submit_sends_default_ram(self, cli_runner, logged_in_creds, patch_httpx, mock_router):
48
+ mock_router.add("POST", "/prod/run/submit", json={
49
+ "analysis_id": "aaa55555",
50
+ "task_id": "ttt55555",
51
+ "total_tasks": 1,
52
+ })
53
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py"])
54
+ assert result.exit_code == 0
55
+ calls = [c for c in mock_router.calls if c["method"] == "POST" and "/run/submit" in c["url"]]
56
+ body = json.loads(calls[0]["content"])
57
+ assert body["ram"] == "1G"
58
+ assert body["timeout"] == 120
59
+
60
+ def test_submit_timeout_units(self, cli_runner, logged_in_creds, patch_httpx, mock_router):
61
+ mock_router.add("POST", "/prod/run/submit", json={
62
+ "analysis_id": "aaa88888",
63
+ "task_id": "ttt88888",
64
+ "total_tasks": 1,
65
+ })
66
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py", "-t", "2h"])
67
+ assert result.exit_code == 0
68
+ calls = [c for c in mock_router.calls if c["method"] == "POST" and "/run/submit" in c["url"]]
69
+ assert json.loads(calls[0]["content"])["timeout"] == 7200
70
+ assert "timeout 7200s" in result.output
71
+
72
+ def test_submit_timeout_units_rejected(self, cli_runner, logged_in_creds, patch_httpx, mock_router):
73
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py", "-t", "2x"])
74
+ assert result.exit_code == 1
75
+ assert "Invalid timeout" in result.output
76
+
77
+ def test_submit_ram_option(self, cli_runner, logged_in_creds, patch_httpx, mock_router):
78
+ mock_router.add("POST", "/prod/run/submit", json={
79
+ "analysis_id": "aaa66666",
80
+ "task_id": "ttt66666",
81
+ "total_tasks": 1,
82
+ })
83
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py", "--ram", "2G"])
84
+ assert result.exit_code == 0
85
+ calls = [c for c in mock_router.calls if c["method"] == "POST" and "/run/submit" in c["url"]]
86
+ body = json.loads(calls[0]["content"])
87
+ assert body["ram"] == "2G"
88
+ assert "ram 2G" in result.output
89
+
90
+ def test_submit_ram_adjustment_notice(self, cli_runner, logged_in_creds, patch_httpx, mock_router):
91
+ mock_router.add("POST", "/prod/run/submit", json={
92
+ "analysis_id": "aaa77777",
93
+ "task_id": "ttt77777",
94
+ "total_tasks": 1,
95
+ "ram_adjustment": {
96
+ "requested": 2048,
97
+ "effective": 1024,
98
+ "message": "RAM was reduced from 2G to 1G (your account maximum is 1G).",
99
+ },
100
+ })
101
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py", "--ram", "2G"])
102
+ assert result.exit_code == 0
103
+ assert "reduced from 2G to 1G" in result.output
104
+ assert "aaa77777" in result.stdout
105
+
46
106
  def test_submit_local_file(self, cli_runner, logged_in_creds, patch_httpx, mock_router, tmp_file):
47
107
  """Local file upload + submit."""
48
108
  mock_router.add("POST", "/prod/files/upload", json={
49
109
  "upload_url": "https://s3.example.com/presigned-put?sig=abc"
50
110
  })
51
111
  mock_router.add_any_url("PUT", status=200)
112
+ mock_router.add("POST", "/prod/files/complete", json={"library_bytes": 1})
52
113
  mock_router.add("POST", "/prod/run/submit", json={
53
114
  "analysis_id": "aaa22222",
54
115
  "task_id": "ttt22222",
55
116
  "total_tasks": 1,
56
117
  })
57
- result = cli_runner.invoke(app, ["run", "submit", str(tmp_file)])
118
+ result = cli_runner.invoke(app, ["run", "submit", str(tmp_file), "--folder", "lab"])
58
119
  assert result.exit_code == 0
59
120
  assert "Uploading" in result.output
60
121
  assert "aaa22222" in result.stdout
122
+ upload_calls = [c for c in mock_router.calls if c["method"] == "POST" and "/files/upload" in c["url"]]
123
+ assert upload_calls
124
+ assert b"lab/" in upload_calls[0]["content"]
125
+
126
+ def test_submit_local_file_to_dropbox(self, cli_runner, logged_in_creds, patch_httpx, mock_router, tmp_file):
127
+ """A linked account uploads the local script with the Dropbox ticket."""
128
+ mock_router.add("POST", "/prod/files/upload", json={
129
+ "path": "lab/model.py",
130
+ "dropbox_upload": {
131
+ "url": "https://content.dropboxapi.com/2/files/upload",
132
+ "token": "access-token",
133
+ "path": "/lab/model.py",
134
+ },
135
+ })
136
+ mock_router.add_any_url("POST", status=200)
137
+ mock_router.add("POST", "/prod/run/submit", json={
138
+ "analysis_id": "aaa33333",
139
+ "task_id": "ttt33333",
140
+ "total_tasks": 1,
141
+ })
142
+ result = cli_runner.invoke(app, ["run", "submit", str(tmp_file), "--folder", "lab"])
143
+ assert result.exit_code == 0, result.output
144
+ assert "aaa33333" in result.stdout
145
+ dropbox_calls = [c for c in mock_router.calls if "content.dropboxapi.com" in c["url"]]
146
+ assert dropbox_calls
147
+
148
+ def test_submit_local_file_requires_folder(self, cli_runner, logged_in_creds, patch_httpx, mock_router, tmp_file):
149
+ result = cli_runner.invoke(app, ["run", "submit", str(tmp_file)])
150
+ assert result.exit_code == 1
151
+ assert "folder" in result.output.lower()
152
+
153
+ def test_submit_cloud_root_rejected(self, cli_runner, logged_in_creds, patch_httpx, mock_router):
154
+ result = cli_runner.invoke(app, ["run", "submit", "Truss.py"])
155
+ assert result.exit_code == 1
156
+ assert "folder" in result.output.lower()
61
157
 
62
158
  def test_submit_count_zero(self, cli_runner, logged_in_creds, patch_httpx, mock_router):
63
159
  result = cli_runner.invoke(app, ["run", "submit", "model.py", "--count", "0"])
@@ -72,7 +168,7 @@ class TestSubmitQuota:
72
168
  "error": "Another submission in progress",
73
169
  "code": "submit_locked",
74
170
  })
75
- result = cli_runner.invoke(app, ["run", "submit", "Truss.py"])
171
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py"])
76
172
  assert result.exit_code == 1
77
173
  assert "submission" in result.output.lower() or "Another" in result.output
78
174
 
@@ -81,7 +177,7 @@ class TestSubmitQuota:
81
177
  "error": "Monthly runtime quota exceeded",
82
178
  "code": "quota_runtime",
83
179
  })
84
- result = cli_runner.invoke(app, ["run", "submit", "Truss.py"])
180
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py"])
85
181
  assert result.exit_code == 1
86
182
  assert "quota" in result.output.lower() or "runtime" in result.output.lower()
87
183
 
@@ -90,7 +186,7 @@ class TestSubmitQuota:
90
186
  "error": "Storage quota exceeded",
91
187
  "code": "quota_storage",
92
188
  })
93
- result = cli_runner.invoke(app, ["run", "submit", "Truss.py"])
189
+ result = cli_runner.invoke(app, ["run", "submit", "lab/Truss.py"])
94
190
  assert result.exit_code == 1
95
191
 
96
192
  def test_partial_concurrent_confirm(self, cli_runner, logged_in_creds, patch_httpx, mock_router):
@@ -133,7 +229,7 @@ class TestSubmitQuota:
133
229
  mock_router.handle = routing_handle
134
230
  result = cli_runner.invoke(
135
231
  app,
136
- ["run", "submit", "Truss.py", "--count", "10"],
232
+ ["run", "submit", "lab/Truss.py", "--count", "10"],
137
233
  input="y\n",
138
234
  )
139
235
  assert result.exit_code == 0
@@ -149,7 +245,7 @@ class TestSubmitQuota:
149
245
  })
150
246
  result = cli_runner.invoke(
151
247
  app,
152
- ["run", "submit", "Truss.py", "--count", "10"],
248
+ ["run", "submit", "lab/Truss.py", "--count", "10"],
153
249
  input="n\n",
154
250
  )
155
251
  assert result.exit_code == 0
File without changes