Seth Claude Sonnet 5 commited on
Commit
810c33d
·
1 Parent(s): 1d7a01a

Fix LinkedIn campaign generation reliability, quality, and persistence

Browse files

- Stop silently swallowing generation errors as fake generic fallback
content; retry once on transient OpenAI failures, then surface a
typed failure instead of writing fabricated sequence rows.
- Fix step-order/message-numbering bugs so LinkedIn steps keep the
wizard's configured order and messages aren't mislabeled by list
position.
- Enforce the LinkedIn connection-note character cap server-side and
tighten the prompt to require concrete personalization and ban
generic filler openers.
- Give campaigns a real backend record (UploadedFile campaign_name/
status/updated_at + list/detail/meta-patch/delete routes) instead of
browser localStorage, which had a bug where a parse failure would
silently repopulate demo data over real campaigns.
- Reconcile the dashboard from the backend list, auto-save campaign
identity from the wizard on every step, and re-fetch the saved
sequence plan/prompts when reopening a campaign so content and
configuration survive closing and reopening the tab.
- Surface per-contact generation failures in the wizard UI (with
retry) instead of silently claiming success when nothing was
actually generated.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

backend/app/database.py CHANGED
@@ -135,7 +135,10 @@ class UploadedFile(Base):
135
  contact_count = Column(Integer)
136
  file_path = Column(String)
137
  sequence_plan_json = Column(Text, nullable=True)
 
 
138
  created_at = Column(DateTime, default=datetime.utcnow)
 
139
 
140
 
141
  class Prompt(Base):
@@ -772,6 +775,12 @@ def run_migrations(connection_engine):
772
  ufcols = [c["name"] for c in insp.get_columns("uploaded_files")]
773
  if "sequence_plan_json" not in ufcols:
774
  conn.execute(text("ALTER TABLE uploaded_files ADD COLUMN sequence_plan_json TEXT"))
 
 
 
 
 
 
775
 
776
  insp = inspect(connection_engine)
777
  if insp.has_table("unipile_accounts"):
 
135
  contact_count = Column(Integer)
136
  file_path = Column(String)
137
  sequence_plan_json = Column(Text, nullable=True)
138
+ campaign_name = Column(String, nullable=True) # user-facing campaign name — the backend record of "this campaign exists"
139
+ status = Column(String, default="draft") # draft | generating | ready | launched
140
  created_at = Column(DateTime, default=datetime.utcnow)
141
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
142
 
143
 
144
  class Prompt(Base):
 
775
  ufcols = [c["name"] for c in insp.get_columns("uploaded_files")]
776
  if "sequence_plan_json" not in ufcols:
777
  conn.execute(text("ALTER TABLE uploaded_files ADD COLUMN sequence_plan_json TEXT"))
778
+ if "campaign_name" not in ufcols:
779
+ conn.execute(text("ALTER TABLE uploaded_files ADD COLUMN campaign_name TEXT"))
780
+ if "status" not in ufcols:
781
+ conn.execute(text("ALTER TABLE uploaded_files ADD COLUMN status TEXT DEFAULT 'draft'"))
782
+ if "updated_at" not in ufcols:
783
+ conn.execute(text("ALTER TABLE uploaded_files ADD COLUMN updated_at DATETIME"))
784
 
785
  insp = inspect(connection_engine)
786
  if insp.has_table("unipile_accounts"):
backend/app/gpt_service.py CHANGED
@@ -547,10 +547,7 @@ def generate_linkedin_sequence(
547
  if campaign_sequence and isinstance(campaign_sequence.get("linkedin_actions"), list):
548
  li_actions = [str(x) for x in campaign_sequence["linkedin_actions"] if x]
549
  if li_actions:
550
- connects = [a for a in li_actions if a == "linkedin_connect"]
551
- dms = [a for a in li_actions if a == "linkedin_dm"]
552
- other = [a for a in li_actions if a not in ("linkedin_connect", "linkedin_dm")]
553
- li_actions = connects + dms + other
554
  num_messages = len(li_actions)
555
  else:
556
  num_messages = 3
@@ -606,21 +603,52 @@ Every message MUST end with "Best Regards" on its own line, then the sender name
606
  {f'Use exactly this sender sign-off name: {li_sign}' if li_sign else 'Use {{sender_name}} on the sign-off line if no sender name was provided for this run.'}
607
  For connection request notes (~280 chars total), keep the body concise but still include the sign-off when possible.
608
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609
  Output format (strict) — use exactly these {num_messages} labeled blocks and nothing beyond:
610
  {output_blocks}
611
 
612
  Use the contact's real first name where a greeting is appropriate. Do not use placeholder tokens like {{{{first_name}}}} in the final output."""
613
 
614
- response = client.chat.completions.create(
615
- model="gpt-4o-mini",
616
- messages=[
617
- {"role": "system", "content": system_prompt},
618
- {"role": "user", "content": user_prompt},
619
- ],
620
- temperature=0.7,
621
- max_tokens=1800,
622
- )
623
- generated_text = response.choices[0].message.content or ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624
 
625
  messages: List[Dict[str, Any]] = []
626
  lines = generated_text.split("\n")
@@ -667,17 +695,32 @@ Use the contact's real first name where a greeting is appropriate. Do not use pl
667
  )
668
  messages.append({"email_number": 1, "subject": "", "body": chunk})
669
 
670
- # Keep only the first N parsed messages when the model returns extras (campaign plan is authoritative).
671
- if len(messages) > num_messages:
672
- messages = messages[:num_messages]
 
 
 
 
 
 
 
 
 
673
 
674
  out = []
675
- for idx, m in enumerate(messages, start=1):
 
676
  body = normalize_linkedin_message_format(
677
  m["body"] or "",
678
  first_name=first_name,
679
  signoff=li_sign,
680
  )
 
 
 
 
 
681
  out.append(
682
  {
683
  "first_name": first_name or "",
@@ -686,36 +729,24 @@ Use the contact's real first name where a greeting is appropriate. Do not use pl
686
  "company": company or "",
687
  "title": title or "",
688
  "product": product_name,
689
- "email_number": idx,
690
  "subject": "",
691
  "email_content": body,
692
  }
693
  )
 
 
694
  return out
695
  except Exception as e:
696
- logger.warning("Error generating LinkedIn sequence: %s", e)
697
- fn = safe_str(contact.get("first_name") or contact.get("First Name") or "there")
698
- company = safe_str(
699
- contact.get("company") or contact.get("Company") or contact.get("Organization") or "your company"
700
- )
701
- email = safe_str(contact.get("email") or contact.get("Email") or "")
702
- li_fb = (sender_linkedin_name or "").strip()
703
- fb_body = normalize_linkedin_message_format(
704
- f"Hi {fn},\n\nQuick note on {product_name} for {company} — happy to compare notes if useful.",
705
- first_name=fn,
706
- signoff=li_fb,
707
  )
708
  return [
709
  {
710
- "first_name": fn,
711
- "last_name": safe_str(contact.get("last_name") or contact.get("Last Name") or ""),
712
- "email": email,
713
- "company": company,
714
- "title": safe_str(contact.get("title") or contact.get("Title") or ""),
715
- "product": product_name,
716
- "email_number": 1,
717
- "subject": "",
718
- "email_content": fb_body,
719
  }
720
  ]
721
 
 
547
  if campaign_sequence and isinstance(campaign_sequence.get("linkedin_actions"), list):
548
  li_actions = [str(x) for x in campaign_sequence["linkedin_actions"] if x]
549
  if li_actions:
550
+ # Preserve the wizard's actual configured order — do not regroup connects before DMs.
 
 
 
