zerochat 10.30.0__tar.gz → 10.31.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.30.0
3
+ Version: 10.31.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "zerochat"
7
- version = "10.30.0"
7
+ version = "10.31.0"
8
8
  description = "Private local web client for AI models, tools and MCP services"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.30.0
3
+ Version: 10.31.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -337,6 +337,8 @@ class TokenGrant:
337
337
  if method == "zerochat/conversations/save":
338
338
  conv = params.get("conversation")
339
339
  return isinstance(conv, dict) and conv.get("id") == self.conversation_id
340
+ if method == "zerochat/conversations/save_chunk":
341
+ return params.get("conversationId") == self.conversation_id
340
342
  return False
341
343
 
342
344
 
@@ -1575,7 +1577,7 @@ def dispatch_browser(method: str, params: dict) -> RpcOutcome:
1575
1577
 
1576
1578
 
1577
1579
 
1578
- SOURCE_BACKEND_VERSION = "10.30.0"
1580
+ SOURCE_BACKEND_VERSION = "10.31.0"
1579
1581
 
1580
1582
 
1581
1583
  def _read_source_version(filename: str) -> str | None:
@@ -2802,6 +2804,12 @@ MAX_CONVERSATION_ID_LENGTH = 128
2802
2804
  MAX_CONVERSATION_TITLE_LENGTH = 256
2803
2805
  MAX_BLOB_SIZE = 50 * 1024 * 1024
2804
2806
  MAX_BLOB_HTTP_BYTES = 72 * 1024 * 1024
2807
+ CONVERSATION_UPLOAD_TTL_SECONDS = 300
2808
+ MAX_PENDING_CONVERSATION_UPLOADS = 16
2809
+ MAX_STAGED_CONVERSATION_BYTES = 64 * 1024 * 1024
2810
+ MAX_CONVERSATION_UPLOAD_CHUNKS = 512
2811
+ _UPLOAD_ID_PATTERN = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$")
2812
+ _PENDING_CONVERSATION_UPLOADS: dict[str, dict] = {}
2805
2813
  def _obfuscate_saved_api_keys(conn: sqlite3.Connection):
2806
2814
  """Las API keys de los perfiles del servidor, guardadas en claro hasta ahora, pasan a guardarse ofuscadas."""
2807
2815
  rows = conn.execute("SELECT id, api_key FROM profiles WHERE api_key != '';").fetchall()
@@ -3346,6 +3354,166 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
3346
3354
  return _row_to_conversation_header(row)
3347
3355
 
3348
3356
 
