Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat(chat): per-message Copy / Retry / Delete actions (#4659) (#4689)

LearningCircuit06e731b63aa3
diff --git a/changelog.d/4659.feature.md b/changelog.d/4659.feature.md
new file mode 100644
index 0000000000..af73a3aa37
--- /dev/null
+++ b/changelog.d/4659.feature.md
@@ -0,0 +1 @@
+Add per-message **Copy**, **Retry**, and **Delete** actions to chat — the standard ChatGPT/Claude.ai hover-icon pattern. Retry replaces the failed turn and re-submits the same query as a fresh research run; Delete removes the user message, research, and any assistant response for that turn. The History page also gains a Copy-query button on each card and the rerun button is now shown for failed/suspended researches too (previously only successful runs had it).
diff --git a/src/local_deep_research/chat/routes.py b/src/local_deep_research/chat/routes.py
index 8c712d0f64..2f4694fc58 100644
--- a/src/local_deep_research/chat/routes.py
+++ b/src/local_deep_research/chat/routes.py
@@ -11,6 +11,7 @@ Provides endpoints for:
import unicodedata
import uuid
from datetime import datetime, timedelta, UTC
+from typing import Any, Dict, List
from flask import Blueprint, request, jsonify, session
from loguru import logger
from sqlalchemy import update as sa_update
@@ -18,6 +19,8 @@ from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from .service import (
ArchiveBlockedError,
+ AttemptInProgress,
+ AttemptNotFound,
ChatService,
ChatSessionNotFound,
DB_EXCEPTIONS,
@@ -187,6 +190,321 @@ def _cleanup_chat_send_rows(
)
+class ChatSpawnError(Exception):
+ """Raised by ``_spawn_chat_research`` to signal a mapped HTTP failure.
+
+ Carries the HTTP status code, an error string for the response body,
+ and optional extra fields merged into the JSON payload (e.g.
+ ``active_research_id`` for the 409 path). Both ``send_message`` and
+ ``retry_attempt`` catch this and translate to a ``jsonify(...)`` with
+ the same shape, keeping the spawn path single-sourced.
+ """
+
+ def __init__(self, status_code: int, error: str, **extra):
+ super().__init__(error)
+ self.status_code = status_code
+ self.error = error
+ self.extra = extra
+
+
+def _spawn_chat_research(
+ username: str,
+ session_id: str,
+ content: str,
+ settings_snapshot: Dict[str, Any],
+ research_context: Dict[str, Any],
+ messages: List[Dict[str, Any]],
+ service: "ChatService",
+ research_mode: str = "quick",
+) -> tuple[str, str]:
+ """Atomically write the user message + IN_PROGRESS research row, then
+ spawn the research worker.
+
+ Single-sources the spawn path shared by ``send_message`` (new chat
+ turn) and ``retry_attempt`` (delete failed turn, re-submit same
+ content). Returns ``(research_id, message_id)`` on success.
+
+ Pre-requisites the CALLER must satisfy before invoking:
+ - Session exists and is active (``ChatService.get_session`` passed).
+ - Per-session in-progress guard passed (no other live research).
+ - Per-user concurrent cap not exceeded.
+
+ Failure modes (mapped to ``ChatSpawnError``):
+ - 400: malformed numeric settings (``iterations`` / ``questions``).
+ - 404: session was deleted between caller's existence check and
+ this helper's atomic write.
+ - 409: race against the partial unique index
+ ``ux_research_history_chat_session_in_progress`` (two concurrent
+ sends both passed the per-session guard), or
+ ``DuplicateResearchError`` from ``start_research_process`` (live
+ thread already owns the id).
+ - 429: ``SystemAtCapacityError`` from ``start_research_process``
+ (cap filled between caller's check and spawn).
+
+ Raises ``ChatSpawnError`` only; never returns ``None``. The caller
+ catches once and translates to ``jsonify`` + status.
+ """
+ # Parse numeric search settings up-front. A malformed value (a
+ # non-numeric string in the user's settings DB) must return a clean
+ # 400 HERE — before the atomic write below commits the user message
+ # + IN_PROGRESS research row. Mirrors the original send_message
+ # ordering rationale.
+ try:
+ iterations = int(
+ settings_snapshot.get("search.iterations", {}).get("value", 3)
+ )
+ questions = int(
+ settings_snapshot.get("search.questions_per_iteration", {}).get(
+ "value", 1
+ )
+ )
+ except (ValueError, TypeError):
+ raise ChatSpawnError(
+ 400,
+ "Invalid numeric value in search settings "
+ "(iterations / questions_per_iteration).",
+ )
+
+ research_id = str(uuid.uuid4())
+
+ # ---- Atomic write: user message + research row in ONE transaction ----
+ # Closes the orphan window: any IntegrityError or concurrent-delete on
+ # the research insert rolls back the user message too. The
+ # UPDATE...RETURNING inside insert_message_in_db doubles as the
+ # authoritative "session-still-exists" check; if the session was
+ # deleted between the caller's existence check and now, a ValueError
+ # surfaces with "not found" and we map it to 404.
+ try:
+ with get_user_db_session(username) as db_session:
+ message_id = service.insert_message_in_db(
+ db_session,
+ session_id=session_id,
+ role="user",
+ content=content,
+ message_type="query" if len(messages) == 0 else "followup",
+ )
+
+ created_at = datetime.now(UTC).isoformat()
+ research_meta = {
+ "submission": {
+ "chat_session_id": session_id,
+ "message_id": message_id,
+ "research_mode": research_mode,
+ },
+ }
+ research = ResearchHistory(
+ id=research_id,
+ query=content,
+ mode=research_mode,
+ status=ResearchStatus.IN_PROGRESS.value,
+ created_at=created_at,
+ progress_log=[{"time": created_at, "progress": 0}],
+ research_meta=research_meta,
+ chat_session_id=session_id,
+ )
+ db_session.add(research)
+
+ # Count this research toward the per-user concurrent cap.
+ # Added in the SAME transaction as the research row so the
+ # IntegrityError rollback below undoes both.
+ import threading
+
+ db_session.add(
+ UserActiveResearch(
+ username=username,
+ research_id=research_id,
+ status=ResearchStatus.IN_PROGRESS,
+ thread_id=str(threading.current_thread().ident),
+ settings_snapshot=settings_snapshot,
+ )
+ )
+
+ try:
+ db_session.commit()
+ except IntegrityError:
+ # Two near-simultaneous POSTs both passed the per-session
+ # guard; the partial unique index on (chat_session_id)
+ # WHERE status='in_progress' (migration 0010) catches the
+ # loser here. Rolling back the transaction also undoes the
+ # user-message INSERT and the message_count increment.
+ db_session.rollback()
+ logger.warning(
+ f"Concurrent in-progress research race for chat "
+ f"{session_id[:8]}..."
+ )
+ raise ChatSpawnError(
+ 409,
+ "Research already in progress on this chat session.",
+ )
+ except ValueError as exc:
+ # ``insert_message_in_db`` raises ValueError("not found") when
+ # the session row was deleted between the existence check and
+ # the UPDATE...RETURNING.
+ if "not found" in str(exc).lower():
+ raise ChatSpawnError(404, "Session not found")
+ raise
+ # ---- end atomic write ----
+
+ # Get user password for metrics writes inside the worker thread.
+ pw = get_user_password(username)
+
+ model_provider = settings_snapshot.get("llm.provider", {}).get("value", "")
+ model = settings_snapshot.get("llm.model", {}).get("value", "")
+ search_engine = settings_snapshot.get("search.tool", {}).get("value", "")
+ custom_endpoint = settings_snapshot.get("llm.openai_endpoint.url", {}).get(
+ "value"
+ )
+ user_strategy = settings_snapshot.get("search.search_strategy", {}).get(
+ "value", "langgraph-agent"
+ )
+
+ # For follow-up messages, use the contextual follow-up strategy
+ # which wraps the user's preferred strategy as a delegate.
+ if research_context.get("is_multi_turn"):
+ strategy = "enhanced-contextual-followup"
+ research_context["delegate_strategy"] = user_strategy
+ else:
+ strategy = user_strategy
+
+ # Spawn the worker thread. ``DuplicateResearchError`` and
+ # ``SystemAtCapacityError`` inherit from ``Exception`` (not
+ # RuntimeError) so they are NOT in ROUTE_EXCEPTIONS and would
+ # otherwise escape to a generic 500 — leaving the user message +
+ # research row we just committed as orphans. Catch them here, undo
+ # our side effects via ``_cleanup_chat_send_rows``, and re-raise as
+ # ``ChatSpawnError`` for the caller to translate.
+ try:
+ start_research_process(
+ research_id,
+ content,
+ research_mode,
+ run_research_process,
+ username=username,
+ user_password=pw,
+ model_provider=model_provider,
+ model=model,
+ search_engine=search_engine,
+ custom_endpoint=custom_endpoint,
+ strategy=strategy,
+ iterations=iterations,
+ questions_per_iteration=questions,
+ research_context=research_context,
+ chat_session_id=session_id,
+ chat_message_id=message_id,
+ settings_snapshot=settings_snapshot,
+ )
+ except DuplicateResearchError:
+ logger.warning(
+ f"DuplicateResearchError on chat spawn for "
+ f"{research_id[:8]}... (chat {session_id[:8]}...)"
+ )
+ _cleanup_chat_send_rows(
+ username, research_id, message_id, session_id, "duplicate"
+ )
+ raise ChatSpawnError(
+ 409, "Research already in progress on this chat session."
+ )
+ except SystemAtCapacityError:
+ logger.warning(
+ f"SystemAtCapacityError on chat spawn for "
+ f"{research_id[:8]}... (chat {session_id[:8]}...)"
+ )
+ _cleanup_chat_send_rows(
+ username, research_id, message_id, session_id, "capacity"
+ )
+ raise ChatSpawnError(
+ 429, "Server is at research capacity. Please retry shortly."
+ )
+
+ logger.info(
+ f"Started chat research {research_id[:8]}... for chat "
+ f"{session_id[:8]}..."
+ )
+ return research_id, message_id
+
+
+def _chat_spawn_response(exc: ChatSpawnError):
+ """Translate a ChatSpawnError into the (jsonify, status) tuple the
+ Flask route returns.
+
+ Both ``send_message`` and ``retry_attempt`` shape errors identically,
+ so this lives once. ``exc.extra`` (e.g. ``active_research_id``) is
+ merged into the JSON body when present.
+ """
+ payload = {"success": False, "error": exc.error}
+ payload.update(exc.extra)
+ return jsonify(payload), exc.status_code
+
+
+# ============================================================================
+# Concurrency-guard helpers shared by send_message + retry_attempt
+# ============================================================================
+
+
+def _enforce_chat_session_research_slot(
+ cap_db, username: str, session_id: str
+) -> tuple[str, int] | None:
+ """Reject send/retry when this chat session or user is at capacity.
+
+ Runs inside the caller's ``cap_db`` transaction so the stale-row
+ reclaims it performs are visible to the count check below it.
+
+ Returns ``(error_message, http_status)`` when the request should be
+ rejected, else ``None``.
+
+ Two checks:
+ 1. Per-session guard: at most one live research per chat session.
+ Mirrors the same check in send_message's inline block
+ (chat/routes.py:925-941 in the pre-refactor layout).
+ 2. Per-user global cap: at most ``app.max_concurrent_researches``
+ researches per user across ALL sessions. Mirrors
+ research_routes.start_research.
+
+ DOES NOT include the stale-row reclaim sweep — the caller does that
+ first via ``reclaim_stale_user_active_research`` so the count check
+ sees accurate numbers.
+ """
+ # Per-session guard. Note: this fires for ANY in-progress research
+ # on the session, INCLUDING the target research on a retry path.
+ # Retry routes must therefore ensure the target is not in-progress
+ # (typically via delete_attempt's AttemptInProgress semantics)
+ # BEFORE calling this.
+ existing_session_research = (
+ cap_db.query(ResearchHistory)
+ .filter_by(
+ chat_session_id=session_id,
+ status=ResearchStatus.IN_PROGRESS,
+ )
+ .first()
+ )
+ if existing_session_research:
+ return (
+ "Research already in progress on this chat session. "
+ "Stop it before sending a new message.",
+ 409,
+ )
+
+ active_count = (
+ cap_db.query(UserActiveResearch)
+ .filter_by(
+ username=username,
+ status=ResearchStatus.IN_PROGRESS,
+ )
+ .count()
+ )
+ max_concurrent = SettingsManager(db_session=cap_db).get_setting(
+ "app.max_concurrent_researches", 3
+ )
+ if active_count >= max_concurrent:
+ return (
+ f"Concurrent research limit reached ({active_count}/"
+ f"{max_concurrent}). Wait for an existing research to finish.",
+ 429,
+ )
+
+ return None
+
+
# ============================================================================
# Page Routes
# ============================================================================
@@ -1002,265 +1320,344 @@ def send_message(session_id):
research_context = context_manager.build_research_context(
current_query=content
)
- research_id = str(uuid.uuid4())
-
- # Parse numeric search settings up-front. A malformed value
- # (a non-numeric string in the user's settings DB) must
- # return a clean 400 HERE — before the atomic write below
- # commits the user message + IN_PROGRESS research row. If the
- # int() cast ran after the commit (as it used to, down in the
- # research-dispatch block), the ValueError would propagate as
- # an unhandled 500 with those rows already committed, orphaning
- # them and soft-bricking the session via the per-session 409
- # guard.
+
+ # Atomically insert user message + IN_PROGRESS research row,
+ # then spawn the worker. All failure modes (400 malformed
+ # settings, 404 session-deleted-race, 409 concurrent /
+ # duplicate, 429 at-capacity) surface as ChatSpawnError and
+ # are translated by ``_chat_spawn_response`` so the response
+ # shape stays single-sourced across send_message and
+ # retry_attempt.
try:
- iterations = int(
- settings_snapshot.get("search.iterations", {}).get(
- "value", 3
- )
- )
- questions = int(
- settings_snapshot.get(
- "search.questions_per_iteration", {}
- ).get("value", 1)
+ research_id, message_id = _spawn_chat_research(
+ username,
+ session_id,
+ content,
+ settings_snapshot,
+ research_context,
+ messages,
+ service,
+ research_mode=research_mode,
)
- except (ValueError, TypeError):
- return jsonify(
- {
- "success": False,
- "error": (
- "Invalid numeric value in search settings "
- "(iterations / questions_per_iteration)."
+ except ChatSpawnError as exc:
+ return _chat_spawn_response(exc)
+ else:
+ # trigger_research=False: persist the user message without
+ # spawning a research run. Mirrors the original send_message
+ # shape — the message lands even when research is suppressed.
+ try:
+ with get_user_db_session(username) as db_session:
+ message_id = service.insert_message_in_db(
+ db_session,
+ session_id=session_id,
+ role="user",
+ content=content,
+ message_type=(
+ "query" if len(messages) == 0 else "followup"
),
- }
- ), 400
+ )
+ db_session.commit()
+ except ValueError as exc:
+ if "not found" in str(exc).lower():
+ return jsonify(
+ {"success": False, "error": "Session not found"}
+ ), 404
+ raise
+ research_id = None
+
+ return jsonify(
+ {
+ "success": True,
+ "message_id": message_id,
+ "session_id": session_id,
+ "research_id": research_id,
+ "research_mode": research_mode,
+ }
+ )
+
+ except ROUTE_EXCEPTIONS:
+ logger.exception("Error sending chat message")
+ return jsonify(
+ {
+ "success": False,
+ "error": "Failed to send message",
+ }
+ ), 500
- # ---- Atomic write: user message + research row in ONE transaction ----
- # Closes the orphan window: any IntegrityError or
- # concurrent-delete on the research insert rolls back the user
- # message too. The UPDATE...RETURNING inside
- # insert_message_in_db doubles as the authoritative
- # "session-still-exists" check; if the session was deleted
- # between the get_session call above and now, a ValueError
- # surfaces with "not found" and we map it to 404.
+
+# ============================================================================
+# Per-attempt API Routes (delete + retry a single chat turn)
+# ============================================================================
+
+
+@chat_bp.route(
+ "/api/chat/sessions/<session_id>/attempts/<research_id>",
+ methods=["DELETE"],
+)
+@login_required
+# Per-user keying, like the other state-changing chat routes. Caps bulk
+# delete attempts that the global limiter alone left under-constrained.
[email protected]("30 per minute", key_func=_get_api_user_key)
+def delete_attempt(session_id, research_id):
+ """Delete a single chat attempt (user message + research + response).
+
+ Refuses with 409 if the target research is IN_PROGRESS and its worker
+ thread is alive — the client must Stop it first (or wait for it to
+ fail naturally). Stale IN_PROGRESS rows whose thread is dead are
+ reclaimed and deleted.
+ """
+ try:
+ username = session.get("username")
+ service = ChatService(username)
try:
- with get_user_db_session(username) as db_session:
- message_id = service.insert_message_in_db(
- db_session,
- session_id=session_id,
- role="user",
- content=content,
- message_type="query" if len(messages) == 0 else "followup",
- )
+ service.delete_attempt(session_id, research_id)
+ except AttemptNotFound:
+ return jsonify(
+ {"success": False, "error": "Attempt not found"}
+ ), 404
+ except AttemptInProgress:
+ return jsonify(
+ {
+ "success": False,
+ "error": (
+ "Research is in progress. Stop it before deleting "
+ "the attempt."
+ ),
+ "active_research_id": research_id,
+ }
+ ), 409
- if trigger_research:
- created_at = datetime.now(UTC).isoformat()
- research_meta = {
- "submission": {
- "chat_session_id": session_id,
- "message_id": message_id,
- "research_mode": research_mode,
- },
- }
- research = ResearchHistory(
- id=research_id,
- query=content,
- mode=research_mode,
- status=ResearchStatus.IN_PROGRESS.value,
- created_at=created_at,
- progress_log=[{"time": created_at, "progress": 0}],
- research_meta=research_meta,
- chat_session_id=session_id,
- )
- db_session.add(research)
-
- # Count this research toward the per-user concurrent
- # cap. Mirrors research_routes.start_research — without a
- # UserActiveResearch row, chat research is invisible to
- # the cap (queried at the top of this handler AND by the
- # UI start path), letting multiple chat tabs bypass it.
- # Added in the SAME transaction as the research row so the
- # IntegrityError rollback below undoes both. Removed on
- # spawn failure by _cleanup_chat_send_rows, and on normal
- # completion by the cleanup_completed_research middleware
- # (keyed on is_research_active(research_id), which covers
- # chat and non-chat research alike).
- import threading
-
- db_session.add(
- UserActiveResearch(
- username=username,
- research_id=research_id,
- status=ResearchStatus.IN_PROGRESS,
- thread_id=str(threading.current_thread().ident),
- settings_snapshot=settings_snapshot,
- )
- )
+ return jsonify({"success": True})
- try:
- db_session.commit()
- except IntegrityError:
- # Two near-simultaneous POSTs both passed the
- # per-session guard; the partial unique index on
- # (chat_session_id) WHERE status='in_progress'
- # (migration 0010) catches the loser here.
- # Rolling back the transaction also undoes the
- # user-message INSERT and the message_count
- # increment — no orphan.
- db_session.rollback()
+ except ROUTE_EXCEPTIONS:
+ logger.exception("Error deleting chat attempt")
+ return jsonify(
+ {"success": False, "error": "Failed to delete attempt"}
+ ), 500
+
+
+@chat_bp.route(
+ "/api/chat/sessions/<session_id>/attempts/<research_id>/retry",
+ methods=["POST"],
+)
+@login_required
+# Same per-minute cap as send_message: retry spawns a full research run,
+# so it shares the spawn budget rather than getting a separate one (else
+# alternating send/retry would let a user exceed the intended rate).
[email protected]("10 per minute", key_func=_get_api_user_key)
+def retry_attempt(session_id, research_id):
+ """Retry a chat attempt: delete the old turn, re-submit same content.
+
+ Looks up the original user message content via
+ ``ChatService.get_original_attempt_query`` (uses
+ ``research_meta.submission.message_id`` first, falls back to a
+ ChatMessage query for older rows), deletes the old attempt
+ atomically, then runs the same spawn path as ``send_message``.
+
+ Returns the SAME shape as ``send_message`` so the client can
+ subscribe to the new research_id via its existing post-send flow.
+ """
+ try:
+ username = session.get("username")
+ service = ChatService(username)
+
+ # Verify session exists + is active BEFORE doing anything
+ # destructive. The get_session call also seeds session_data for
+ # the context-builder below.
+ try:
+ session_data = service.get_session(session_id)
+ except ChatSessionNotFound:
+ return jsonify(
+ {"success": False, "error": "Session not found"}
+ ), 404
+
+ if session_data.get("status") != ChatSessionStatus.ACTIVE.value:
+ return jsonify(
+ {
+ "success": False,
+ "error": (
+ "This chat is archived. Reactivate it to continue."
+ ),
+ }
+ ), 409
+
+ # Resolve DB password BEFORE any destructive op: the spawn path
+ # needs it for metrics writes, and re-checking AFTER delete_attempt
+ # would leave the attempt gone on a session-expired 401.
+ _pw, session_expired = resolve_user_password(username)
+ if session_expired:
+ return jsonify(
+ {
+ "success": False,
+ "error": (
+ "Your session has expired. Please log out and "
+ "log back in to continue."
+ ),
+ }
+ ), 401
+
+ # Per-session + per-user concurrency guards. Same sweep pattern
+ # as send_message: reclaim stale rows older than the grace
+ # window first so the count check is accurate, then refuse if
+ # this session OR the user is at capacity.
+ #
+ # If the TARGET research is still IN_PROGRESS, the per-session
+ # guard catches it here and returns 409 — the user must Stop it
+ # first. (delete_attempt would also catch this via
+ # AttemptInProgress, but failing earlier — before any rows are
+ # touched — keeps the failure cheap.)
+ _STALE_RESEARCH_GRACE_SECONDS = 30
+ grace_cutoff_dt = datetime.now(UTC) - timedelta(
+ seconds=_STALE_RESEARCH_GRACE_SECONDS
+ )
+ grace_cutoff_iso = grace_cutoff_dt.isoformat()
+ with get_user_db_session(username) as cap_db:
+ # Reclaim stale chat-session research rows whose worker is
+ # dead AND older than the grace cutoff. Mirrors
+ # send_message's sweep at chat/routes.py:903-923.
+ stale_chat = (
+ cap_db.query(ResearchHistory)
+ .filter(
+ ResearchHistory.chat_session_id == session_id,
+ ResearchHistory.status == ResearchStatus.IN_PROGRESS,
+ ResearchHistory.created_at < grace_cutoff_iso,
+ )
+ .all()
+ )
+ reclaimed_chat = False
+ for row in stale_chat:
+ if not is_research_thread_alive(row.id):
logger.warning(
- f"Concurrent in-progress research race for chat {session_id[:8]}..."
+ f"Reclaiming stale chat research {row.id[:8]}... "
+ f"(thread dead) on chat {session_id[:8]}..."
)
+ row.status = ResearchStatus.FAILED
+ cleanup_research(row.id)
+ reclaimed_chat = True
+ if reclaimed_chat:
+ cap_db.commit()
+
+ # Reclaim stale UserActiveResearch rows globally for this
+ # user, so the per-user cap count below isn't inflated.
+ from ..web.routes.globals import (
+ reclaim_stale_user_active_research,
+ )
+
+ if reclaim_stale_user_active_research(
+ cap_db,
+ username,
+ grace_cutoff_dt=grace_cutoff_dt,
+ logger=logger,
+ ):
+ cap_db.commit()
+
+ cap_error = _enforce_chat_session_research_slot(
+ cap_db, username, session_id
+ )
+ if cap_error is not None:
+ msg, status = cap_error
+ if status == 409:
return jsonify(
{
"success": False,
- "error": "Research already in progress on this chat session.",
+ "error": msg,
+ "active_research_id": research_id,
}
), 409
- except ValueError as exc:
- # `insert_message_in_db` raises ValueError("not found")
- # when the session row was deleted between the existence
- # check and the UPDATE...RETURNING. Map to 404 so the
- # client can distinguish a deleted session from a 500.
- if "not found" in str(exc).lower():
- return jsonify(
- {"success": False, "error": "Session not found"}
- ), 404
- raise
- # ---- end atomic write ----
-
- if trigger_research:
- # Type narrowing: the variables below were initialized to None
- # at the top of the route and then assigned inside the matching
- # `if trigger_research:` block above. They are guaranteed
- # non-None here, but mypy doesn't connect the two branches —
- # so we narrow explicitly. Uses a real runtime check (not
- # ``assert``) so it survives ``python -O`` (bandit S101).
- if (
- settings_snapshot is None
- or research_context is None
- or research_id is None
- or message_id is None
- ): # pragma: no cover — unreachable invariant guard
- raise RuntimeError(
- "trigger_research path entered with unset state"
- )
- # Get user password for metrics
- pw = get_user_password(username)
+ return jsonify({"success": False, "error": msg}), status
- # Extract settings values with safe .get() defaults
- model_provider = settings_snapshot.get("llm.provider", {}).get(
- "value", ""
- )
- model = settings_snapshot.get("llm.model", {}).get("value", "")
- search_engine = settings_snapshot.get("search.tool", {}).get(
- "value", ""
+ # Fetch original user content BEFORE deleting the old attempt.
+ # After delete_attempt the row is gone, so this lookup must
+ # succeed first. Raises AttemptNotFound → 404.
+ try:
+ original_content = service.get_original_attempt_query(
+ session_id, research_id
)
- custom_endpoint = settings_snapshot.get(
- "llm.openai_endpoint.url", {}
- ).get("value")
- # Defensive fallbacks kept in sync with default_settings.json:
- # `search.search_strategy` defaults to "langgraph-agent",
- # `search.iterations` to 3, `search.questions_per_iteration`
- # to 1. Out-of-sync fallbacks here silently produce a
- # *different* research product if the snapshot ever lacks
- # the key (e.g., fresh user DB before defaults are seeded).
- user_strategy = settings_snapshot.get(
- "search.search_strategy", {}
- ).get("value", "langgraph-agent")
- # `iterations` and `questions` were parsed + validated up-front
- # (before the atomic write) so a malformed setting returns a
- # clean 400 instead of orphaning a committed research row.
-
- # For follow-up messages, use the contextual follow-up strategy
- # which wraps the user's preferred strategy as a delegate
- if research_context.get("is_multi_turn"):
- strategy = "enhanced-contextual-followup"
- research_context["delegate_strategy"] = user_strategy
- else:
- strategy = user_strategy
-
- # Spawn the worker thread. ``DuplicateResearchError``
- # inherits from ``Exception`` (not RuntimeError) so it is
- # NOT in ROUTE_EXCEPTIONS and would otherwise escape to a
- # generic 500 — leaving the user message + research row
- # we just committed as orphans. Catch it here, undo our
- # side effects, and return 409.
- try:
- start_research_process(
- research_id,
- content,
- research_mode,
- run_research_process,
- username=username,
- user_password=pw,
- model_provider=model_provider,
- model=model,
- search_engine=search_engine,
- custom_endpoint=custom_endpoint,
- strategy=strategy,
- iterations=iterations,
- questions_per_iteration=questions,
- research_context=research_context,
- chat_session_id=session_id,
- chat_message_id=message_id,
- settings_snapshot=settings_snapshot,
- )
- except DuplicateResearchError:
- logger.warning(
- f"DuplicateResearchError on chat send_message "
- f"for {research_id[:8]}... (chat {session_id[:8]}...)"
- )
- # Per ``DuplicateResearchError`` docstring: do NOT
- # mutate UserActiveResearch or the existing
- # ResearchHistory row — those belong to the live
- # thread. Only undo the rows we created in our own
- # transaction above.
- _cleanup_chat_send_rows(
- username, research_id, message_id, session_id, "duplicate"
- )
- return jsonify(
- {
- "success": False,
- "error": "Research already in progress on this chat session.",
- }
- ), 409
- except SystemAtCapacityError:
- # System at concurrent-research capacity. Undo the rows we
- # committed above and return 429 so the client can retry.
- logger.warning(
- f"SystemAtCapacityError on chat send_message "
- f"for {research_id[:8]}... (chat {session_id[:8]}...)"
- )
- _cleanup_chat_send_rows(
- username, research_id, message_id, session_id, "capacity"
- )
- return jsonify(
- {
- "success": False,
- "error": "Server is at research capacity. Please retry shortly.",
- }
- ), 429
+ except AttemptNotFound:
+ return jsonify(
+ {"success": False, "error": "Attempt not found"}
+ ), 404
- logger.info(
- f"Started chat research {research_id[:8]}... for chat {session_id[:8]}..."
+ if not original_content.strip():
+ # Empty/whitespace-only original — shouldn't happen since
+ # send_message rejects these, but guard against a corrupt
+ # row before we destroy the only copy.
+ return jsonify(
+ {
+ "success": False,
+ "error": (
+ "Original attempt has no query content to retry."
+ ),
+ }
+ ), 400
+
+ # Delete the old attempt. By this point the target is guaranteed
+ # not IN_PROGRESS (the per-session guard above would have
+ # caught it), so this should not raise AttemptInProgress — but
+ # catch it anyway in case of a narrow race.
+ try:
+ service.delete_attempt(session_id, research_id)
+ except AttemptInProgress:
+ return jsonify(
+ {
+ "success": False,
+ "error": (
+ "Research is in progress. Stop it before retrying."
+ ),
+ "active_research_id": research_id,
+ }
+ ), 409
+ except AttemptNotFound:
+ # Concurrent retry already deleted the target.
+ return jsonify(
+ {"success": False, "error": "Attempt not found"}
+ ), 404
+
+ # Re-fetch messages list AFTER the delete so the context
+ # builder doesn't see the just-removed attempt (otherwise the
+ # new research would treat the retried query as a follow-up to
+ # itself).
+ messages = service.get_session_messages(session_id, limit=20)
+
+ settings_snapshot = _load_settings(username)
+ context_manager = ChatContextManager(
+ session_id,
+ messages,
+ session_data.get("accumulated_context"),
+ settings_snapshot=settings_snapshot,
+ )
+ research_context = context_manager.build_research_context(
+ current_query=original_content
+ )
+
+ # Spawn the new research via the shared helper. Same failure
+ # shape as send_message.
+ try:
+ new_research_id, new_message_id = _spawn_chat_research(
+ username,
+ session_id,
+ original_content,
+ settings_snapshot,
+ research_context,
+ messages,
+ service,
+ research_mode="quick",
)
+ except ChatSpawnError as exc:
+ return _chat_spawn_response(exc)
return jsonify(
{
"success": True,
- "message_id": message_id,
"session_id": session_id,
- "research_id": research_id,
- "research_mode": research_mode,
+ "research_id": new_research_id,
+ "message_id": new_message_id,
+ "research_mode": "quick",
}
)
except ROUTE_EXCEPTIONS:
- logger.exception("Error sending chat message")
+ logger.exception("Error retrying chat attempt")
return jsonify(
- {
- "success": False,
- "error": "Failed to send message",
- }
+ {"success": False, "error": "Failed to retry attempt"}
), 500
diff --git a/src/local_deep_research/chat/service.py b/src/local_deep_research/chat/service.py
index 73151fb610..c647f3a5f3 100644
--- a/src/local_deep_research/chat/service.py
+++ b/src/local_deep_research/chat/service.py
@@ -24,9 +24,14 @@ from ..database.models import (
ChatSession,
ChatSessionStatus,
ResearchHistory,
+ UserActiveResearch,
)
from ..database.session_context import get_user_db_session
-from ..web.routes.globals import set_termination_flag
+from ..web.routes.globals import (
+ cleanup_research,
+ is_research_thread_alive,
+ set_termination_flag,
+)
from ..constants import ResearchStatus
# Standard exception tuple for service-layer DB operations
@@ -60,6 +65,32 @@ class ChatRepositoryError(RuntimeError):
"""
+class AttemptNotFound(LookupError):
+ """Raised when no ResearchHistory row matches the supplied research_id
+ inside the session scoped by ``session_id``.
+
+ The route layer translates this to HTTP 404. Distinct from
+ ChatSessionNotFound (also 404) so the diagnostic log distinguishes
+ "session missing" from "research missing".
+ """
+
+
+class AttemptInProgress(RuntimeError):
+ """Raised by delete_attempt when the target research is IN_PROGRESS
+ AND its worker thread is alive.
+
+ Deleting a research out from under a live worker would orphan the
+ thread (it would keep burning LLM cycles against a ResearchHistory
+ row that no longer exists). The route layer translates this to HTTP
+ 409 and returns ``research_id`` so the client can offer a Stop +
+ retry flow.
+
+ A stale IN_PROGRESS row whose thread is dead does NOT raise: the
+ sweep logic inside ``delete_attempt`` reclaims it (mirrors
+ send_message's stale-row reclaim at chat/routes.py:903-923).
+ """
+
+
# Title generation should not block the request thread on a slow LLM.
# Wrap the synchronous llm.invoke() call in a worker future with a hard
# wall-clock timeout. The default matches the rest of the codebase's
@@ -888,6 +919,294 @@ class ChatService:
logger.exception("Error deleting chat session")
return False
+ def delete_attempt(self, session_id: str, research_id: str) -> bool:
+ """Permanently delete one chat attempt (research + its messages + steps).
+
+ An "attempt" is the user message that triggered a research, the
+ research_history row itself, any assistant response message(s)
+ tagged with that research, and all chat_progress_steps. The
+ assistant message(s) and progress steps carry ``research_id``
+ directly; the user message is inserted with ``research_id=NULL``
+ (see ``_spawn_chat_research``) and is reachable only via
+ ``research_meta.submission.message_id`` — both linkages are
+ resolved below so the user bubble is removed too (issue #4659).
+
+ Refuses to delete while the target research is IN_PROGRESS and
+ its worker thread is alive (raises ``AttemptInProgress`` → 409).
+ A stale IN_PROGRESS row whose thread is dead is reclaimed: the
+ status flips to FAILED inside the same transaction that deletes
+ the rows (mirrors the stale-reclaim sweep in
+ chat/routes.py:903-923).
+
+ Unlike ``delete_session``, this MUST decrement
+ ``ChatSession.message_count`` — the session still exists, so the
+ counter would otherwise drift permanently upward. Mirrors the
+ per-message decrement in ``_cleanup_chat_send_rows``
+ (chat/routes.py:175-179).
+
+ Args:
+ session_id: ID of the parent chat session (scoped lookup).
+ research_id: ID of the research attempt to delete.
+
+ Returns:
+ True if the attempt existed and was deleted.
+
+ Raises:
+ AttemptNotFound: research_id does not belong to session_id.
+ Route layer maps to HTTP 404.
+ AttemptInProgress: research is IN_PROGRESS and its worker
+ thread is alive. Route layer maps to HTTP 409 with
+ ``active_research_id``.
+ """
+ try:
+ # Phase 1 — load + liveness check, OUTSIDE the delete tx so
+ # the (rare) set_termination_flag call below doesn't have to
+ # roll back if the worker is still mid-flight. Also lets us
+ # return AttemptNotFound before touching any rows.
+ with get_user_db_session(self.username) as db:
+ research = (
+ db.query(ResearchHistory)
+ .filter(
+ ResearchHistory.id == research_id,
+ ResearchHistory.chat_session_id == session_id,
+ )
+ .first()
+ )
+ if research is None:
+ raise AttemptNotFound(research_id) # noqa: TRY301 — re-raised by outer except
+ if (
+ research.status == ResearchStatus.IN_PROGRESS
+ and is_research_thread_alive(research_id)
+ ):
+ # Signal the worker to drain; the route layer tells
+ # the client to Stop+retry. Don't hard-delete while a
+ # live thread owns the row — the worker's finally
+ # block would otherwise write back to a deleted id.
+ set_termination_flag(research_id)
+ raise AttemptInProgress(research_id) # noqa: TRY301 — re-raised by outer except
+
+ # Phase 2 — atomic delete. The row may be FAILED, COMPLETED,
+ # SUSPENDED, or stale-IN_PROGRESS (thread dead); all of those
+ # are safe to delete. Count the ChatMessage rows first so the
+ # message_count decrement matches the rows removed.
+ with get_user_db_session(self.username) as db:
+ # Re-load inside this tx (the row may have changed
+ # status between Phase 1 and Phase 2 — e.g. the worker
+ # finished). If the session itself was deleted by a
+ # concurrent request, the rows we're about to delete
+ # CASCADE away anyway, so a missing row here is a clean
+ # 404.
+ research = (
+ db.query(ResearchHistory)
+ .filter(
+ ResearchHistory.id == research_id,
+ ResearchHistory.chat_session_id == session_id,
+ )
+ .first()
+ )
+ if research is None:
+ raise AttemptNotFound(research_id) # noqa: TRY301 — re-raised by outer except
+
+ # Belt-and-braces: re-check liveness. A thread that was
+ # dead in Phase 1 can't come back, but a thread that was
+ # alive (and tripped AttemptInProgress above) would have
+ # returned already, so this branch only fires for the
+ # narrow race where the worker went from dead→alive
+ # between the two phases — not actually possible, kept
+ # as a defensive guard.
+ if (
+ research.status == ResearchStatus.IN_PROGRESS
+ and is_research_thread_alive(research_id)
+ ):
+ set_termination_flag(research_id)
+ raise AttemptInProgress(research_id) # noqa: TRY301 — re-raised by outer except
+
+ # Resolve the user (query) message id. In current
+ # production the user message is inserted by
+ # _spawn_chat_research with research_id=NULL and linked to
+ # the attempt only via research_meta.submission.message_id
+ # (mirrors get_original_attempt_query). Assistant
+ # response(s) — and legacy pre-research_meta user rows —
+ # carry research_id directly. We must delete BOTH, otherwise
+ # the user bubble lingers orphaned after the attempt is
+ # removed (issue #4659).
+ user_message_id = None
+ meta = research.research_meta or {}
+ submission = meta.get("submission") or {}
+ if isinstance(submission, dict):
+ candidate = submission.get("message_id")
+ if isinstance(candidate, str) and candidate:
+ user_message_id = candidate
+
+ # research_id matches assistant rows (+ legacy user rows);
+ # the id branch matches the NULL-research_id user message.
+ # session_id scopes the id branch so a forged/corrupt
+ # message_id can't reach another session's row.
+ msg_filter = ChatMessage.research_id == research_id
+ if user_message_id:
+ msg_filter = or_(
+ msg_filter,
+ and_(
+ ChatMessage.id == user_message_id,
+ ChatMessage.session_id == session_id,
+ ),
+ )
+
+ # Count messages BEFORE deleting them so the
+ # message_count decrement is exact.
+ removed_messages = (
+ db.query(ChatMessage).filter(msg_filter).count()
+ )
+
+ # ChatMessage.research_id FK is ON DELETE SET NULL, not
+ # CASCADE — explicit delete is required to remove the rows
+ # (otherwise the bubbles linger with a stale research_id).
+ db.query(ChatMessage).filter(msg_filter).delete(
+ synchronize_session=False
+ )
+
+ # chat_progress_steps FK is ON DELETE CASCADE, so the
+ # research_history.delete() below would clean them up.
+ # Delete explicitly so the count is predictable and the
+ # tx is self-contained if the CASCADE pragma ever flips.
+ db.query(ChatProgressStep).filter(
+ ChatProgressStep.research_id == research_id
+ ).delete(synchronize_session=False)
+
+ # user_active_research row (per-user cap counter).
+ # Filtered by research_id; the username filter is
+ # belt-and-braces (this user's DB only contains their own
+ # rows).
+ db.query(UserActiveResearch).filter(
+ UserActiveResearch.research_id == research_id
+ ).delete(synchronize_session=False)
+
+ # ResearchHistory last so its CASCADE doesn't fire while
+ # our explicit deletes are pending.
+ db.query(ResearchHistory).filter(
+ ResearchHistory.id == research_id
+ ).delete(synchronize_session=False)
+
+ # Decrement message_count. Skipped when no messages were
+ # removed (e.g. an attempt that crashed before any
+ # assistant response landed) — avoids a pointless UPDATE.
+ if removed_messages > 0:
+ db.query(ChatSession).filter(
+ ChatSession.id == session_id
+ ).update(
+ {
+ ChatSession.message_count: (
+ ChatSession.message_count - removed_messages
+ )
+ },
+ synchronize_session=False,
+ )
+
+ db.commit()
+
+ # Phase 3 — post-commit in-memory cleanup. The worker's own
+ # finally block calls cleanup_research too, so this is a
+ # no-op for the in-progress path; for the stale-IN_PROGRESS
+ # path it frees the slot immediately.
+ cleanup_research(research_id)
+
+ logger.info(
+ f"Deleted chat attempt: user={self.username[:8]}... "
+ f"session={session_id[:8]}... research={research_id[:8]}... "
+ f"({removed_messages} messages)"
+ )
+ return True
+
+ except (AttemptNotFound, AttemptInProgress):
+ raise
+ except DB_EXCEPTIONS:
+ logger.exception("Error deleting chat attempt")
+ raise
+
+ def get_original_attempt_query(
+ self, session_id: str, research_id: str
+ ) -> str:
+ """Return the original user message content for a chat research.
+
+ Used by the retry route to re-submit the same query without the
+ client echoing it back. Looks up ``research_meta.submission.\
+ message_id`` first (set at send time by chat/routes.py:1058);
+ falls back to a query on ``ChatMessage.research_id == X AND
+ role='user'`` for older rows that predate the meta field.
+
+ Args:
+ session_id: ID of the parent chat session (scoped lookup).
+ research_id: ID of the research attempt.
+
+ Returns:
+ The original user message content as a string.
+
+ Raises:
+ AttemptNotFound: research_id does not belong to session_id,
+ or no user message is reachable from it. Route layer
+ maps to HTTP 404.
+ """
+ try:
+ with get_user_db_session(self.username) as db:
+ # Scope-by-session first: a research_id from another
+ # session (e.g. user-supplied path param) should 404,
+ # not silently return that other session's content.
+ research = (
+ db.query(ResearchHistory)
+ .filter(
+ ResearchHistory.id == research_id,
+ ResearchHistory.chat_session_id == session_id,
+ )
+ .first()
+ )
+ if research is None:
+ raise AttemptNotFound(research_id) # noqa: TRY301 — re-raised by outer except
+
+ # Fast path: research_meta carries the original
+ # message_id set at send time.
+ user_message_id = None
+ meta = research.research_meta or {}
+ submission = meta.get("submission") or {}
+ if isinstance(submission, dict):
+ candidate = submission.get("message_id")
+ if isinstance(candidate, str) and candidate:
+ user_message_id = candidate
+
+ if user_message_id:
+ msg = (
+ db.query(ChatMessage)
+ .filter(
+ ChatMessage.id == user_message_id,
+ ChatMessage.session_id == session_id,
+ ChatMessage.role == ChatRole.USER.value,
+ )
+ .first()
+ )
+ if msg is not None and msg.content:
+ return str(msg.content)
+
+ # Fallback: pre-research_meta rows. Look up the user
+ # message by research_id + role.
+ msg = (
+ db.query(ChatMessage)
+ .filter(
+ ChatMessage.research_id == research_id,
+ ChatMessage.session_id == session_id,
+ ChatMessage.role == ChatRole.USER.value,
+ )
+ .order_by(ChatMessage.created_at.asc())
+ .first()
+ )
+ if msg is None or not msg.content:
+ raise AttemptNotFound(research_id) # noqa: TRY301 — re-raised by outer except
+ return str(msg.content)
+
+ except AttemptNotFound:
+ raise
+ except DB_EXCEPTIONS:
+ logger.exception("Error fetching original attempt query")
+ raise
+
def update_accumulated_context(
self,
session_id: str,
diff --git a/src/local_deep_research/web/static/css/chat.css b/src/local_deep_research/web/static/css/chat.css
index 9056e5a887..2515c8407c 100644
--- a/src/local_deep_research/web/static/css/chat.css
+++ b/src/local_deep_research/web/static/css/chat.css
@@ -945,6 +945,59 @@
text-decoration: none;
}
+/* Per-message hover actions (Copy / Retry / Delete). Revealed on
+ hover AND keyboard focus-within so keyboard-only users get the
+ same affordance as mouse users. Mirrors the .ldr-chat-message-meta
+ reveal pattern above. */
+.ldr-chat-message-actions {
+ display: flex;
+ gap: 0.15rem;
+ margin-top: 0.4rem;
+ opacity: 0;
+ transition: opacity 0.15s;
+}
+
+.ldr-chat-message:hover .ldr-chat-message-actions,
+.ldr-chat-message:focus-within .ldr-chat-message-actions {
+ opacity: 0.85;
+}
+
+.ldr-chat-msg-action {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 1.6rem;
+ height: 1.6rem;
+ padding: 0;
+ font-size: 0.75rem;
+ line-height: 1;
+ color: var(--text-muted, #8a8aa0);
+ background: transparent;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+}
+
+.ldr-chat-msg-action:hover,
+.ldr-chat-msg-action:focus-visible {
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--text-primary, #e0e0e8);
+ outline: none;
+}
+
+.ldr-chat-msg-action:focus-visible {
+ box-shadow: 0 0 0 2px var(--accent-tertiary, #40bfff);
+}
+
+/* Delete gets a subtle red tint on hover so the destructive action is
+ visually distinct from Copy/Retry. */
+.ldr-chat-msg-action-delete:hover,
+.ldr-chat-msg-action-delete:focus-visible {
+ color: #ff6b6b;
+ background: rgba(var(--error-color-rgb), 0.08);
+}
+
/* Load-older-messages pagination trigger at the top of the chat
stream. Sits above the oldest currently-displayed message; clicking
prepends the previous batch via /messages?before_created_at=. */
diff --git a/src/local_deep_research/web/static/js/components/chat.js b/src/local_deep_research/web/static/js/components/chat.js
index 3134fd3112..28acd20afb 100644
--- a/src/local_deep_research/web/static/js/components/chat.js
+++ b/src/local_deep_research/web/static/js/components/chat.js
@@ -353,6 +353,236 @@
if (exportBtn) {
exportBtn.addEventListener('click', handleExport);
}
+
+ // Per-message action bar (Copy / Retry / Delete). Delegated from
+ // #chat-messages so a single listener covers every bubble,
+ // including ones added later by the streaming path.
+ if (chatMessages) {
+ chatMessages.addEventListener('click', handleMessageActionClick);
+ }
+ }
+
+ /**
+ * Delegated click handler for the per-message action buttons.
+ *
+ * Routes by ``data-action`` to the right handler, passing the
+ * message's ``data-research-id`` (for retry/delete) and the
+ * ``data-copy-content`` (for copy). Clicks inside the streaming
+ * bubble or step accordion are ignored — those don't carry the
+ * ``.ldr-chat-msg-action`` class.
+ */
+ function handleMessageActionClick(event) {
+ const btn = event.target.closest('.ldr-chat-msg-action');
+ if (!btn || !chatMessages.contains(btn)) return;
+
+ const messageEl = btn.closest('.ldr-chat-message');
+ if (!messageEl) return;
+
+ const action = btn.dataset.action;
+ const actionsEl = messageEl.querySelector('.ldr-chat-message-actions');
+ const researchId = messageEl.dataset.researchId || null;
+ const copyContent = actionsEl?.dataset.copyContent || '';
+
+ if (action === 'copy') {
+ handleCopyMessage(copyContent, btn);
+ } else if (action === 'retry') {
+ if (!researchId || isProcessing) return;
+ handleRetryAttempt(researchId);
+ } else if (action === 'delete') {
+ if (!researchId) return;
+ handleDeleteAttempt(researchId);
+ }
+ }
+
+ /**
+ * Copy message content to the clipboard. Falls back to a hidden
+ * textarea + execCommand when ``navigator.clipboard`` is unavailable
+ * (older browsers, insecure context). Shows a brief "Copied" label
+ * on the clicked button so the click registers.
+ */
+ async function handleCopyMessage(content, btn) {
+ const text = String(content || '');
+ let ok;
+ try {
+ if (navigator.clipboard && window.isSecureContext) {
+ await navigator.clipboard.writeText(text);
+ ok = true;
+ } else {
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.setAttribute('readonly', '');
+ ta.style.position = 'absolute';
+ ta.style.left = '-9999px';
+ document.body.appendChild(ta);
+ ta.select();
+ ok = document.execCommand('copy');
+ document.body.removeChild(ta);
+ }
+ } catch (e) {
+ _log.error('Chat: copy failed', e);
+ ok = false;
+ }
+
+ // Visual feedback regardless of path: briefly swap the icon for
+ // a checkmark. The label change also nudges the aria-live region
+ // (the parent #chat-messages is role="log") to announce the
+ // result for screen readers.
+ if (btn) {
+ const icon = btn.querySelector('i');
+ // If a previous copy's transient icon is still showing, cancel
+ // its restore timer and put the real icon back BEFORE capturing
+ // the "original" below. Without this, a second click within the
+ // 1.2s window captures the checkmark as the original and the
+ // button is left stuck on it.
+ if (btn._ldrCopyRestoreTimer) {
+ clearTimeout(btn._ldrCopyRestoreTimer);
+ if (icon && btn._ldrCopyIconClass != null) {
+ icon.className = btn._ldrCopyIconClass;
+ }
+ if (btn._ldrCopyLabel != null) {
+ btn.setAttribute('aria-label', btn._ldrCopyLabel);
+ }
+ }
+ const originalClass = icon ? icon.className : '';
+ const originalLabel = btn.getAttribute('aria-label');
+ btn._ldrCopyIconClass = originalClass;
+ btn._ldrCopyLabel = originalLabel;
+ if (icon) icon.className = ok ? 'fas fa-check' : 'fas fa-xmark';
+ btn.setAttribute('aria-label', ok ? 'Copied' : 'Copy failed');
+ btn._ldrCopyRestoreTimer = setTimeout(() => {
+ if (icon) icon.className = originalClass;
+ if (originalLabel) btn.setAttribute('aria-label', originalLabel);
+ btn._ldrCopyRestoreTimer = null;
+ }, 1200);
+ }
+ }
+
+ /**
+ * Delete a single chat attempt (user msg + research + assistant msg
+ * + steps). Confirms via native ``confirm()`` — the stakes are
+ * bounded (one turn, recoverable by re-typing) and bringing the
+ * library's Bootstrap modal markup into chat.html is too much
+ * weight for one dialog. On success, every DOM node tagged with the
+ * research id is removed.
+ */
+ async function handleDeleteAttempt(researchId) {
+ if (!researchId || !sessionId) return;
+ // Default to the "Re-run / replace" wording which is safe for
+ // both failed and completed attempts — the client doesn't
+ // always know the prior status cheaply.
+ const ok = window.confirm(
+ 'Delete this attempt? The user message, research, and any '
+ + 'response will be permanently removed from this chat.'
+ );
+ if (!ok) return;
+
+ try {
+ await apiPost(
+ `/api/chat/sessions/${encodeURIComponent(sessionId)}/attempts/${encodeURIComponent(researchId)}`,
+ null,
+ 'DELETE',
+ );
+ } catch (e) {
+ _log.error('Chat: delete attempt failed', e);
+ const raw = (e && e.message) ? e.message : '';
+ const display = raw && !/^Request failed \(\d+\)$/.test(raw)
+ ? raw
+ : 'Failed to delete attempt. Please try again.';
+ // Surface inline rather than via alert() — the chat already
+ // uses inline assistant messages for error feedback
+ // (handleSend's catch block).
+ addMessageToUI('assistant', display);
+ return;
+ }
+
+ // Remove every DOM node tagged with this research id: the user
+ // message, any assistant response(s), and the step accordion.
+ // The step accordion is built by ensureLiveAccordion/wrap-
+ // StepsInAccordion and doesn't carry data-research-id, so a
+ // full session reload is the simplest correct path. Cheaper
+ // alternative would be a sibling walk, but the reload also
+ // fixes any message_count drift in the sidebar.
+ await loadSession(sessionId);
+ }
+
+ /**
+ * Retry a chat attempt: delete the failed/prior turn, then re-submit
+ * the same content as a fresh research run. Server returns the new
+ * research_id + message_id; the client adopts the same live-update
+ * subscription path as handleSend.
+ *
+ * The confirm copy uses "Re-run / replace" wording to make it
+ * explicit that the prior assistant response is destroyed — even
+ * for a previously-completed attempt this is the right mental model
+ * (Retry always replaces).
+ */
+ async function handleRetryAttempt(researchId) {
+ if (!researchId || !sessionId || isProcessing) return;
+ const ok = window.confirm(
+ 'Re-run this attempt? The previous response will be '
+ + 'replaced and the same query will be submitted again.'
+ );
+ if (!ok) return;
+
+ // If a different research is in-flight (e.g. user started a new
+ // turn after the failed one), tear down its listeners before
+ // subscribing to the new id — otherwise step events from the
+ // old research would interleave into the new bubble.
+ if (currentResearchId && currentResearchId !== researchId) {
+ cleanupSocketListeners(currentResearchId);
+ } else if (currentResearchId === researchId) {
+ cleanupSocketListeners(researchId);
+ }
+ cancelPendingTimers();
+
+ isProcessing = true;
+ sendBtn.disabled = true;
+
+ // Show the thinking indicator BEFORE the await so the user sees
+ // immediate feedback. The old attempt's DOM stays in place
+ // until the new research is dispatched, then we reload — that
+ // way a failed retry leaves the original turn intact.
+ const thinkingEl = showThinking('Retrying attempt…');
+
+ try {
+ const data = await apiPost(
+ `/api/chat/sessions/${encodeURIComponent(sessionId)}/attempts/${encodeURIComponent(researchId)}/retry`,
+ {},
+ );
+ if (!data.research_id) {
+ throw new Error('Server did not return a new research_id');
+ }
+ // eslint-disable-next-line require-atomic-updates -- handleRetryAttempt checks isProcessing at entry; no concurrent call can reach here
+ currentResearchId = data.research_id;
+ completionHandled = false;
+ suspendedHandled = false;
+ setThinkingLabel(thinkingEl, null);
+ showProgress();
+ // Reload from DB so the old attempt's bubbles are gone and
+ // the new user message is in place. loadSession() owns the
+ // resubscription: it resets active research state (tearing
+ // down the pre-await thinkingEl + any timers) and, because the
+ // freshly spawned research is IN_PROGRESS, re-subscribes with a
+ // fresh thinkingEl via its in_progress_research_id branch.
+ // Subscribing again here would leak loadSession's poll timer
+ // (pollTimerId is module-level) and attach handlers to the
+ // detached thinkingEl — so we deliberately don't. Mirrors
+ // handleDeleteAttempt. Use the captured sessionId to avoid
+ // races with a concurrent startNewChat().
+ const sidAtCall = sessionId;
+ await loadSession(sidAtCall);
+ } catch (e) {
+ _log.error('Chat: retry attempt failed', e);
+ removeThinking(thinkingEl);
+ const raw = (e && e.message) ? e.message : '';
+ const display = raw && !/^Request failed \(\d+\)$/.test(raw)
+ ? raw
+ : 'Failed to retry attempt. Please try again.';
+ addMessageToUI('assistant', display);
+ // eslint-disable-next-line require-atomic-updates -- handleRetryAttempt checks isProcessing at entry; no concurrent call can reach here
+ isProcessing = false;
+ sendBtn.disabled = !chatInput.value.trim();
+ }
}
/**
@@ -391,11 +621,17 @@
}
async function apiPost(url, body, method = 'POST') {
- const r = await fetch(url, {
+ const options = {
method,
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCsrfToken() },
- body: JSON.stringify(body),
- });
+ };
+ // Skip body for null/undefined so DELETE and GET-style POSTs
+ // don't send a literal "null" or "undefined" string. Empty
+ // body is fine for endpoints that don't @require_json_body.
+ if (body !== null && body !== undefined) {
+ options.body = JSON.stringify(body);
+ }
+ const r = await fetch(url, options);
if (!r.ok) {
const err = await r.json().catch(() => ({}));
throw new Error(err.error || `Request failed (${r.status})`);
@@ -863,6 +1099,9 @@
// safety check in refreshSessionMessages can detect whether the
// assistant response actually landed in the DOM (vs missing due
// to a streaming-swap race) and auto-recover by reloading.
+ // Also used by the per-attempt Retry/Delete action handlers to
+ // locate every element of the attempt (user msg + assistant msg
+ // + step accordion) without walking siblings.
if (researchId) {
messageEl.dataset.researchId = researchId;
}
@@ -886,9 +1125,79 @@
timeEl.textContent = date.toLocaleTimeString();
}
+ _appendMessageActions(messageEl, role, content, researchId);
+
return messageEl;
}
+ /**
+ * Build the per-message hover-action row (Copy / Retry / Delete).
+ *
+ * Mirrors the ChatGPT/Claude.ai pattern: a small icon row below the
+ * bubble's content, revealed on hover AND keyboard focus (a11y —
+ * the keyboard path is the focus-within branch in chat.css).
+ *
+ * Retry and Delete are only attached when the message has a
+ * ``researchId``: they operate on the whole attempt (user msg +
+ * research + assistant response + steps), so a no-research message
+ * (e.g. one sent with trigger_research=false) has nothing to
+ * retry or delete at the attempt level. Copy is always available.
+ *
+ * Click handling is delegated from #chat-messages in
+ * setupEventListeners so a single listener covers every bubble,
+ * including ones added later by the streaming path.
+ */
+ function _appendMessageActions(messageEl, role, content, researchId) {
+ const contentEl = messageEl.querySelector('.ldr-chat-message-content');
+ if (!contentEl) return;
+
+ const actionsEl = document.createElement('div');
+ actionsEl.className = 'ldr-chat-message-actions';
+ // Store content for the copy handler. TextContent of a user
+ // message is the raw input; for an assistant bubble, the
+ // rendered markdown is what the user sees and would expect on
+ // the clipboard. Both are retrievable via the .ldr-chat-message-
+ // text child.
+ actionsEl.dataset.copyContent = content || '';
+
+ // Copy — always available.
+ actionsEl.appendChild(_buildActionButton({
+ action: 'copy',
+ iconClass: 'fa-copy',
+ label: role === 'user' ? 'Copy message' : 'Copy response',
+ }));
+
+ // Retry / Delete — only when this message belongs to a research
+ // attempt. The endpoint keys off researchId.
+ if (researchId) {
+ actionsEl.appendChild(_buildActionButton({
+ action: 'retry',
+ iconClass: 'fa-rotate-right',
+ label: 'Retry this attempt',
+ }));
+ actionsEl.appendChild(_buildActionButton({
+ action: 'delete',
+ iconClass: 'fa-trash-can',
+ label: 'Delete this attempt',
+ }));
+ }
+
+ contentEl.appendChild(actionsEl);
+ }
+
+ function _buildActionButton({action, iconClass, label}) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = `ldr-chat-msg-action ldr-chat-msg-action-${action}`;
+ btn.dataset.action = action;
+ btn.setAttribute('aria-label', label);
+ btn.setAttribute('title', label);
+ const icon = document.createElement('i');
+ icon.className = `fas ${iconClass}`;
+ btn.appendChild(icon);
+ return btn;
+ }
+
function addMessageToUI(role, content, timestamp, researchId) {
const messageEl = buildMessageBubble(role, content, timestamp, researchId);
if (!messageEl) return;
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index 58646f35b7..e8eedc7137 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -289,6 +289,8 @@
handleSubscribe(itemData);
} else if (e.target.closest('.ldr-rerun-btn')) {
handleRerun(itemData);
+ } else if (e.target.closest('.ldr-copy-query-btn')) {
+ handleCopyQuery(itemData);
} else if (isChatItem || itemData._is_chat) {
// Item-level click on a chat session
URLValidator.safeAssign(window.location, 'href', `/chat/${encodeURIComponent(itemId)}`);
@@ -600,10 +602,14 @@
`<button class="btn btn-sm ldr-btn-outline ldr-subscribe-btn" data-research-id="${esc(item.id)}" data-query="${esc(encodeURIComponent(item.query))}">
<i class="fas fa-bell"></i><span> Subscribe</span>
</button>` : ''}
- ${!isChatItem && ResearchStates.isCompleted(item.status) ?
+ ${!isChatItem && ResearchStates.isTerminal(item.status) ?
`<button class="btn btn-sm ldr-btn-outline ldr-rerun-btn" title="Re-run this research">
<i class="fas fa-redo"></i><span> Re-run</span>
</button>` : ''}
+ ${!isChatItem && item.query ?
+ `<button class="btn btn-sm ldr-btn-outline ldr-copy-query-btn" title="Copy query" aria-label="Copy query">
+ <i class="fas fa-copy"></i>
+ </button>` : ''}
<button class="btn btn-sm ldr-btn-outline ldr-delete-item-btn" title="Delete" aria-label="Delete">
<i class="fas fa-trash-alt"></i>
</button>
@@ -823,6 +829,46 @@
URLValidator.safeAssign(window.location, 'href', '/');
}
+ /**
+ * Handle copy-query button click. Copies the item's original query
+ * to the clipboard so the user can paste it elsewhere (a new
+ * research run, an external tool, a bug report) without having to
+ * open the research detail page.
+ *
+ * Directly addresses azrael-229's #4659 comment: "copying query
+ * content from failed search in history is somewhat clunky" —
+ * previously the only path was open-results → select-all → copy.
+ *
+ * @param {Object} item - The history item whose query should be copied
+ */
+ async function handleCopyQuery(item) {
+ if (!item || !item.query) return;
+ const text = String(item.query);
+ let ok;
+ try {
+ if (navigator.clipboard && window.isSecureContext) {
+ await navigator.clipboard.writeText(text);
+ ok = true;
+ } else {
+ // Hidden-textarea fallback for older browsers / insecure
+ // contexts (HTTP, iframe without allow="clipboard-write").
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.setAttribute('readonly', '');
+ ta.style.position = 'absolute';
+ ta.style.left = '-9999px';
+ document.body.appendChild(ta);
+ ta.select();
+ ok = document.execCommand('copy');
+ document.body.removeChild(ta);
+ }
+ } catch (e) {
+ SafeLogger.error('Copy-query failed:', e);
+ ok = false;
+ }
+ uiUtils.showMessage(ok ? 'Query copied to clipboard' : 'Copy failed — please copy manually');
+ }
+
// Modal-based subscription removed - now redirects to dedicated form page
// Folder loading removed - handled by dedicated form page
diff --git a/tests/chat/test_chat_attempt_delete_retry.py b/tests/chat/test_chat_attempt_delete_retry.py
new file mode 100644
index 0000000000..bde36384e6
--- /dev/null
+++ b/tests/chat/test_chat_attempt_delete_retry.py
@@ -0,0 +1,765 @@
+# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
+"""Tests for per-attempt delete + retry endpoints.
+
+Issue #4659: when a chat-triggered research fails (OoM, crash, dead LLM
+endpoint), the user message stays in the thread and there's no in-chat
+way to retry without copy-pasting. The new endpoints
+
+ DELETE /api/chat/sessions/<sid>/attempts/<rid>
+ POST /api/chat/sessions/<sid>/attempts/<rid>/retry
+
+let the client delete or re-run a single attempt atomically.
+
+Coverage in this file:
+
+- Service-level (``ChatService.delete_attempt`` /
+ ``get_original_attempt_query``): happy path, missing, in-progress
+ refusal, stale-IN_PROGRESS reclaim, message_count decrement,
+ research_meta fallback.
+- HTTP-level: happy paths, 404 / 409 mappings, CSRF enforcement,
+ concurrent-message 409 race via the partial unique index.
+"""
+
+import json
+import uuid
+from datetime import datetime, UTC
+from contextlib import contextmanager
+from unittest.mock import patch
+
+import pytest
+
+from src.local_deep_research.chat.service import (
+ AttemptInProgress,
+ AttemptNotFound,
+ ChatService,
+)
+from src.local_deep_research.constants import ResearchStatus
+from src.local_deep_research.database.models import (
+ ChatMessage,
+ ChatProgressStep,
+ ChatRole,
+ ChatSession,
+ ChatSessionStatus,
+ ResearchHistory,
+)
+
+
+# ---------------------------------------------------------------------------
+# Seed helpers — used by both service-level and HTTP-level tests.
+# ---------------------------------------------------------------------------
+
+
+@contextmanager
+def _service_db(SessionLocal):
+ """Redirect ``ChatService.get_user_db_session`` to the test DB.
+
+ ChatService opens the per-user encrypted DB by username; the test
+ DB from ``setup_database_for_all_tests`` is a plain SQLite file.
+ Same pattern as ``tests/chat/test_chat_delete_terminates_research.py``.
+ """
+ with patch(
+ "src.local_deep_research.chat.service.get_user_db_session"
+ ) as ctx:
+ ctx.return_value.__enter__.return_value = SessionLocal()
+ ctx.return_value.__exit__.return_value = False
+ yield
+
+
+def _seed_attempt(
+ db,
+ username: str,
+ session_id: str,
+ research_id: str,
+ *,
+ research_status: str = ResearchStatus.FAILED.value,
+ user_content: str = "What is quantum computing?",
+ assistant_content: str | None = "Quantum computing uses qubits...",
+ include_research_meta: bool = True,
+ user_message_id: str | None = None,
+):
+ """Insert a full attempt (user msg + research + optional assistant msg).
+
+ Returns ``(user_message_id, assistant_message_id_or_None)``.
+ """
+ # Look up the session to find the next sequence_number.
+ session = db.query(ChatSession).filter_by(id=session_id).first()
+ next_seq = (session.message_count if session else 0) + 1
+
+ user_msg_id = user_message_id or str(uuid.uuid4())
+ # Mirror production: _spawn_chat_research inserts the user message with
+ # research_id=NULL and links it to the attempt only via
+ # research_meta.submission.message_id. Only legacy rows that predate the
+ # research_meta field carried research_id on the user message — model
+ # those when include_research_meta is False so the fallback lookup path
+ # in get_original_attempt_query / delete_attempt stays exercised.
+ user_research_id = None if include_research_meta else research_id
+ db.add(
+ ChatMessage(
+ id=user_msg_id,
+ session_id=session_id,
+ research_id=user_research_id,
+ role=ChatRole.USER.value,
+ message_type="query",
+ content=user_content,
+ sequence_number=next_seq,
+ )
+ )
+
+ research_meta = None
+ if include_research_meta:
+ research_meta = {
+ "submission": {
+ "chat_session_id": session_id,
+ "message_id": user_msg_id,
+ "research_mode": "quick",
+ }
+ }
+
+ db.add(
+ ResearchHistory(
+ id=research_id,
+ query=user_content,
+ mode="quick",
+ status=research_status,
+ created_at=datetime.now(UTC).isoformat(),
+ chat_session_id=session_id,
+ research_meta=research_meta,
+ )
+ )
+
+ assistant_msg_id = None
+ if assistant_content is not None:
+ assistant_msg_id = str(uuid.uuid4())
+ db.add(
+ ChatMessage(
+ id=assistant_msg_id,
+ session_id=session_id,
+ research_id=research_id,
+ role=ChatRole.ASSISTANT.value,
+ message_type="response",
+ content=assistant_content,
+ sequence_number=next_seq + 1,
+ )
+ )
+
+ # A progress step tied to this research.
+ db.add(
+ ChatProgressStep(
+ id=str(uuid.uuid4()),
+ research_id=research_id,
+ session_id=session_id,
+ phase="search",
+ content="Searching...",
+ sequence_number=1,
+ )
+ )
+
+ # Bump session message_count to match what we inserted.
+ if session:
+ session.message_count = session.message_count + (
+ 2 if assistant_content is not None else 1
+ )
+
+ db.commit()
+ return user_msg_id, assistant_msg_id
+
+
+def _make_session(db, username: str, title: str = "test chat") -> str:
+ session_id = str(uuid.uuid4())
+ db.add(
+ ChatSession(
+ id=session_id,
+ title=title,
+ status=ChatSessionStatus.ACTIVE.value,
+ message_count=0,
+ )
+ )
+ db.commit()
+ return session_id
+
+
+# ===========================================================================
+# Service-level: ChatService.delete_attempt
+# ===========================================================================
+
+
+class TestDeleteAttemptService:
+ """Direct ChatService.delete_attempt tests."""
+
+ def test_delete_attempt_happy_path(self, setup_database_for_all_tests):
+ """Deleting a FAILED attempt removes the user msg, assistant msg,
+ progress step, and research row; decrements message_count by 2."""
+ SessionLocal = setup_database_for_all_tests
+ username = f"alice_{uuid.uuid4().hex[:8]}"
+ service = ChatService(username=username)
+
+ with SessionLocal() as db:
+ session_id = _make_session(db, username)
+ research_id = str(uuid.uuid4())
+ user_msg_id, assistant_msg_id = _seed_attempt(
+ db,
+ username,
+ session_id,
+ research_id,
+ research_status=ResearchStatus.FAILED.value,
+ )
+ # Sanity: 2 messages (user + assistant) + 1 step + 1 research
+ # exist. Count by session_id, NOT research_id — the user message
+ # is seeded with research_id=NULL (production behaviour), so a
+ # research_id filter would only see the assistant row.
+ assert (
+ db.query(ChatMessage)
+ .filter_by(session_id=session_id)
+ .count()
+ == 2
+ )
+ # Regression guard for #4659: the user message must be linked
+ # to the attempt only via research_meta, with research_id NULL.
+ user_row = (
+ db.query(ChatMessage).filter_by(id=user_msg_id).first()
+ )
+ assert user_row is not None
+ assert user_row.research_id is None
+ assert (
+ db.query(ChatProgressStep)
+ .filter_by(research_id=research_id)
+ .count()
+ == 1
+ )
+
+ with _service_db(SessionLocal):
+ result = service.delete_attempt(session_id, research_id)
+ assert result is True
+
+ with SessionLocal() as db:
+ # All attempt rows gone — including the NULL-research_id user
+ # message (the #4659 bug left it orphaned in the thread).
+ assert (
+ db.query(ChatMessage)
+ .filter_by(session_id=session_id)
+ .count()
+ == 0
+ )
+ assert db.query(ChatMessage).filter_by(id=user_msg_id).first() is None
+ assert (
+ db.query(ChatProgressStep)
+ .filter_by(research_id=research_id)
+ .count()
+ == 0
+ )
+ assert (
+ db.query(ResearchHistory).filter_by(id=research_id).first()
+ is None
+ )
+ # Session still exists and message_count was decremented.
+ session = db.query(ChatSession).filter_by(id=session_id).first()
+ assert session is not None
+ assert session.message_count == 0
+
+ def test_delete_attempt_failed_no_assistant_removes_user_msg(
+ self, setup_database_for_all_tests
+ ):
+ """Primary #4659 case: a FAILED attempt with NO assistant reply.
+
+ The user message is the only chat row and is stored with
+ research_id=NULL (linked via research_meta.submission.message_id).
+ Before the fix, delete_attempt filtered solely on research_id, so it
+ removed nothing user-visible and never decremented message_count —
+ leaving an orphaned user bubble. Delete must remove the user message
+ and decrement the counter by exactly 1.
+ """
+ SessionLocal = setup_database_for_all_tests
+ username = f"alice_{uuid.uuid4().hex[:8]}"
+ service = ChatService(username=username)
+
+ with SessionLocal() as db:
+ session_id = _make_session(db, username)
+ research_id = str(uuid.uuid4())
+ user_msg_id, assistant_msg_id = _seed_attempt(
+ db,
+ username,
+ session_id,
+ research_id,
+ research_status=ResearchStatus.FAILED.value,
+ assistant_content=None,
+ )
+ assert assistant_msg_id is None
+ # Only the user message exists, and it has NULL research_id.
+ assert (
+ db.query(ChatMessage)
+ .filter_by(session_id=session_id)
+ .count()
+ == 1
+ )
+ user_row = (
+ db.query(ChatMessage).filter_by(id=user_msg_id).first()
+ )
+ assert user_row is not None and user_row.research_id is None
+ assert (
+ db.query(ChatSession)
+ .filter_by(id=session_id)
+ .first()
+ .message_count
+ == 1
+ )
+
+ with _service_db(SessionLocal):
+ assert service.delete_attempt(session_id, research_id) is True
+
+ with SessionLocal() as db:
+ assert db.query(ChatMessage).filter_by(id=user_msg_id).first() is None
+ assert (
+ db.query(ChatMessage)
+ .filter_by(session_id=session_id)
+ .count()
+ == 0
+ )
+ assert (
+ db.query(ResearchHistory).filter_by(id=research_id).first()
+ is None
+ )
+ # The counter was decremented by exactly 1 (the orphaned user
+ # bubble), not left drifting at 1.
+ assert (
+ db.query(ChatSession)
+ .filter_by(id=session_id)
+ .first()
+ .message_count
+ == 0
+ )
+
+ def test_delete_attempt_missing(self, setup_database_for_all_tests):
+ """Unknown research_id → AttemptNotFound."""
+ SessionLocal = setup_database_for_all_tests
+ username = f"alice_{uuid.uuid4().hex[:8]}"
+ service = ChatService(username=username)
+
+ with SessionLocal() as db:
+ session_id = _make_session(db, username)
+
+ with _service_db(SessionLocal):
+ with pytest.raises(AttemptNotFound):
+ service.delete_attempt(session_id, str(uuid.uuid4()))
+
+ def test_delete_attempt_wrong_session(self, setup_database_for_all_tests):
+ """Research exists but belongs to a different session_id →
+ AttemptNotFound (scoped lookup refuses to return cross-session
+ rows)."""
+ SessionLocal = setup_database_for_all_tests
+ username = f"alice_{uuid.uuid4().hex[:8]}"
+ service = ChatService(username=username)
+
+ with SessionLocal() as db:
+ session_a = _make_session(db, username, title="A")
+ session_b = _make_session(db, username, title="B")
+ research_id = str(uuid.uuid4())
+ _seed_attempt(
+ db,
+ username,
+ session_a,
+ research_id,
+ research_status=ResearchStatus.FAILED.value,
+ )
+
+ # Asking for the research under session_b must 404.
+ with _service_db(SessionLocal):
+ with pytest.raises(AttemptNotFound):
+ service.delete_attempt(session_b, research_id)
+
+ def test_delete_attempt_in_progress_with_live_thread(
+ self, setup_database_for_all_tests
+ ):
+ """IN_PROGRESS + alive thread → AttemptInProgress (409 mapping)
+ and the worker is flagged for termination."""
+ SessionLocal = setup_database_for_all_tests
+ username = f"alice_{uuid.uuid4().hex[:8]}"
+ service = ChatService(username=username)
+
+ with SessionLocal() as db:
+ session_id = _make_session(db, username)
+ research_id = str(uuid.uuid4())
+ _seed_attempt(
+ db,
+ username,
+ session_id,
+ research_id,
+ research_status=ResearchStatus.IN_PROGRESS.value,
+ )
+
+ flagged = []
+ with (
+ patch(
+ "src.local_deep_research.chat.service.set_termination_flag",
+ side_effect=lambda rid: flagged.append(rid),
+ ),
+ patch(
+ "src.local_deep_research.chat.service.is_research_thread_alive",
+ return_value=True,
+ ),
+ _service_db(SessionLocal),
+ ):
+ with pytest.raises(AttemptInProgress):
+ service.delete_attempt(session_id, research_id)
+
+ # Worker was flagged before the raise.
+ assert flagged == [research_id]
+
+ # Row still exists — we refused to hard-delete.
+ with SessionLocal() as db:
+ assert (
+ db.query(ResearchHistory).filter_by(id=research_id).first()
+ is not None
+ )
+
+ def test_delete_attempt_stale_in_progress_reclaims(
+ self, setup_database_for_all_tests
+ ):
+ """IN_PROGRESS but thread is dead → reclaimed and deleted (200),
+ not 409."""
+ SessionLocal = setup_database_for_all_tests
+ username = f"alice_{uuid.uuid4().hex[:8]}"
+ service = ChatService(username=username)
+
+ with SessionLocal() as db:
+ session_id = _make_session(db, username)
+ research_id = str(uuid.uuid4())
+ _seed_attempt(
+ db,
+ username,
+ session_id,
+ research_id,
+ research_status=ResearchStatus.IN_PROGRESS.value,
+ )
+
+ # is_research_thread_alive returns False → sweep reclaims.
+ with (
+ patch(
+ "src.local_deep_research.chat.service.is_research_thread_alive",
+ return_value=False,
+ ),
+ _service_db(SessionLocal),
+ ):
+ assert service.delete_attempt(session_id, research_id) is True
+
+ with SessionLocal() as db:
+ assert (
+ db.query(ResearchHistory).filter_by(id=research_id).first()
+ is None
+ )
+
+
+# ===========================================================================
+# Service-level: ChatService.get_original_attempt_query
+# ===========================================================================
+
+
+class TestGetOriginalAttemptQuery:
+ """Direct ChatService.get_original_attempt_query tests."""
+
+ def test_uses_research_meta_message_id_fast_path(
+ self, setup_database_for_all_tests
+ ):
+ SessionLocal = setup_database_for_all_tests
+ username = f"alice_{uuid.uuid4().hex[:8]}"
+ service = ChatService(username=username)
+
+ with SessionLocal() as db:
+ session_id = _make_session(db, username)
+ research_id = str(uuid.uuid4())
+ _seed_attempt(
+ db,
+ username,
+ session_id,
+ research_id,
+ user_content="Probe question",
+ include_research_meta=True,
+ )
+
+ with _service_db(SessionLocal):
+ result = service.get_original_attempt_query(session_id, research_id)
+ assert result == "Probe question"
+
+ def test_falls_back_to_chatmessage_query_when_meta_missing(
+ self, setup_database_for_all_tests
+ ):
+ """Older rows predate research_meta; the fallback lookup by
+ ChatMessage.research_id + role='user' must succeed."""
+ SessionLocal = setup_database_for_all_tests
+ username = f"alice_{uuid.uuid4().hex[:8]}"
+ service = ChatService(username=username)
+
+ with SessionLocal() as db:
+ session_id = _make_session(db, username)
+ research_id = str(uuid.uuid4())
+ _seed_attempt(
+ db,
+ username,
+ session_id,
+ research_id,
+ user_content="Legacy query",
+ include_research_meta=False,
+ )
+
+ with _service_db(SessionLocal):
+ result = service.get_original_attempt_query(session_id, research_id)
+ assert result == "Legacy query"
+
+ def test_missing_research_raises(self, setup_database_for_all_tests):
+ SessionLocal = setup_database_for_all_tests
+ username = f"alice_{uuid.uuid4().hex[:8]}"
+ service = ChatService(username=username)
+
+ with SessionLocal() as db:
+ session_id = _make_session(db, username)
+
+ with _service_db(SessionLocal):
+ with pytest.raises(AttemptNotFound):
+ service.get_original_attempt_query(
+ session_id, str(uuid.uuid4())
+ )
+
+
+# ===========================================================================
+# HTTP-level: DELETE /api/chat/sessions/<sid>/attempts/<rid>
+# ===========================================================================
+
+
+class TestDeleteAttemptRoute:
+ """HTTP tests for the delete-attempt endpoint."""
+
+ def test_delete_happy_path(self, authenticated_client):
+ """DELETE removes the attempt and returns 200."""
+ create_resp = authenticated_client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "test"},
+ content_type="application/json",
+ )
+ session_id = json.loads(create_resp.data)["session_id"]
+
+ # Drive a real send_message with mocked spawn so we get a real
+ # ResearchHistory + ChatMessage + step row to delete.
+ with patch("local_deep_research.chat.routes.start_research_process"):
+ send_resp = authenticated_client.post(
+ f"/api/chat/sessions/{session_id}/messages",
+ json={"content": "what is X?", "trigger_research": True},
+ content_type="application/json",
+ )
+ assert send_resp.status_code == 200
+ research_id = json.loads(send_resp.data)["research_id"]
+ assert research_id is not None
+
+ # Sanity: research exists, message_count is at least 1.
+ get_resp = authenticated_client.get(f"/api/chat/sessions/{session_id}")
+ assert get_resp.status_code == 200
+ assert json.loads(get_resp.data)["session"]["message_count"] >= 1
+
+ # Now delete the attempt.
+ del_resp = authenticated_client.delete(
+ f"/api/chat/sessions/{session_id}/attempts/{research_id}"
+ )
+ assert del_resp.status_code == 200
+ assert json.loads(del_resp.data)["success"] is True
+
+ def test_delete_missing_research_returns_404(self, authenticated_client):
+ create_resp = authenticated_client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "test"},
+ content_type="application/json",
+ )
+ session_id = json.loads(create_resp.data)["session_id"]
+
+ del_resp = authenticated_client.delete(
+ f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}"
+ )
+ assert del_resp.status_code == 404
+
+ def test_delete_missing_session_returns_404(self, authenticated_client):
+ """Unknown session_id → 404 (research can't belong to it)."""
+ del_resp = authenticated_client.delete(
+ f"/api/chat/sessions/{uuid.uuid4()}/attempts/{uuid.uuid4()}"
+ )
+ assert del_resp.status_code == 404
+
+ def test_delete_in_progress_returns_409(self, authenticated_client):
+ """IN_PROGRESS research with a live thread → 409 with
+ active_research_id."""
+ create_resp = authenticated_client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "test"},
+ content_type="application/json",
+ )
+ session_id = json.loads(create_resp.data)["session_id"]
+
+ with patch("local_deep_research.chat.routes.start_research_process"):
+ send_resp = authenticated_client.post(
+ f"/api/chat/sessions/{session_id}/messages",
+ json={"content": "what is X?", "trigger_research": True},
+ content_type="application/json",
+ )
+ research_id = json.loads(send_resp.data)["research_id"]
+
+ # Patch is_research_thread_alive to True so delete_attempt
+ # treats the just-spawned research as live.
+ with patch(
+ "local_deep_research.chat.service.is_research_thread_alive",
+ return_value=True,
+ ):
+ del_resp = authenticated_client.delete(
+ f"/api/chat/sessions/{session_id}/attempts/{research_id}"
+ )
+
+ assert del_resp.status_code == 409
+ body = json.loads(del_resp.data)
+ assert body["success"] is False
+ assert body["active_research_id"] == research_id
+
+
+# ===========================================================================
+# HTTP-level: POST /api/chat/sessions/<sid>/attempts/<rid>/retry
+# ===========================================================================
+
+
+class TestRetryAttemptRoute:
+ """HTTP tests for the retry-attempt endpoint."""
+
+ def test_retry_happy_path_returns_new_research_id(
+ self, authenticated_client
+ ):
+ """Retry of a FAILED attempt: returns 200 + a fresh research_id
+ + message_id."""
+ create_resp = authenticated_client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "test"},
+ content_type="application/json",
+ )
+ session_id = json.loads(create_resp.data)["session_id"]
+
+ with patch("local_deep_research.chat.routes.start_research_process"):
+ send_resp = authenticated_client.post(
+ f"/api/chat/sessions/{session_id}/messages",
+ json={"content": "what is X?", "trigger_research": True},
+ content_type="application/json",
+ )
+ old_research_id = json.loads(send_resp.data)["research_id"]
+
+ # The retry route's stale-row sweep only fires for rows older
+ # than the grace window (30s); the just-spawned research is
+ # brand-new so the sweep skips it and the per-session guard
+ # would refuse with 409. Patch the cap check to short-circuit
+ # so we can exercise the actual delete + re-spawn path. The
+ # cap-check itself is covered by the dedicated 409 test below.
+ # Also patch is_research_thread_alive=False so delete_attempt's
+ # own IN_PROGRESS check reclaims the row instead of refusing.
+ with (
+ patch(
+ "local_deep_research.chat.routes._enforce_chat_session_research_slot",
+ return_value=None,
+ ),
+ patch(
+ "local_deep_research.chat.service.is_research_thread_alive",
+ return_value=False,
+ ),
+ patch("local_deep_research.chat.routes.start_research_process"),
+ ):
+ retry_resp = authenticated_client.post(
+ f"/api/chat/sessions/{session_id}/attempts/{old_research_id}/retry"
+ )
+
+ assert retry_resp.status_code == 200, retry_resp.data
+ body = json.loads(retry_resp.data)
+ assert body["success"] is True
+ new_research_id = body["research_id"]
+ new_message_id = body["message_id"]
+ assert new_research_id is not None
+ assert new_message_id is not None
+ # The retry produced a DIFFERENT research id (the old one was
+ # deleted; new UUID allocated).
+ assert new_research_id != old_research_id
+
+ def test_retry_missing_research_returns_404(self, authenticated_client):
+ create_resp = authenticated_client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "test"},
+ content_type="application/json",
+ )
+ session_id = json.loads(create_resp.data)["session_id"]
+
+ retry_resp = authenticated_client.post(
+ f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}/retry"
+ )
+ assert retry_resp.status_code == 404
+
+ def test_retry_on_missing_session_returns_404(self, authenticated_client):
+ retry_resp = authenticated_client.post(
+ f"/api/chat/sessions/{uuid.uuid4()}/attempts/{uuid.uuid4()}/retry"
+ )
+ assert retry_resp.status_code == 404
+
+ def test_retry_archived_session_returns_409(self, authenticated_client):
+ """Archived sessions are read-only; retry must refuse."""
+ create_resp = authenticated_client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "test"},
+ content_type="application/json",
+ )
+ session_id = json.loads(create_resp.data)["session_id"]
+
+ # Archive it.
+ archived = authenticated_client.patch(
+ f"/api/chat/sessions/{session_id}",
+ json={"status": "archived"},
+ content_type="application/json",
+ )
+ assert archived.status_code == 200
+
+ retry_resp = authenticated_client.post(
+ f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}/retry"
+ )
+ assert retry_resp.status_code == 409
+
+
+# ===========================================================================
+# CSRF enforcement
+# ===========================================================================
+
+
+class TestAttemptEndpointsCSRF:
+ """DELETE and POST retry must reject requests without a CSRF token."""
+
+ def test_delete_without_csrf_token_rejected(
+ self, csrf_authenticated_client
+ ):
+ client, token = csrf_authenticated_client
+
+ create_resp = client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "Test"},
+ content_type="application/json",
+ headers={"X-CSRFToken": token},
+ )
+ assert create_resp.status_code == 200
+ session_id = json.loads(create_resp.data)["session_id"]
+
+ # DELETE without token — must be rejected.
+ response = client.delete(
+ f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}"
+ )
+ assert response.status_code == 400
+
+ def test_retry_without_csrf_token_rejected(self, csrf_authenticated_client):
+ client, token = csrf_authenticated_client
+
+ create_resp = client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "Test"},
+ content_type="application/json",
+ headers={"X-CSRFToken": token},
+ )
+ assert create_resp.status_code == 200
+ session_id = json.loads(create_resp.data)["session_id"]
+
+ # POST retry without token — must be rejected.
+ response = client.post(
+ f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}/retry"
+ )
+ assert response.status_code == 400
diff --git a/tests/js/components/chat-message-actions.test.js b/tests/js/components/chat-message-actions.test.js
new file mode 100644
index 0000000000..76e5310968
--- /dev/null
+++ b/tests/js/components/chat-message-actions.test.js
@@ -0,0 +1,152 @@
+/**
+ * Tests for the per-message Copy action in chat.js (#4659 / PR #4689).
+ *
+ * The Copy/Retry/Delete affordances are wired through a single delegated
+ * click listener on #chat-messages (handleMessageActionClick), so we drive
+ * them by building the real action-button DOM and dispatching clicks — the
+ * handlers themselves are private to the chat IIFE.
+ *
+ * Focus: handleCopyMessage clipboard write + the transient icon swap, and a
+ * regression guard for the rapid-double-click timer race (clicking copy
+ * twice within 1.2s must NOT leave the button stuck on the checkmark).
+ */
+import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest';
+
+function buildChatDom() {
+ document.body.innerHTML = `
+ <div id="chat-welcome"></div>
+ <textarea id="chat-input"></textarea>
+ <button id="send-btn"></button>
+ <div id="chat-title"></div>
+ <div id="chat-messages" role="log"></div>
+ `;
+}
+
+/** Build an assistant message + action row matching _appendMessageActions. */
+function addCopyableMessage(copyContent = 'hello world') {
+ const messages = document.getElementById('chat-messages');
+ const msg = document.createElement('div');
+ msg.className = 'ldr-chat-message ldr-chat-message-assistant';
+ const content = document.createElement('div');
+ content.className = 'ldr-chat-message-content';
+ const actions = document.createElement('div');
+ actions.className = 'ldr-chat-message-actions';
+ actions.dataset.copyContent = copyContent;
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'ldr-chat-msg-action ldr-chat-msg-action-copy';
+ btn.dataset.action = 'copy';
+ btn.setAttribute('aria-label', 'Copy response');
+ const icon = document.createElement('i');
+ icon.className = 'fas fa-copy';
+ btn.appendChild(icon);
+ actions.appendChild(btn);
+ content.appendChild(actions);
+ msg.appendChild(content);
+ messages.appendChild(msg);
+ return { btn, icon };
+}
+
+const flush = async (n = 6) => {
+ for (let i = 0; i < n; i++) await Promise.resolve();
+};
+
+const click = (el) =>
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+
+describe('chat.js — per-message Copy action', () => {
+ let writeText;
+
+ beforeEach(async () => {
+ vi.resetModules();
+ buildChatDom();
+ writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ value: { writeText },
+ configurable: true,
+ });
+ Object.defineProperty(window, 'isSecureContext', {
+ value: true,
+ configurable: true,
+ });
+ // Keep init()'s awaited session restore from throwing.
+ globalThis.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: async () => ({ sessions: [] }),
+ });
+ window.ui = { renderMarkdown: (t) => t };
+ window.api = { getCsrfToken: () => '' };
+ window.socket = {
+ on: vi.fn(),
+ subscribeToResearch: vi.fn(),
+ unsubscribeFromResearch: vi.fn(),
+ };
+ // Import AFTER the DOM + globals exist so the IIFE's init() finds
+ // #chat-messages and attaches the delegated click listener.
+ await import('@js/components/chat.js');
+ await flush();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ document.body.innerHTML = '';
+ });
+
+ it('writes the message content to the clipboard and shows a checkmark', async () => {
+ const { btn, icon } = addCopyableMessage('copy me please');
+ click(icon);
+ await flush();
+
+ expect(writeText).toHaveBeenCalledWith('copy me please');
+ expect(icon.className).toBe('fas fa-check');
+ expect(btn.getAttribute('aria-label')).toBe('Copied');
+ });
+
+ it('restores the original icon and label after the 1.2s window', async () => {
+ vi.useFakeTimers();
+ const { btn, icon } = addCopyableMessage();
+ click(icon);
+ await flush();
+ expect(icon.className).toBe('fas fa-check');
+
+ vi.advanceTimersByTime(1200);
+ expect(icon.className).toBe('fas fa-copy');
+ expect(btn.getAttribute('aria-label')).toBe('Copy response');
+ });
+
+ it('rapid double-click does not leave the icon stuck on the checkmark', async () => {
+ // Regression guard: before the fix the second click captured the
+ // checkmark as the "original", so the later restore timer reverted
+ // the icon to the checkmark and it stayed stuck.
+ vi.useFakeTimers();
+ const { icon } = addCopyableMessage();
+
+ click(icon);
+ await flush();
+ vi.advanceTimersByTime(500); // second click well within the window
+ click(icon);
+ await flush();
+ expect(icon.className).toBe('fas fa-check');
+
+ // Let every scheduled restore fire.
+ vi.advanceTimersByTime(2000);
+ expect(icon.className).toBe('fas fa-copy');
+ });
+
+ it('falls back to execCommand when the async clipboard is unavailable', async () => {
+ Object.defineProperty(navigator, 'clipboard', {
+ value: undefined,
+ configurable: true,
+ });
+ const exec = vi.fn().mockReturnValue(true);
+ document.execCommand = exec;
+ const { icon } = addCopyableMessage('legacy path');
+ click(icon);
+ await flush();
+
+ expect(exec).toHaveBeenCalledWith('copy');
+ expect(icon.className).toBe('fas fa-check');
+ });
+});