551
  num_messages = len(li_actions)
552
  else:
553
  num_messages = 3
 
603
  {f'Use exactly this sender sign-off name: {li_sign}' if li_sign else 'Use {{sender_name}} on the sign-off line if no sender name was provided for this run.'}
604
  For connection request notes (~280 chars total), keep the body concise but still include the sign-off when possible.
605
 
606
+ PERSONALIZATION (required, not optional):
607
+ - Every message must reference at least one concrete, specific detail about THIS contact — their
608
+ actual title, their company's likely focus given its name/industry, or their location/industry —
609
+ woven naturally into the message. Do not write a message that would be equally true of any
610
+ random contact; if you can't point to the specific sentence that only fits {first_name or 'this person'}
611
+ at {company or 'their company'}, rewrite it.
612
+ - Give a specific, credible reason THIS person would want to connect or reply — tied to their role
613
+ or company, not a generic claim about your product being useful to "companies like yours."
614
+ - Banned openers and filler — do not use these or close paraphrases of them: "Quick note on",
615
+ "happy to compare notes", "I came across your profile", "I noticed you work at", "reaching out
616
+ because", "hope this finds you well", "just wanted to connect". Open with something specific to
617
+ the contact instead.
618
+ - Do not pad with vague enthusiasm ("excited to", "would love to") in place of substance. Every
619
+ sentence should earn its place.
620
+
621
  Output format (strict) — use exactly these {num_messages} labeled blocks and nothing beyond:
622
  {output_blocks}
623
 
624
  Use the contact's real first name where a greeting is appropriate. Do not use placeholder tokens like {{{{first_name}}}} in the final output."""
625
 
626
+ generated_text = ""
627
+ last_api_error: Optional[Exception] = None
628
+ for attempt in range(2): # one retry on transient OpenAI errors
629
+ try:
630
+ response = client.chat.completions.create(
631
+ model="gpt-4o-mini",
632
+ messages=[
633
+ {"role": "system", "content": system_prompt},
634
+ {"role": "user", "content": user_prompt},
635
+ ],
636
+ temperature=0.7,
637
+ max_tokens=1800,
638
+ )
639
+ generated_text = response.choices[0].message.content or ""
640
+ last_api_error = None
641
+ break
642
+ except Exception as api_err:
643
+ last_api_error = api_err
644
+ if attempt == 0:
645
+ logger.warning(
646
+ "LinkedIn sequence OpenAI call failed for %s, retrying once: %s",
647
+ email, api_err,
648
+ )
649
+ time.sleep(1.0)
650
+ if last_api_error is not None:
651
+ raise last_api_error
652
 
653
  messages: List[Dict[str, Any]] = []
654
  lines = generated_text.split("\n")
 
695
  )
696
  messages.append({"email_number": 1, "subject": "", "body": chunk})
697
 
698
+ # Keep the model's own "Message N" label (not list position) so a message the model
699
+ # explicitly labeled #3 never gets silently relabeled #2 if #2 failed to parse. Clamp to
700
+ # the expected range and drop duplicates/out-of-range labels (campaign plan is authoritative).
701
+ seen_n: set = set()
702
+ deduped: List[Dict[str, Any]] = []
703
+ for m in messages:
704
+ n = m["email_number"]
705
+ if not isinstance(n, int) or n < 1 or n > num_messages or n in seen_n:
706
+ continue
707
+ seen_n.add(n)
708
+ deduped.append(m)
709
+ messages = sorted(deduped, key=lambda m: m["email_number"])
710
 
711
  out = []
712
+ for m in messages:
713
+ n = m["email_number"]
714
  body = normalize_linkedin_message_format(
715
  m["body"] or "",
716
  first_name=first_name,
717
  signoff=li_sign,
718
  )
719
+ # Server-side enforce LinkedIn's connection-note length cap rather than trusting the
720
+ # model to self-limit — only applies to whichever message is the connection request.
721
+ is_connect = li_actions[n - 1] == "linkedin_connect" if li_actions and n <= len(li_actions) else (n == 1)
722
+ if is_connect:
723
+ body = linkedin_invite_note(body)
724
  out.append(
725
  {
726
  "first_name": first_name or "",
 
729
  "company": company or "",
730
  "title": title or "",
731
  "product": product_name,
732
+ "email_number": n,
733
  "subject": "",
734
  "email_content": body,
735
  }
736
  )
737
+ if not out:
738
+ raise ValueError("LinkedIn sequence generation produced no usable messages after parsing")
739
  return out
740
  except Exception as e:
741
+ logger.exception(
742
+ "LinkedIn sequence generation failed for contact %s (product=%s): %s",
743
+ safe_str(contact.get("email") or contact.get("Email") or ""), product_name, e,
 
 
 
 
 
 
 
 
744
  )
745
  return [
746
  {
747
+ "generation_failed": True,
748
+ "error": str(e),
749
+ "email": safe_str(contact.get("email") or contact.get("Email") or ""),
 
 
 
 
 
 
750
  }
751
  ]
752
 
backend/app/main.py CHANGED
@@ -46,12 +46,14 @@ from .database import (
46
  UnipileHostedAuthState,
47
  OutreachSendReceipt,
48
  ChatAgentConfig,
 
49
  )
50
  from pydantic import ValidationError
51
 