3357
+ def _validate_int_in_range(value, name: str, min_value: int, max_value: int) -> int:
3358
+ if isinstance(value, bool) or not isinstance(value, int):
3359
+ raise ValueError(f"{name} debe ser un entero")
3360
+ if value < min_value or value > max_value:
3361
+ raise ValueError(f"{name} fuera de rango ({min_value}..{max_value})")
3362
+ return value
3363
+
3364
+
3365
+ def _validate_upload_id(upload_id) -> str:
3366
+ if not isinstance(upload_id, str) or not _UPLOAD_ID_PATTERN.fullmatch(upload_id):
3367
+ raise ValueError("uploadId no válido")
3368
+ return upload_id
3369
+
3370
+
3371
+ def _purge_expired_conversation_uploads(now: float):
3372
+ expired = [
3373
+ uid for uid, entry in _PENDING_CONVERSATION_UPLOADS.items()
3374
+ if now - entry["updated_at"] > CONVERSATION_UPLOAD_TTL_SECONDS
3375
+ ]
3376
+ for uid in expired:
3377
+ del _PENDING_CONVERSATION_UPLOADS[uid]
3378
+
3379
+
3380
+ def _parse_chunk_payload(messages, message_part) -> tuple[int, list[dict] | None, tuple | None]:
3381
+ if messages is not None and message_part is not None:
3382
+ raise ValueError("No se puede combinar messages y messagePart")
3383
+ if messages is None and message_part is None:
3384
+ raise ValueError("Cada tramo debe incluir messages o messagePart")
3385
+ if messages is not None:
3386
+ if not isinstance(messages, list) or not all(isinstance(msg, dict) for msg in messages):
3387
+ raise ValueError("Los mensajes del tramo deben ser una lista de objetos")
3388
+ return len(json.dumps(messages, ensure_ascii=False).encode("utf-8")), messages, None
3389
+ if not isinstance(message_part, dict):
3390
+ raise ValueError("messagePart debe ser un objeto")
3391
+ total_parts = _validate_int_in_range(message_part.get("totalParts"), "totalParts", 1, MAX_CONVERSATION_UPLOAD_CHUNKS)
3392
+ part_index = _validate_int_in_range(message_part.get("partIndex"), "partIndex", 0, total_parts - 1)
3393
+ content = message_part.get("content")
3394
+ if not isinstance(content, str):
3395
+ raise ValueError("content de messagePart debe ser texto")
3396
+ msg_shell = message_part.get("message")
3397
+ if part_index == 0 and not isinstance(msg_shell, dict):
3398
+ raise ValueError("El primer fragmento debe incluir message")
3399
+ if part_index > 0 and msg_shell is not None:
3400
+ raise ValueError("Solo el primer fragmento debe incluir message")
3401
+ shell_bytes = len(json.dumps(msg_shell, ensure_ascii=False).encode("utf-8")) if part_index == 0 else 0
3402
+ return len(content.encode("utf-8")) + shell_bytes, None, (part_index, total_parts, content, msg_shell)
3403
+
3404
+
3405
+ def _acquire_conversation_upload_entry(
3406
+ upload_id: str,
3407
+ conv_id: str,
3408
+ chunk_index: int,
3409
+ total_chunks: int,
3410
+ chunk_bytes: int,
3411
+ part_info: tuple | None,
3412
+ now: float,
3413
+ ) -> dict:
3414
+ staged_bytes = sum(item["bytes"] for item in _PENDING_CONVERSATION_UPLOADS.values())
3415
+ if staged_bytes + chunk_bytes > MAX_STAGED_CONVERSATION_BYTES:
3416
+ raise ValueError("Se superó el límite temporal de subida de conversaciones")
3417
+ if chunk_index == 0:
3418
+ if upload_id in _PENDING_CONVERSATION_UPLOADS:
3419
+ raise ValueError("uploadId ya existe")
3420
+ if len(_PENDING_CONVERSATION_UPLOADS) >= MAX_PENDING_CONVERSATION_UPLOADS:
3421
+ raise ValueError("Demasiadas subidas de conversación en curso")
3422
+ if part_info is not None and part_info[0] != 0:
3423
+ raise ValueError("El primer fragmento de un mensaje parcial debe tener partIndex 0")
3424
+ entry = {
3425
+ "conversation_id": conv_id,
3426
+ "total_chunks": total_chunks,
3427
+ "next_index": 0,
3428
+ "messages": [],
3429
+ "partial_message": None,
3430
+ "bytes": 0,
3431
+ "updated_at": now,
3432
+ }
3433
+ _PENDING_CONVERSATION_UPLOADS[upload_id] = entry
3434
+ return entry
3435
+ entry = _PENDING_CONVERSATION_UPLOADS.get(upload_id)
3436
+ if not entry:
3437
+ raise ValueError("Subida de conversación no encontrada o caducada")
3438
+ if entry["conversation_id"] != conv_id or entry["total_chunks"] != total_chunks:
3439
+ raise ValueError("La cabecera del tramo no coincide con la subida")
3440
+ if entry["next_index"] != chunk_index:
3441
+ raise ValueError("Tramo de conversación fuera de orden")
3442
+ return entry
3443
+
3444
+
3445
+ def _apply_chunk_message_part(entry: dict, part_info: tuple):
3446
+ part_index, total_parts, content, msg_shell = part_info
3447
+ if part_index == 0:
3448
+ if entry["partial_message"] is not None:
3449
+ raise ValueError("Ya hay un mensaje parcial en curso")
3450
+ entry["partial_message"] = {
3451
+ "message": dict(msg_shell),
3452
+ "parts": [content],
3453
+ "next_part": 1,
3454
+ "total_parts": total_parts,
3455
+ }
3456
+ else:
3457
+ partial = entry["partial_message"]
3458
+ if not partial or partial["total_parts"] != total_parts or partial["next_part"] != part_index:
3459
+ raise ValueError("Fragmento de mensaje fuera de orden")
3460
+ partial["parts"].append(content)
3461
+ partial["next_part"] += 1
3462
+ partial = entry["partial_message"]
3463
+ if partial and partial["next_part"] == partial["total_parts"]:
3464
+ full_msg = dict(partial["message"])
3465
+ full_msg["content"] = "".join(partial["parts"])
3466
+ entry["messages"].append(full_msg)
3467
+ entry["partial_message"] = None
3468
+
3469
+
3470
+ def save_conversation_chunk(params: dict) -> dict:
3471
+ """Almacena temporalmente un tramo de mensajes de una conversación para su guardado atómico final."""
3472
+ if not isinstance(params, dict):
3473
+ raise ValueError("Los parámetros deben ser un objeto")
3474
+ upload_id = _validate_upload_id(params.get("uploadId"))
3475
+ conv_id = _validate_conversation_id(params.get("conversationId"))
3476
+ total_chunks = _validate_int_in_range(params.get("totalChunks"), "totalChunks", 1, MAX_CONVERSATION_UPLOAD_CHUNKS)
3477
+ chunk_index = _validate_int_in_range(params.get("chunkIndex"), "chunkIndex", 0, total_chunks - 1)
3478
+ chunk_bytes, messages, part_info = _parse_chunk_payload(params.get("messages"), params.get("messagePart"))
3479
+
3480
+ with _STORAGE_LOCK:
3481
+ now = time.monotonic()
3482
+ _purge_expired_conversation_uploads(now)
3483
+ entry = _acquire_conversation_upload_entry(
3484
+ upload_id, conv_id, chunk_index, total_chunks, chunk_bytes, part_info, now
3485
+ )
3486
+ if messages is not None:
3487
+ if entry["partial_message"] is not None:
3488
+ raise ValueError("Faltan fragmentos del mensaje parcial anterior")
3489
+ entry["messages"].extend(messages)
3490
+ elif part_info is not None:
3491
+ _apply_chunk_message_part(entry, part_info)
3492
+ entry["next_index"] = chunk_index + 1
3493
+ entry["bytes"] += chunk_bytes
3494
+ entry["updated_at"] = now
3495
+ return {"ok": True, "uploadId": upload_id, "receivedChunks": entry["next_index"]}
3496
+
3497
+
3498
+ def commit_conversation_upload(session_meta: dict, upload_id: str) -> dict:
3499
+ """Consolida atómicamente en SQLite una conversación subida por tramos."""
3500
+ if not isinstance(session_meta, dict):
3501
+ raise ValueError("Los metadatos de la conversación deben ser un objeto")
3502
+ session_id = _validate_conversation_id(session_meta.get("id"))
3503
+ clean_upload_id = _validate_upload_id(upload_id)
3504
+ with _STORAGE_LOCK:
3505
+ _purge_expired_conversation_uploads(time.monotonic())
3506
+ entry = _PENDING_CONVERSATION_UPLOADS.get(clean_upload_id)
3507
+ if not entry:
3508
+ raise ValueError("Subida de conversación no encontrada o caducada")
3509
+ if entry["conversation_id"] != session_id:
3510
+ raise ValueError("La conversación no coincide con la subida")
3511
+ if entry["next_index"] != entry["total_chunks"] or entry["partial_message"] is not None:
3512
+ raise ValueError("La subida de conversación está incompleta")
3513
+ messages = _PENDING_CONVERSATION_UPLOADS.pop(clean_upload_id)["messages"]
3514
+ return save_conversation(session_meta, messages)
3515
+
3516
+
3349
3517
  def mark_conversation_server_run(session_id: str, profile_name: str | None = None) -> bool:
3350
3518
  """Marca la conversación en SQLite como ejecutada en servidor asociándole el perfil."""
3351
3519
  try:
@@ -4858,11 +5026,22 @@ def _rpc_delete_conversations(params: dict) -> RpcOutcome:
4858
5026
  return rpc_result({"deleted": delete_conversation(params.get("id"))})
4859
5027
 
4860
5028
 
5029
+ def _rpc_save_conversation(params: dict) -> RpcOutcome:
5030
+ if not isinstance(params, dict):
5031
+ raise ValueError("Los parámetros deben ser un objeto")
5032
+ upload_id = params.get("uploadId")
5033
+ if upload_id is not None:
5034
+ if params.get("messages") is not None:
5035
+ raise ValueError("No se puede combinar uploadId y messages")
5036
+ return rpc_result({"conversation": commit_conversation_upload(params.get("conversation"), upload_id)})
5037
+ return rpc_result({"conversation": save_conversation(params.get("conversation"), params.get("messages"))})
5038
+
5039
+
4861
5040
  CONVERSATION_METHODS = {
4862
5041
  "zerochat/conversations/list": lambda _params: rpc_result({"conversations": list_conversations()}),
4863
5042
  "zerochat/conversations/get": lambda params: rpc_result({"conversation": get_conversation(params.get("id"))}),
4864
- "zerochat/conversations/save": lambda params: rpc_result(
4865
- {"conversation": save_conversation(params.get("conversation"), params.get("messages"))}),
5043
+ "zerochat/conversations/save": _rpc_save_conversation,
5044
+ "zerochat/conversations/save_chunk": lambda params: rpc_result(save_conversation_chunk(params)),
4866
5045
  "zerochat/conversations/rename": lambda params: rpc_result(
4867
5046
  {"renamed": rename_conversation(params.get("id"), params.get("title"))}),
4868
5047
  "zerochat/conversations/delete": _rpc_delete_conversations,
File without changes
File without changes
File without changes