52
  from .models import (
53
  UploadResponse,
54
  PromptSaveRequest,
 
55
  SequenceResponse,
56
  SmartleadPushRequest,
57
  SmartleadRunResponse,
@@ -2737,6 +2739,9 @@ async def generate_linkedin_campaign_sequences(
2737
  li_list = generate_linkedin_sequence(
2738
  contact, body.prompt_template, campaign.name, sender_linkedin_name=li_sig or None
2739
  )
 
 
 
2740
  for seq_data in li_list:
2741
  db.add(
2742
  GeneratedSequence(
@@ -4818,6 +4823,11 @@ async def save_prompts(request: PromptSaveRequest, t: TenantContext = Depends(ge
4818
  if uf is not None:
4819
  if request.sequence_plan is not None:
4820
  uf.sequence_plan_json = json.dumps(request.sequence_plan)
 
 
 
 
 
4821
  db.commit()
4822
 
4823
  return {"message": "Prompts saved successfully"}
@@ -4825,6 +4835,151 @@ async def save_prompts(request: PromptSaveRequest, t: TenantContext = Depends(ge
4825
  raise HTTPException(status_code=500, detail=f"Error saving prompts: {str(e)}")
4826
 
4827
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4828
  def _normalize_campaign_plan_steps(raw_data) -> Optional[List[Dict]]:
4829
  if raw_data is None:
4830
  return None
@@ -4869,10 +5024,8 @@ def _parse_campaign_plan_pack(db_file) -> Optional[Dict[str, Any]]:
4869
  gmail_specs.append({"step_order": ord_global, "title": title})
4870
  elif ch == "linkedin" and act in ("linkedin_connect", "linkedin_dm"):
4871
  li_wizard.append({"step_order": ord_global, "action": act, "title": title})
4872
- li_connects = [x for x in li_wizard if x["action"] == "linkedin_connect"]
4873
- li_dms = [x for x in li_wizard if x["action"] == "linkedin_dm"]
4874
- li_other = [x for x in li_wizard if x["action"] not in ("linkedin_connect", "linkedin_dm")]
4875
- li_for_gpt = li_connects + li_dms + li_other
4876
  total_actions = len(gmail_specs) + len(li_wizard)
4877
  if total_actions == 0:
4878
  return None
@@ -5373,49 +5526,55 @@ async def generate_sequences(
5373
  li_product,
5374
  )
5375
 
5376
- for i, seq_data in enumerate(li_list):
5377
- step_order_v = None
5378
- if plan_pack and li_meta_for_rows and i < len(li_meta_for_rows):
5379
- step_order_v = li_meta_for_rows[i]["step_order"]
5380
- db_sequence = GeneratedSequence(
5381
- tenant_id=tenant_id,
5382
- file_id=file_id,
5383
- sequence_id=sequence_id,
5384
- email_number=seq_data["email_number"],
5385
- channel="linkedin",
5386
- first_name=seq_data["first_name"],
5387
- last_name=seq_data["last_name"],
5388
- email=seq_data["email"],
5389
- company=seq_data["company"],
5390
- title=seq_data.get("title", ""),
5391
- product=seq_data["product"],
5392
- subject=seq_data.get("subject") or "",
5393
- email_content=seq_data["email_content"],
5394
- step_order=step_order_v,
5395
- )
5396
- db.add(db_sequence)
5397
-
5398
- db.commit()
5399
-
5400
- for i, seq_data in enumerate(li_list):
5401
- step_order_v = None
5402
- if plan_pack and li_meta_for_rows and i < len(li_meta_for_rows):
5403
- step_order_v = li_meta_for_rows[i]["step_order"]
5404
- sequence_response = {
5405
- "id": sequence_id,
5406
- "emailNumber": seq_data["email_number"],
5407
- "firstName": seq_data["first_name"],
5408
- "lastName": seq_data["last_name"],
5409
- "email": seq_data["email"],
5410
- "company": seq_data["company"],
5411
- "title": seq_data.get("title", ""),
5412
- "product": seq_data["product"],
5413
- "subject": seq_data.get("subject") or "",
5414
- "emailContent": seq_data["email_content"],
5415
- "channel": "linkedin",
5416
- "stepOrder": step_order_v,
5417
- }
5418
- yield f"data: {json.dumps({'type': 'sequence', 'sequence': sequence_response})}\n\n"
 
 
 
 
 
 
5419
 
5420
  prog = plan_progress_pct() if plan_pack else progress_pct(sequence_id, linkedin_phase=True)
5421
  yield f"data: {json.dumps({'type': 'progress', 'progress': prog})}\n\n"
 
46
  UnipileHostedAuthState,
47
  OutreachSendReceipt,
48
  ChatAgentConfig,
49
+ FileOutreachExecution,
50
  )
51
  from pydantic import ValidationError
52
 
53
  from .models import (
54
  UploadResponse,
55
  PromptSaveRequest,
56
+ CampaignMetaPatchRequest,
57
  SequenceResponse,
58
  SmartleadPushRequest,
59
  SmartleadRunResponse,
 
2739
  li_list = generate_linkedin_sequence(
2740
  contact, body.prompt_template, campaign.name, sender_linkedin_name=li_sig or None
2741
  )
2742
+ if li_list and li_list[0].get("generation_failed"):
2743
+ sequence_id += 1
2744
+ continue
2745
  for seq_data in li_list:
2746
  db.add(
2747
  GeneratedSequence(
 
4823
  if uf is not None:
4824
  if request.sequence_plan is not None:
4825
  uf.sequence_plan_json = json.dumps(request.sequence_plan)
4826
+ if request.campaign_name is not None:
4827
+ uf.campaign_name = request.campaign_name
4828
+ if request.status is not None:
4829
+ uf.status = request.status
4830
+ uf.updated_at = datetime.utcnow()
4831
  db.commit()
4832
 
4833
  return {"message": "Prompts saved successfully"}
 
4835
  raise HTTPException(status_code=500, detail=f"Error saving prompts: {str(e)}")
4836
 
4837
 
4838
+ @app.patch("/api/campaign-files/{file_id}/meta")
4839
+ async def patch_campaign_meta(
4840
+ file_id: str, body: CampaignMetaPatchRequest, t: TenantContext = Depends(get_tenant_context)
4841
+ ):
4842
+ """Lightweight auto-save for campaign name/status — called on every wizard step transition
4843
+ so the campaign stays discoverable from the backend even if the tab closes before Launch."""
4844
+ db = t.db
4845
+ if body.file_id != file_id:
4846
+ raise HTTPException(status_code=400, detail="file_id mismatch")
4847
+ uf = (
4848
+ db.query(UploadedFile)
4849
+ .filter(UploadedFile.tenant_id == t.tenant_id, UploadedFile.file_id == file_id)
4850
+ .first()
4851
+ )
4852
+ if not uf:
4853
+ raise HTTPException(status_code=404, detail="Campaign file not found")
4854
+ if body.campaign_name is not None:
4855
+ uf.campaign_name = body.campaign_name
4856
+ if body.status is not None:
4857
+ uf.status = body.status
4858
+ uf.updated_at = datetime.utcnow()
4859
+ db.commit()
4860
+ return {"ok": True}
4861
+
4862
+
4863
+ @app.get("/api/campaign-files")
4864
+ async def list_campaign_files(t: TenantContext = Depends(get_tenant_context)):
4865
+ """Tenant-scoped list of campaigns — the backend record of "this campaign exists" that the
4866
+ frontend campaigns dashboard reads from instead of browser localStorage."""
4867
+ db = t.db
4868
+ rows = (
4869
+ db.query(UploadedFile)
4870
+ .filter(UploadedFile.tenant_id == t.tenant_id)
4871
+ .order_by(UploadedFile.created_at.desc())
4872
+ .all()
4873
+ )
4874
+ if not rows:
4875
+ return {"campaigns": []}
4876
+ file_ids = [r.file_id for r in rows]
4877
+ counts = dict(
4878
+ db.query(GeneratedSequence.file_id, func.count(GeneratedSequence.id))
4879
+ .filter(GeneratedSequence.tenant_id == t.tenant_id, GeneratedSequence.file_id.in_(file_ids))
4880
+ .group_by(GeneratedSequence.file_id)
4881
+ .all()
4882
+ )
4883
+ out = []
4884
+ for r in rows:
4885
+ plan_pack = _parse_campaign_plan_pack(r)
4886
+ expected = (r.contact_count or 0) * (plan_pack["total_actions"] if plan_pack else 1)
4887
+ out.append(
4888
+ {
4889
+ "file_id": r.file_id,
4890
+ "campaign_name": r.campaign_name or r.filename or r.file_id,
4891
+ "filename": r.filename or "",
4892
+ "contact_count": r.contact_count or 0,
4893
+ "status": r.status or "draft",
4894
+ "created_at": r.created_at.isoformat() if r.created_at else None,
4895
+ "updated_at": r.updated_at.isoformat() if r.updated_at else None,
4896
+ "generated_count": counts.get(r.file_id, 0),
4897
+ "expected_count": expected,
4898
+ "has_sequence_plan": bool((r.sequence_plan_json or "").strip()),
4899
+ }
4900
+ )
4901
+ return {"campaigns": out}
4902
+
4903
+
4904
+ @app.delete("/api/campaign-files/{file_id}")
4905
+ async def delete_campaign_file(file_id: str, t: TenantContext = Depends(get_tenant_context)):
4906
+ """Delete a campaign and everything generated for it. Cascades manually since these rows
4907
+ were never modeled with DB-level ON DELETE CASCADE."""
4908
+ db = t.db
4909
+ uf = (
4910
+ db.query(UploadedFile)
4911
+ .filter(UploadedFile.tenant_id == t.tenant_id, UploadedFile.file_id == file_id)
4912
+ .first()
4913
+ )
4914
+ if not uf:
4915
+ raise HTTPException(status_code=404, detail="Campaign file not found")
4916
+ for model in (GeneratedSequence, Prompt, OutreachSendReceipt, FileOutreachExecution):
4917
+ db.query(model).filter(model.tenant_id == t.tenant_id, model.file_id == file_id).delete(
4918
+ synchronize_session=False
4919
+ )
4920
+ db.delete(uf)
4921
+ db.commit()
4922
+ return {"ok": True}
4923
+
4924
+
4925
+ @app.get("/api/campaign-files/{file_id}")
4926
+ async def get_campaign_file_detail(file_id: str, t: TenantContext = Depends(get_tenant_context)):
4927
+ """Full campaign detail — sequence plan + saved prompts — for reopening the wizard on a
4928
+ campaign whose local browser state was lost (cleared storage, different device/tab)."""
4929
+ db = t.db
4930
+ uf = (
4931
+ db.query(UploadedFile)
4932
+ .filter(UploadedFile.tenant_id == t.tenant_id, UploadedFile.file_id == file_id)
4933
+ .first()
4934
+ )
4935
+ if not uf:
4936
+ raise HTTPException(status_code=404, detail="Campaign file not found")
4937
+
4938
+ sequence_plan = None
4939
+ parallel_tracks = False
4940
+ raw = (uf.sequence_plan_json or "").strip()
4941
+ if raw:
4942
+ try:
4943
+ parsed = json.loads(raw)
4944
+ if isinstance(parsed, dict) and isinstance(parsed.get("steps"), list):
4945
+ sequence_plan = parsed["steps"]
4946
+ parallel_tracks = bool(parsed.get("parallel_tracks"))
4947
+ elif isinstance(parsed, list):
4948
+ sequence_plan = parsed
4949
+ except Exception:
4950
+ sequence_plan = None
4951
+
4952
+ prompt_rows = (
4953
+ db.query(Prompt)
4954
+ .filter(Prompt.tenant_id == t.tenant_id, Prompt.file_id == file_id)
4955
+ .all()
4956
+ )
4957
+ prompts = {
4958
+ p.product_name: p.prompt_template
4959
+ for p in prompt_rows
4960
+ if (getattr(p, "prompt_kind", None) or "email") == "email"
4961
+ }
4962
+ linkedin_prompts = {
4963
+ p.product_name: p.prompt_template
4964
+ for p in prompt_rows
4965
+ if getattr(p, "prompt_kind", None) == "linkedin"
4966
+ }
4967
+ products = sorted(set(prompts.keys()) | set(linkedin_prompts.keys()))
4968
+
4969
+ return {
4970
+ "file_id": uf.file_id,
4971
+ "campaign_name": uf.campaign_name or uf.filename or uf.file_id,
4972
+ "filename": uf.filename or "",
4973
+ "contact_count": uf.contact_count or 0,
4974
+ "status": uf.status or "draft",
4975
+ "sequence_plan": sequence_plan,
4976
+ "parallel_tracks": parallel_tracks,
4977
+ "prompts": prompts,
4978
+ "linkedin_prompts": linkedin_prompts,
4979
+ "products": products,
4980
+ }
4981
+
4982
+
4983
  def _normalize_campaign_plan_steps(raw_data) -> Optional[List[Dict]]:
4984
  if raw_data is None:
4985
  return None
 
5024
  gmail_specs.append({"step_order": ord_global, "title": title})
5025
  elif ch == "linkedin" and act in ("linkedin_connect", "linkedin_dm"):
5026
  li_wizard.append({"step_order": ord_global, "action": act, "title": title})
5027
+ # Preserve the wizard's actual configured order — do not regroup connects before DMs.
5028
+ li_for_gpt = li_wizard
 
 
5029
  total_actions = len(gmail_specs) + len(li_wizard)
5030
  if total_actions == 0:
5031
  return None
 
5526
  li_product,
5527
  )
5528
 
5529
+ li_failed = bool(li_list) and li_list[0].get("generation_failed")
5530
+ if li_failed:
5531
+ yield f"data: {json.dumps({'type': 'contact_error', 'channel': 'linkedin', 'sequence_id': sequence_id, 'email': li_list[0].get('email', ''), 'error': li_list[0].get('error', '')})}\n\n"
5532
+ else:
5533
+ def _step_order_for(seq_data):
5534
+ if not (plan_pack and li_meta_for_rows):
5535
+ return None
5536
+ idx = seq_data["email_number"] - 1
5537
+ if 0 <= idx < len(li_meta_for_rows):
5538
+ return li_meta_for_rows[idx]["step_order"]
5539
+ return None
5540
+
5541
+ for seq_data in li_list:
5542
+ db_sequence = GeneratedSequence(
5543
+ tenant_id=tenant_id,
5544
+ file_id=file_id,
5545
+ sequence_id=sequence_id,
5546
+ email_number=seq_data["email_number"],
5547
+ channel="linkedin",
5548
+ first_name=seq_data["first_name"],
5549
+ last_name=seq_data["last_name"],
5550
+ email=seq_data["email"],
5551
+ company=seq_data["company"],
5552
+ title=seq_data.get("title", ""),
5553
+ product=seq_data["product"],
5554
+ subject=seq_data.get("subject") or "",
5555
+ email_content=seq_data["email_content"],
5556
+ step_order=_step_order_for(seq_data),
5557
+ )
5558
+ db.add(db_sequence)
5559
+
5560
+ db.commit()
5561
+
5562
+ for seq_data in li_list:
5563
+ sequence_response = {
5564
+ "id": sequence_id,
5565
+ "emailNumber": seq_data["email_number"],
5566
+ "firstName": seq_data["first_name"],
5567
+ "lastName": seq_data["last_name"],
5568
+ "email": seq_data["email"],
5569
+ "company": seq_data["company"],
5570
+ "title": seq_data.get("title", ""),
5571
+ "product": seq_data["product"],
5572
+ "subject": seq_data.get("subject") or "",
5573
+ "emailContent": seq_data["email_content"],
5574
+ "channel": "linkedin",
5575
+ "stepOrder": _step_order_for(seq_data),
5576
+ }
5577
+ yield f"data: {json.dumps({'type': 'sequence', 'sequence': sequence_response})}\n\n"
5578
 
5579
  prog = plan_progress_pct() if plan_pack else progress_pct(sequence_id, linkedin_phase=True)
5580
  yield f"data: {json.dumps({'type': 'progress', 'progress': prog})}\n\n"
backend/app/models.py CHANGED
@@ -29,6 +29,18 @@ class PromptSaveRequest(BaseModel):
29
  products: List[str]
30
  linkedin_prompts: Dict[str, str] = Field(default_factory=dict)
31
  sequence_plan: Optional[Union[List[Dict], Dict[str, Any]]] = Field(default=None)
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
 
34
  class SequenceResponse(BaseModel):
 
29
  products: List[str]
30
  linkedin_prompts: Dict[str, str] = Field(default_factory=dict)
31
  sequence_plan: Optional[Union[List[Dict], Dict[str, Any]]] = Field(default=None)
32
+ campaign_name: Optional[str] = None
33
+ status: Optional[str] = None
34
+
35
+
36
+ class CampaignMetaPatchRequest(BaseModel):
37
+ """Lightweight auto-save for campaign identity, independent of the full prompts/sequence
38
+ payload — called on every wizard step transition so an abrupt tab close never strands
39
+ already-generated content with no backend pointer back to it."""
40
+
41
+ file_id: str
42
+ campaign_name: Optional[str] = None
43
+ status: Optional[str] = None
44
 
45
 
46
  class SequenceResponse(BaseModel):
frontend/src/components/campaigns/CampaignsDashboardTab.jsx CHANGED
@@ -28,6 +28,7 @@ function uid() {
28
  const DEMO_CAMPAIGNS = [
29
  {
30
  id: 'demo_1',
 
31
  name: 'Q4 Enterprise SaaS Reachout',
32
  status: 'running',
33
  contacts: 2450,
@@ -46,6 +47,7 @@ const DEMO_CAMPAIGNS = [
46
  },
47
  {
48
  id: 'demo_2',
 
49
  name: 'Inbound Demo Follow-up',
50
  status: 'paused',
51
  contacts: 840,
@@ -60,6 +62,7 @@ const DEMO_CAMPAIGNS = [
60
  },
61
  {
62
  id: 'demo_3',
 
63
  name: 'Holiday Special Offer',
64
  status: 'draft',
65
  contacts: 5000,
@@ -115,24 +118,47 @@ function formatCreatedAt(iso) {
115
  function loadCampaigns() {
116
  try {
117
  const raw = localStorage.getItem(STORAGE_KEY);
118
- if (raw) {
 
 
 
 
119
  const parsed = JSON.parse(raw);
120
- if (Array.isArray(parsed) && parsed.length) return parsed.map(normalizeCampaign);
121
  }
122
  } catch {
123
- /* ignore */
124
  }
125
  return DEMO_CAMPAIGNS.map(normalizeCampaign);
126
  }
127
 
128
  function saveCampaigns(list) {
129
  try {
130
- localStorage.setItem(STORAGE_KEY, JSON.stringify(list));
 
131
  } catch {
132
  /* ignore */
133
  }
134
  }
135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  function progressFromGenerationStatus(status) {
137
  if (status?.is_complete) return 100;
138
  const total = status.total_contacts || 0;
@@ -272,6 +298,22 @@ export default function CampaignsDashboardTab() {
272
 
273
  startCampaignExecutionRef.current = startCampaignExecution;
274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  const startBackgroundGeneration = useCallback((campaignId, fileId, { resume = false } = {}) => {
276
  const existing = generationStreamsRef.current.get(fileId);
277
  if (existing) {
@@ -336,6 +378,37 @@ export default function CampaignsDashboardTab() {
336
  saveCampaigns(campaigns);
337
  }, [campaigns]);
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  useEffect(() => {
340
  const tick = async () => {
341
  const list = campaignsRef.current.filter(
@@ -613,10 +686,18 @@ export default function CampaignsDashboardTab() {
613
  return;
614
  }
615
  const drop = new Set(selectedIds);
 
 
 
616
  setCampaigns((prev) => prev.filter((c) => !drop.has(c.id)));
617
  setSelectedIds([]);
618
  setMenuOpenId(null);
619
  closeBulkMenu();
 
 
 
 
 
620
  }, [selectedIds, closeBulkMenu]);
621
 
622
  const toggleStatus = useCallback(async (id) => {
@@ -687,9 +768,15 @@ export default function CampaignsDashboardTab() {
687
  }, []);
688
 
689
  const deleteCampaign = useCallback((id) => {
 
690
  setCampaigns((prev) => prev.filter((c) => c.id !== id));
691
  setMenuOpenId(null);
692
  setSelectedIds((prev) => prev.filter((x) => x !== id));
 
 
 
 
 
693
  }, []);
694
 
695
  const restartDelivery = useCallback(async (c) => {
@@ -798,6 +885,7 @@ export default function CampaignsDashboardTab() {
798
  return [row, ...prev];
799
  });
800
  setWizardCampaign(null);
 
801
  if (payload.fileId && payload.startBackgroundGeneration) {
802
  startBackgroundGeneration(id, payload.fileId, {
803
  resume: !!payload.resumeGeneration,
@@ -805,7 +893,7 @@ export default function CampaignsDashboardTab() {
805
  } else if (payload.fileId && payload.generationComplete) {
806
  void startCampaignExecution(id, payload.fileId);
807
  }
808
- }, [startBackgroundGeneration, startCampaignExecution]);
809
 
810
  const onWizardDraftPersist = useCallback((payload) => {
811
  if (!payload?.fileId && !payload?.id) return;
@@ -863,7 +951,8 @@ export default function CampaignsDashboardTab() {
863
  }
864
  return [row, ...prev];
865
  });
866
- }, []);
 
867
 
868
  const openWizardForCreate = useCallback(() => {
869
  setWizardCampaign(null);
 
28
  const DEMO_CAMPAIGNS = [
29
  {
30
  id: 'demo_1',
31
+ isDemo: true,
32
  name: 'Q4 Enterprise SaaS Reachout',
33
  status: 'running',
34
  contacts: 2450,
 
47
  },
48
  {
49
  id: 'demo_2',
50
+ isDemo: true,
51
  name: 'Inbound Demo Follow-up',
52
  status: 'paused',
53
  contacts: 840,
 
62
  },
63
  {
64
  id: 'demo_3',
65
+ isDemo: true,
66
  name: 'Holiday Special Offer',
67
  status: 'draft',
68
  contacts: 5000,
 
118
  function loadCampaigns() {
119
  try {
120
  const raw = localStorage.getItem(STORAGE_KEY);
121
+ // Only ever fall back to demo placeholders when the key has literally never been
122
+ // written (first-ever visit). A present-but-empty or present-but-corrupt value means
123
+ // the user has real state (or had some) — showing demo data here would get persisted
124
+ // right back over it by the save effect below and destroy it.
125
+ if (raw != null) {
126
  const parsed = JSON.parse(raw);
127
+ if (Array.isArray(parsed)) return parsed.map(normalizeCampaign);
128
  }
129
  } catch {
130
+ return [];
131
  }
132
  return DEMO_CAMPAIGNS.map(normalizeCampaign);
133
  }
134
 
135
  function saveCampaigns(list) {
136
  try {
137
+ // Demo placeholders are never real data — never let them land in persisted storage.
138
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(list.filter((c) => !c.isDemo)));
139
  } catch {
140
  /* ignore */
141
  }
142
  }
143
 
144
+ function backendCampaignToLocal(bc) {
145
+ const expected = Number(bc.expected_count) || 0;
146
+ const generated = Number(bc.generated_count) || 0;
147
+ const generationComplete = expected > 0 && generated >= expected;
148
+ return {
149
+ id: bc.file_id,
150
+ name: bc.campaign_name || bc.filename || 'Untitled campaign',
151
+ status: bc.status === 'launched' ? 'running' : bc.status || 'draft',
152
+ contacts: bc.contact_count || 0,
153
+ fileId: bc.file_id,
154
+ prospectFileName: bc.filename || '',
155
+ generationComplete,
156
+ generationProgressPercent: expected > 0 ? Math.round((generated / expected) * 100) : 0,
157
+ createdAt: bc.created_at || new Date().toISOString(),
158
+ lastEditedLabel: null,
159
+ };
160
+ }
161
+
162
  function progressFromGenerationStatus(status) {
163
  if (status?.is_complete) return 100;
164
  const total = status.total_contacts || 0;
 
298
 
299
  startCampaignExecutionRef.current = startCampaignExecution;
300
 
301
+ // Fire-and-forget backend record of campaign identity, called on every step transition/save
302
+ // so a campaign is discoverable from GET /api/campaign-files even if the tab closes before
303
+ // the wizard's final "Launch" step.
304
+ const persistCampaignMeta = useCallback((fileId, { campaignName, status } = {}) => {
305
+ if (!fileId) return;
306
+ apiFetch(`/api/campaign-files/${encodeURIComponent(fileId)}/meta`, {
307
+ method: 'PATCH',
308
+ headers: { 'Content-Type': 'application/json' },
309
+ body: JSON.stringify({
310
+ file_id: fileId,
311
+ campaign_name: campaignName ?? null,
312
+ status: status ?? null,
313
+ }),
314
+ }).catch((e) => console.error(e));
315
+ }, []);
316
+
317
  const startBackgroundGeneration = useCallback((campaignId, fileId, { resume = false } = {}) => {
318
  const existing = generationStreamsRef.current.get(fileId);
319
  if (existing) {
 
378
  saveCampaigns(campaigns);
379
  }, [campaigns]);
380
 
381
+ // Backend-list reconciliation: UploadedFile rows (via /api/campaign-files) are the
382
+ // authoritative record of "this campaign exists." Merge in anything the backend knows about
383
+ // that isn't already in local state, so a campaign survives even if localStorage was cleared,
384
+ // corrupted, or never had it (different device/profile/browser).
385
+ useEffect(() => {
386
+ let cancelled = false;
387
+ (async () => {
388
+ try {
389
+ const r = await apiFetch('/api/campaign-files');
390
+ if (!r.ok || cancelled) return;
391
+ const data = await r.json().catch(() => ({}));
392
+ const rows = Array.isArray(data.campaigns) ? data.campaigns : [];
393
+ if (!rows.length) return;
394
+ setCampaigns((prev) => {
395
+ const known = new Set(prev.filter((c) => c.fileId).map((c) => c.fileId));
396
+ const additions = rows
397
+ .filter((bc) => bc.file_id && !known.has(bc.file_id))
398
+ .map((bc) => normalizeCampaign(backendCampaignToLocal(bc)));
399
+ if (!additions.length) return prev;
400
+ const withoutDemo = prev.filter((c) => !c.isDemo);
401
+ return [...additions, ...withoutDemo];
402
+ });
403
+ } catch {
404
+ /* backend unreachable — keep whatever local/cached state we already have */
405
+ }
406
+ })();
407
+ return () => {
408
+ cancelled = true;
409
+ };
410
+ }, []);
411
+
412
  useEffect(() => {
413
  const tick = async () => {
414
  const list = campaignsRef.current.filter(
 
686
  return;
687
  }
688
  const drop = new Set(selectedIds);
689
+ const fileIdsToDelete = campaignsRef.current
690
+ .filter((c) => drop.has(c.id) && c.fileId)
691
+ .map((c) => c.fileId);
692
  setCampaigns((prev) => prev.filter((c) => !drop.has(c.id)));
693
  setSelectedIds([]);
694
  setMenuOpenId(null);
695
  closeBulkMenu();
696
+ for (const fid of fileIdsToDelete) {
697
+ apiFetch(`/api/campaign-files/${encodeURIComponent(fid)}`, { method: 'DELETE' }).catch(
698
+ (e) => console.error(e)
699
+ );
700
+ }
701
  }, [selectedIds, closeBulkMenu]);
702
 
703
  const toggleStatus = useCallback(async (id) => {
 
768
  }, []);
769
 
770
  const deleteCampaign = useCallback((id) => {
771
+ const fileId = campaignsRef.current.find((c) => c.id === id)?.fileId;
772
  setCampaigns((prev) => prev.filter((c) => c.id !== id));
773
  setMenuOpenId(null);
774
  setSelectedIds((prev) => prev.filter((x) => x !== id));
775
+ if (fileId) {
776
+ apiFetch(`/api/campaign-files/${encodeURIComponent(fileId)}`, { method: 'DELETE' }).catch(
777
+ (e) => console.error(e)
778
+ );
779
+ }
780
  }, []);
781
 
782
  const restartDelivery = useCallback(async (c) => {
 
885
  return [row, ...prev];
886
  });
887
  setWizardCampaign(null);
888
+ persistCampaignMeta(payload.fileId, { campaignName: payload.name, status: 'running' });
889
  if (payload.fileId && payload.startBackgroundGeneration) {
890
  startBackgroundGeneration(id, payload.fileId, {
891
  resume: !!payload.resumeGeneration,
 
893
  } else if (payload.fileId && payload.generationComplete) {
894
  void startCampaignExecution(id, payload.fileId);
895
  }
896
+ }, [startBackgroundGeneration, startCampaignExecution, persistCampaignMeta]);
897
 
898
  const onWizardDraftPersist = useCallback((payload) => {
899
  if (!payload?.fileId && !payload?.id) return;
 
951
  }
952
  return [row, ...prev];
953
  });
954
+ persistCampaignMeta(payload.fileId, { campaignName: payload.name, status: 'draft' });
955
+ }, [persistCampaignMeta]);
956
 
957
  const openWizardForCreate = useCallback(() => {
958
  setWizardCampaign(null);
frontend/src/components/campaigns/CreateCampaignWizard.jsx CHANGED
@@ -18,6 +18,7 @@ import {
18
  MessageCircle,
19
  Clock,
20
  ChevronRight,
 
21
  } from 'lucide-react';
22
  import { Button } from '@/components/ui/button';
23
  import { Input } from '@/components/ui/input';
@@ -157,6 +158,7 @@ function WizardSequencePreview({
157
  selectedProducts,
158
  sequenceHasLinkedin,
159
  genPhase,
 
160
  }) {
161
  const [searchQuery, setSearchQuery] = useState('');
162
  const [filterProduct, setFilterProduct] = useState('all');
@@ -191,7 +193,11 @@ function WizardSequencePreview({
191
  <div className="mb-2 rounded-2xl border border-slate-200 bg-white p-6">
192
  <div className="mb-4 flex items-center justify-between">
193
  <div className="flex items-center gap-3">
194
- {generationComplete ? (
 
 
 
 
195
  <div className="rounded-xl bg-green-100 p-3">
196
  <CheckCircle2 className="h-6 w-6 text-green-600" />
197
  </div>
@@ -202,7 +208,11 @@ function WizardSequencePreview({
202
  )}
203
  <div>
204
  <h3 className="font-semibold text-slate-800">
205
- {generationComplete ? 'Generation complete!' : `Generating ${phaseLabel}…`}
 
 
 
 
206
  </h3>
207
  <p className="text-sm text-slate-500">
208
  {contacts.length} contacts · {sequences.length} generated rows
@@ -352,6 +362,7 @@ export default function CreateCampaignWizard({
352
  const [genPhase, setGenPhase] = useState('email');
353
  const [genRunId, setGenRunId] = useState(0);
354
  const [genPreviewOnly, setGenPreviewOnly] = useState(false);
 
355
  const eventSourceRef = useRef(null);
356
  const promptEditorRef = useRef(null);
357
  const prevGenRunIdRef = useRef(null);
@@ -394,6 +405,7 @@ export default function CreateCampaignWizard({
394
  setGenPhase('email');
395
  setGenRunId(0);
396
  setGenPreviewOnly(false);
 
397
  prevGenRunIdRef.current = null;
398
  previewTriggeredRef.current = false;
399
  }, []);
@@ -412,6 +424,23 @@ export default function CreateCampaignWizard({
412
  }
413
  }, [open, initialCampaign?.id, reset]);
414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
  useEffect(() => {
416
  if (!open || !initialCampaign?.id) return;
417
  if (hydratedCampaignIdRef.current === initialCampaign.id) return;
@@ -442,11 +471,49 @@ export default function CreateCampaignWizard({
442
  setWizardUpload(null);
443
  }
444
  const seq = initialCampaign.sequence;
445
- if (Array.isArray(seq) && seq.length > 0) {
 
446
  setSequenceSteps(seq);
447
  } else {
448
  setSequenceSteps(createDefaultSequenceSteps());
449
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
450
  setParallelTracks(!!initialCampaign.parallelTracks);
451
  setSelectedProducts(
452
  Array.isArray(initialCampaign.selectedProducts) ? initialCampaign.selectedProducts : []
@@ -645,6 +712,7 @@ export default function CreateCampaignWizard({
645
  sequence_plan: parallelTracks
646
  ? { parallel_tracks: true, steps: sequenceSteps }
647
  : sequenceSteps,
 
648
  }),
649
  });
650
  if (!res.ok) {
@@ -659,6 +727,7 @@ export default function CreateCampaignWizard({
659
  sequenceHasLinkedin,
660
  sequenceSteps,
661
  parallelTracks,
 
662
  ]);
663
 
664
  const startGenerationRun = useCallback(
@@ -685,6 +754,7 @@ export default function CreateCampaignWizard({
685
  const isNewRun = prevGenRunIdRef.current !== genRunId;
686
  if (isNewRun) {
687
  prevGenRunIdRef.current = genRunId;
 
688
  }
689
 
690
  if (eventSourceRef.current) {
@@ -723,6 +793,11 @@ export default function CreateCampaignWizard({
723
  setGenProgress(data.progress);
724
  } else if (data.type === 'phase' && data.phase === 'linkedin') {
725
  setGenPhase('linkedin');
 
 
 
 
 
726
  } else if (data.type === 'preview_complete') {
727
  setGenRunning(false);
728
  setGenPreviewOnly(false);
@@ -1109,17 +1184,32 @@ export default function CreateCampaignWizard({
1109
  />
1110
  {selectedProducts.length > 0 ? (
1111
  <>
1112
- {!genRunning && !genComplete ? (
1113
  <div className="rounded-xl border-2 border-violet-300 bg-gradient-to-br from-violet-50 via-white to-purple-50 p-5 shadow-sm shadow-violet-100/80">
1114
  <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
1115
  <div>
1116
  <p className="text-base font-semibold text-slate-900">
1117
- Generate personalized content
 
 
1118
  </p>
1119
  <p className="mt-1 max-w-xl text-sm text-slate-600">
1120
- Click <strong className="font-semibold text-violet-800">Generate</strong> to
1121
- create emails and LinkedIn copy for all contacts. You can also skip this and
1122
- continue — we&apos;ll auto-preview the first contact on the next step.
 
 
 
 
 
 
 
 
 
 
 
 
 
1123
  </p>
1124
  </div>
1125
  <Button
@@ -1130,7 +1220,7 @@ export default function CreateCampaignWizard({
1130
  onClick={handleGenerate}
1131
  >
1132
  <Sparkles className="mr-2 h-5 w-5" />
1133
- Generate all contacts
1134
  </Button>
1135
  </div>
1136
  </div>
@@ -1150,12 +1240,29 @@ export default function CreateCampaignWizard({
1150
  <Loader2 className="h-4 w-4 shrink-0 animate-spin" />
1151
  Generating in the background — you can continue to Review &amp; Launch anytime.
1152
  </div>
1153
- ) : genComplete ? (
1154
  <div className="flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800">
1155
  <CheckCircle2 className="h-4 w-4 shrink-0" />
1156
  All contact content generated. Continue to review and launch.
1157
  </div>
1158
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1159
  <WizardSequencePreview
1160
  contacts={genContacts}
1161
  sequences={genSequences}
@@ -1167,6 +1274,7 @@ export default function CreateCampaignWizard({
1167
  selectedProducts={selectedProducts}
1168
  sequenceHasLinkedin={sequenceHasLinkedin}
1169
  genPhase={genPhase}
 
1170
  />
1171
  </>
1172
  ) : (
@@ -1220,6 +1328,14 @@ export default function CreateCampaignWizard({
1220
  ) : null}
1221
  </div>
1222
  ) : null}
 
 
 
 
 
 
 
 
1223
  <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50/80 px-4 py-3 text-sm text-slate-700">
1224
  <div>
1225
  <span className="font-semibold text-slate-900">{campaignName || 'Campaign'}</span>
 
18
  MessageCircle,
19
  Clock,
20
  ChevronRight,
21
+ AlertTriangle,
22
  } from 'lucide-react';
23
  import { Button } from '@/components/ui/button';
24
  import { Input } from '@/components/ui/input';
 
158
  selectedProducts,
159
  sequenceHasLinkedin,
160
  genPhase,
161
+ hasFailures,
162
  }) {
163
  const [searchQuery, setSearchQuery] = useState('');
164
  const [filterProduct, setFilterProduct] = useState('all');
 
193
  <div className="mb-2 rounded-2xl border border-slate-200 bg-white p-6">
194
  <div className="mb-4 flex items-center justify-between">
195
  <div className="flex items-center gap-3">
196
+ {generationComplete && hasFailures ? (
197
+ <div className="rounded-xl bg-amber-100 p-3">
198
+ <AlertTriangle className="h-6 w-6 text-amber-600" />
199
+ </div>
200
+ ) : generationComplete ? (
201
  <div className="rounded-xl bg-green-100 p-3">
202
  <CheckCircle2 className="h-6 w-6 text-green-600" />
203
  </div>
 
208
  )}
209
  <div>
210
  <h3 className="font-semibold text-slate-800">
211
+ {generationComplete
212
+ ? hasFailures
213
+ ? 'Generation finished with errors'
214
+ : 'Generation complete!'
215
+ : `Generating ${phaseLabel}…`}
216
  </h3>
217
  <p className="text-sm text-slate-500">
218
  {contacts.length} contacts · {sequences.length} generated rows
 
362
  const [genPhase, setGenPhase] = useState('email');
363
  const [genRunId, setGenRunId] = useState(0);
364
  const [genPreviewOnly, setGenPreviewOnly] = useState(false);
365
+ const [genFailedContacts, setGenFailedContacts] = useState([]);
366
  const eventSourceRef = useRef(null);
367
  const promptEditorRef = useRef(null);
368
  const prevGenRunIdRef = useRef(null);
 
405
  setGenPhase('email');
406
  setGenRunId(0);
407
  setGenPreviewOnly(false);
408
+ setGenFailedContacts([]);
409
  prevGenRunIdRef.current = null;
410
  previewTriggeredRef.current = false;
411
  }, []);
 
424
  }
425
  }, [open, initialCampaign?.id, reset]);
426
 
427
+ // Debounced backend auto-save of campaign identity — fires on name edits and every step
428
+ // transition, not only when the wizard is explicitly closed, so an abrupt tab close never
429
+ // strands already-generated server-side content with no way back to it.
430
+ useEffect(() => {
431
+ if (!open || !wizardUpload?.fileId) return;
432
+ const fileId = wizardUpload.fileId;
433
+ const name = campaignName.trim() || 'Untitled campaign';
434
+ const timer = setTimeout(() => {
435
+ apiFetch(`/api/campaign-files/${encodeURIComponent(fileId)}/meta`, {
436
+ method: 'PATCH',
437
+ headers: { 'Content-Type': 'application/json' },
438
+ body: JSON.stringify({ file_id: fileId, campaign_name: name, status: 'draft' }),
439
+ }).catch((e) => console.error(e));
440
+ }, 800);
441
+ return () => clearTimeout(timer);
442
+ }, [open, wizardUpload?.fileId, campaignName, step]);
443
+
444
  useEffect(() => {
445
  if (!open || !initialCampaign?.id) return;
446
  if (hydratedCampaignIdRef.current === initialCampaign.id) return;
 
471
  setWizardUpload(null);
472
  }
473
  const seq = initialCampaign.sequence;
474
+ const hasLocalSequence = Array.isArray(seq) && seq.length > 0;
475
+ if (hasLocalSequence) {
476
  setSequenceSteps(seq);
477
  } else {
478
  setSequenceSteps(createDefaultSequenceSteps());
479
  }
480
+ // Local dashboard state can be missing the sequence entirely — e.g. a campaign
481
+ // reconciled in from the backend list on a fresh session never had local `sequence`
482
+ // populated. Fall back to the backend's saved sequence_plan_json so reopening a
483
+ // campaign never silently resets it to the default Gmail-only template.
484
+ if (!hasLocalSequence && initialCampaign.fileId) {
485
+ const fid = initialCampaign.fileId;
486
+ const campaignId = initialCampaign.id;
487
+ (async () => {
488
+ try {
489
+ const res = await apiFetch(`/api/campaign-files/${encodeURIComponent(fid)}`);
490
+ if (!res.ok) return;
491
+ const detail = await res.json();
492
+ if (hydratedCampaignIdRef.current !== campaignId) return;
493
+ if (Array.isArray(detail.sequence_plan) && detail.sequence_plan.length > 0) {
494
+ setSequenceSteps(detail.sequence_plan);
495
+ setParallelTracks(!!detail.parallel_tracks);
496
+ }
497
+ if (detail.prompts && Object.keys(detail.prompts).length) {
498
+ setPrompts((prev) => (Object.keys(prev).length ? prev : detail.prompts));
499
+ }
500
+ if (detail.linkedin_prompts && Object.keys(detail.linkedin_prompts).length) {
501
+ setLinkedinPrompts((prev) =>
502
+ Object.keys(prev).length ? prev : detail.linkedin_prompts
503
+ );
504
+ }
505
+ if (Array.isArray(detail.products) && detail.products.length) {
506
+ setSelectedProducts((prev) =>
507
+ prev.length
508
+ ? prev
509
+ : detail.products.map((name, i) => ({ id: `backend-${i}-${name}`, name }))
510
+ );
511
+ }
512
+ } catch (e) {
513
+ console.error(e);
514
+ }
515
+ })();
516
+ }
517
  setParallelTracks(!!initialCampaign.parallelTracks);
518
  setSelectedProducts(
519
  Array.isArray(initialCampaign.selectedProducts) ? initialCampaign.selectedProducts : []
 
712
  sequence_plan: parallelTracks
713
  ? { parallel_tracks: true, steps: sequenceSteps }
714
  : sequenceSteps,
715
+ campaign_name: campaignName.trim() || 'Untitled campaign',
716
  }),
717
  });
718
  if (!res.ok) {
 
727
  sequenceHasLinkedin,
728
  sequenceSteps,
729
  parallelTracks,
730
+ campaignName,
731
  ]);
732
 
733
  const startGenerationRun = useCallback(
 
754
  const isNewRun = prevGenRunIdRef.current !== genRunId;
755
  if (isNewRun) {
756
  prevGenRunIdRef.current = genRunId;
757
+ setGenFailedContacts([]);
758
  }
759
 
760
  if (eventSourceRef.current) {
 
793
  setGenProgress(data.progress);
794
  } else if (data.type === 'phase' && data.phase === 'linkedin') {
795
  setGenPhase('linkedin');
796
+ } else if (data.type === 'contact_error') {
797
+ setGenFailedContacts((prev) => [
798
+ ...prev,
799
+ { email: data.email || '', channel: data.channel || '', error: data.error || '' },
800
+ ]);
801
  } else if (data.type === 'preview_complete') {
802
  setGenRunning(false);
803
  setGenPreviewOnly(false);
 
1184
  />
1185
  {selectedProducts.length > 0 ? (
1186
  <>
1187
+ {!genRunning && (!genComplete || genFailedContacts.length > 0) ? (
1188
  <div className="rounded-xl border-2 border-violet-300 bg-gradient-to-br from-violet-50 via-white to-purple-50 p-5 shadow-sm shadow-violet-100/80">
1189
  <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
1190
  <div>
1191
  <p className="text-base font-semibold text-slate-900">
1192
+ {genFailedContacts.length > 0
1193
+ ? 'Retry failed contacts'
1194
+ : 'Generate personalized content'}
1195
  </p>
1196
  <p className="mt-1 max-w-xl text-sm text-slate-600">
1197
+ {genFailedContacts.length > 0 ? (
1198
+ <>
1199
+ Some contacts failed to generate. Click{' '}
1200
+ <strong className="font-semibold text-violet-800">
1201
+ Retry generation
1202
+ </strong>{' '}
1203
+ to regenerate content for all contacts.
1204
+ </>
1205
+ ) : (
1206
+ <>
1207
+ Click <strong className="font-semibold text-violet-800">Generate</strong>{' '}
1208
+ to create emails and LinkedIn copy for all contacts. You can also skip
1209
+ this and continue — we&apos;ll auto-preview the first contact on the
1210
+ next step.
1211
+ </>
1212
+ )}
1213
  </p>
1214
  </div>
1215
  <Button
 
1220
  onClick={handleGenerate}
1221
  >
1222
  <Sparkles className="mr-2 h-5 w-5" />
1223
+ {genFailedContacts.length > 0 ? 'Retry generation' : 'Generate all contacts'}
1224
  </Button>
1225
  </div>
1226
  </div>
 
1240
  <Loader2 className="h-4 w-4 shrink-0 animate-spin" />
1241
  Generating in the background — you can continue to Review &amp; Launch anytime.
1242
  </div>
1243
+ ) : genComplete && genFailedContacts.length === 0 ? (
1244
  <div className="flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800">
1245
  <CheckCircle2 className="h-4 w-4 shrink-0" />
1246
  All contact content generated. Continue to review and launch.
1247
  </div>
1248
  ) : null}
1249
+ {genFailedContacts.length > 0 ? (
1250
+ <div className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
1251
+ <p className="font-medium">
1252
+ {genFailedContacts.length} contact{genFailedContacts.length === 1 ? '' : 's'} failed
1253
+ to generate — retry generation to fill in the rest.
1254
+ </p>
1255
+ <ul className="mt-1.5 max-h-24 space-y-0.5 overflow-y-auto text-xs text-amber-800">
1256
+ {genFailedContacts.slice(0, 10).map((f, i) => (
1257
+ <li key={`${f.email}-${i}`}>
1258
+ {f.email || 'Unknown contact'}
1259
+ {f.channel ? ` (${f.channel})` : ''}
1260
+ {f.error ? `: ${f.error}` : ''}
1261
+ </li>
1262
+ ))}
1263
+ </ul>
1264
+ </div>
1265
+ ) : null}
1266
  <WizardSequencePreview
1267
  contacts={genContacts}
1268
  sequences={genSequences}
 
1274
  selectedProducts={selectedProducts}
1275
  sequenceHasLinkedin={sequenceHasLinkedin}
1276
  genPhase={genPhase}
1277
+ hasFailures={genFailedContacts.length > 0}
1278
  />
1279
  </>
1280
  ) : (
 
1328
  ) : null}
1329
  </div>
1330
  ) : null}
1331
+ {!genRunning && genFailedContacts.length > 0 ? (
1332
+ <div className="rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
1333
+ <p className="font-medium">
1334
+ {genFailedContacts.length} contact{genFailedContacts.length === 1 ? '' : 's'} failed to
1335
+ generate content and will not have a sequence unless you go back and retry generation.
1336
+ </p>
1337
+ </div>
1338
+ ) : null}
1339
  <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50/80 px-4 py-3 text-sm text-slate-700">
1340
  <div>
1341
  <span className="font-semibold text-slate-900">{campaignName || 'Campaign'}</span>