Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 70 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
)
from backend.utils.attachment_utils import attachments_earlier_in, delete_session_attachments, earlier_attachments_block, process_chat_attachments
from backend.utils import progress_notes as progress_notes_utils
from backend.utils import sonic_folder as sonic_folder_utils
from backend.utils.stored_file_access import can_read_stored_file, first_readable
from backend.utils.docx_writer import DOCX_MIME, render_docx, validate_document
from backend.utils.docx_edit import DocxEditError, apply_edits as apply_docx_edits
Expand Down Expand Up @@ -105,6 +106,7 @@
from backend.utils.agent_utils import is_stale_capability_denial, scrub_stale_capability_denials
from backend.utils.embedding_utils import embed_text
from backend.utils import relevant_findings
from backend.utils import recent_facts
from backend.utils import citation_media
from backend.utils import applied_changes
from backend.utils import process_info
Expand Down Expand Up @@ -1027,6 +1029,7 @@ async def token_streamer():
final_state = {}
# Aggregate counts about how Sonic itself behaved this turn (no user, no text): backend/utils/self_counters.py.
turn_counts = new_turn_counts()
facts_shown: list = [] # the facts this reply is given for the question, marked on it so a short follow-up keeps them (backend/utils/recent_facts.py)
llm_turn = llm_turns.begin(username) # counts this turn's model calls, and adds them to this person's own count (backend/utils/llm_turns.py)
if budget_state.get("paid") and budget_state.get("level") != budget_guard.BLOCKED:
llm_turns.note_paid() # paid for out of their own credit: counted under a paid: label and charged when it finishes (backend/utils/credits.py)
Expand Down Expand Up @@ -1203,6 +1206,11 @@ def log_timings(grade: str, outcome: str):
yield f"data: {json.dumps({'event': 'change_card', **event.get('data', {})})}\n\n"
await asyncio.sleep(0.01)

# Sonic saved something to the person's notes (backend/utils/sonic_folder.py): the page shows what was saved, with Undo.
if kind == "on_custom_event" and event.get("name") == "note_card":
yield f"data: {json.dumps({'event': 'note_card', **event.get('data', {})})}\n\n"
await asyncio.sleep(0.01)

# A check Sonic asks to run on the person's own machine (backend/utils/runner_jobs.py): the page shows a card with the exact command and Run / Cancel buttons.
if kind == "on_custom_event" and event.get("name") == "command_steps":
yield f"data: {json.dumps({'event': 'command_steps', **event.get('data', {})})}\n\n"
Expand Down Expand Up @@ -1657,7 +1665,7 @@ def _read_progress_notes():
await asyncio.to_thread(load_user_facts, username)
guardrail_context = await asyncio.to_thread(fetch_relevant_corrections, username, question)
# question_embedding (computed above, before the relatable line) is threaded through both fact + semantic memory recall — they embed the identical question string this turn.
memory_context = await asyncio.to_thread(lambda: fetch_relevant_user_facts(username, question, precomputed_embedding=question_embedding, messages=chat_sessions[history_key], counts=turn_counts))
memory_context = await asyncio.to_thread(lambda: fetch_relevant_user_facts(username, question, precomputed_embedding=question_embedding, messages=chat_sessions[history_key], counts=turn_counts, shown=facts_shown))
goal_nudge_context = "" if (risk_level != RISK_NONE or open_loop_entry) else await asyncio.to_thread(fetch_goal_nudge_context, username)

if guardrail_context:
Expand Down Expand Up @@ -2223,7 +2231,7 @@ def _read_progress_notes():
tally(turn_counts, "claim_unproven")
if llm_turn.claim_sent_back:
tally(turn_counts, "claim_sent_back")
if claim_check.claims_edit(full_response) and not claim_check.edit_made(llm_turn.tools):
if claim_check.unbacked_edit_claim(full_response, llm_turn.tools):
full_response = f"{full_response}\n\n{claim_check.NO_EDIT_NOTE}" # it says it changed something and nothing was proposed this turn: said plainly, in code
tally(turn_counts, "claim_edit_unbacked")
if int((getattr(llm_turn, "rhythm", None) or {}).get("applies", 0) or 0) > 0:
Expand Down Expand Up @@ -2288,6 +2296,8 @@ def _read_progress_notes():
) # which voice wrote it and what it was shown (ids and labels only), so a thumb can be counted by voice: backend/utils/reply_stamp.py
except Exception:
logger.warning("[reply_stamp] could not stamp the reply.", exc_info=True)
if facts_shown:
ai_message.additional_kwargs[recent_facts.MARK] = facts_shown[:recent_facts.MARK_MAX]
if relatable_entry:
ai_message.additional_kwargs[RELATABLE_MARK] = True # the rate limit reads this on later turns
if encouragement_entry:
Expand Down Expand Up @@ -2679,6 +2689,7 @@ async def clear_chat(request: Request, user = Depends(get_current_user)):
await asyncio.to_thread(delete_session_attachments, username, session_id)
await asyncio.to_thread(conversation_summary_utils.clear, get_db(), username, session_id)
await asyncio.to_thread(read_log_utils.clear, get_db(), username, session_id)
await asyncio.to_thread(sonic_folder_utils.delete_session_scratch, get_db(), username, session_id)
return {"status": "cleared", "count": 1}

# No specific conversation given: wipe every conversation this user has.
Expand All @@ -2689,6 +2700,7 @@ async def clear_chat(request: Request, user = Depends(get_current_user)):
await asyncio.to_thread(delete_session_attachments, username, convo["session_id"])
await asyncio.to_thread(conversation_summary_utils.clear_all, get_db(), username)
await asyncio.to_thread(read_log_utils.clear_all, get_db(), username)
await asyncio.to_thread(sonic_folder_utils.delete_all_scratch, get_db(), username)
return {"status": "cleared", "count": len(conversations)}

@app.post("/api/upload-attachment")
Expand Down Expand Up @@ -2981,6 +2993,7 @@ async def remove_conversation(session_id: str, current_user = Depends(get_curren
await asyncio.to_thread(delete_session_attachments, username, session_id)
await asyncio.to_thread(conversation_summary_utils.clear, get_db(), username, session_id)
await asyncio.to_thread(read_log_utils.clear, get_db(), username, session_id)
await asyncio.to_thread(sonic_folder_utils.delete_session_scratch, get_db(), username, session_id)
return {"status": "deleted", "session_id": session_id}

class ConversationRename(BaseModel):
Expand Down Expand Up @@ -3442,6 +3455,15 @@ async def edit_local_docx(payload: DocxEditRequest, current_user = Depends(get_c
return Response(content=data, media_type=DOCX_MIME)


class SonicNoteEdit(BaseModel):
title: Optional[str] = None
text: Optional[str] = None


class SonicNoteUndo(BaseModel):
rev: int # the revision the card was drawn for: Undo does nothing if the note has changed since


class MemoryEdit(BaseModel):
fact: Optional[str] = None # left out to change only the category or the domain
category: Optional[str] = None
Expand Down Expand Up @@ -3799,6 +3821,52 @@ async def delete_progress_note(note_id: str, current_user = Depends(get_member_u
return {"status": "deleted"}


@app.get("/api/sonic-folder")
async def get_sonic_folder(current_user = Depends(get_member_user)):
"""Sonic's own folder for this person (backend/utils/sonic_folder.py): their notes, and the scratch files of their conversations."""
db = get_db()
if db is None:
raise HTTPException(status_code=503, detail="Your notes are not available right now.")
return await asyncio.to_thread(sonic_folder_utils.page_listing, db, current_user.get("sub"))


@app.put("/api/sonic-folder/{item_id}")
async def edit_sonic_note(item_id: str, payload: SonicNoteEdit, current_user = Depends(get_member_user)):
"""The person's own edit of one of their notes."""
db = get_db()
if db is None:
raise HTTPException(status_code=503, detail="Your notes are not available right now.")
try:
note = await asyncio.to_thread(sonic_folder_utils.edit_note, db, current_user.get("sub"), item_id, payload.title, payload.text)
except sonic_folder_utils.FolderError as problem:
raise HTTPException(status_code=400, detail=str(problem))
if note is None:
raise HTTPException(status_code=404, detail="That note was not found.")
return sonic_folder_utils.public(note)


@app.delete("/api/sonic-folder/{item_id}")
async def delete_sonic_folder_item(item_id: str, current_user = Depends(get_member_user)):
db = get_db()
if db is None:
raise HTTPException(status_code=503, detail="Your notes are not available right now.")
if not await asyncio.to_thread(sonic_folder_utils.delete_item, db, current_user.get("sub"), item_id):
raise HTTPException(status_code=404, detail="That item was not found.")
return {"status": "deleted"}


@app.post("/api/sonic-folder/{item_id}/undo")
async def undo_sonic_note(item_id: str, payload: SonicNoteUndo, current_user = Depends(get_member_user)):
"""Takes back one save, from the card under Sonic's reply. "changed" means the note was changed again since, so nothing was done."""
db = get_db()
if db is None:
raise HTTPException(status_code=503, detail="Your notes are not available right now.")
outcome = await asyncio.to_thread(sonic_folder_utils.undo_note, db, current_user.get("sub"), item_id, payload.rev)
if outcome in ("removed", "restored"):
await asyncio.to_thread(record_turn_counts, {"note_undone": 1})
return {"status": outcome}


@app.post("/api/meetings/{meeting_id}/start")
async def start_user_meeting(meeting_id: str, payload: dict = Body(...), current_user = Depends(get_member_user)):
"""Starts office hours in a conversation: only ever from the person pressing the button."""
Expand Down
22 changes: 19 additions & 3 deletions backend/components/sonic_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,9 +717,9 @@
"month": "2026-10",
"title": "My notes folder and edit approval",
"line": (
"I can keep short notes and tests in a .sonic folder in your project, and in the folder menu you can choose to ask every time, apply changes inside .sonic automatically, or apply everything this session."
"I keep a project's work log in a .sonic folder inside it, and in the folder menu you can choose to ask every time, apply changes inside .sonic automatically, or apply everything this session."
),
"keywords": [".sonic", "notes", "approval", "auto apply", "apply automatically", "edit approval", "scratchpad", "plan", "local folder", "undo"],
"keywords": [".sonic", "work log", "approval", "auto apply", "apply automatically", "edit approval", "plan", "local folder"],
"volunteer": [],
},
{
Expand Down Expand Up @@ -1716,11 +1716,12 @@
"requires": [
"backend/utils/named_facts.py::def pick",
"backend/utils/memory_utils.py::named_facts.pick",
"backend/utils/recent_facts.py::def carried_ids",
],
"month": "2026-11",
"title": "When you name something, I bring what I know about it",
"line": (
"When you mention something by name that I have notes about (a place, an employer, a person), I now bring those notes into my reply even if the rest of your message is about something else."
"When you mention something by name that I have notes about (a place, an employer, a person), I bring those notes in, and keep them for a short follow-up a message or two later."
),
"keywords": ["forgot", "didn't remember", "nothing saved", "you should know", "remember", "my notes about"],
"volunteer": [],
Expand Down Expand Up @@ -2168,4 +2169,19 @@
"keywords": ["runner", "computer", "choose", "switch", "pair"],
"volunteer": [],
},
{
"id": "own_folder",
"requires": [
"backend/utils/sonic_folder.py::def save_note",
"backend/services/sandbox_tests.py::async def run_script",
"local/src/components/NoteCard.tsx",
],
"month": "2026-11",
"title": "A folder of my own",
"line": (
"Ask me to make a note and it goes in your Notes on the Memory page, with Undo, not into your project. While coding I can also write throwaway Python scripts and run them against a copy of your folder."
),
"keywords": ["scratchpad", "scratch", "notes", "make a note", "write that down", "throwaway", "temp folder", "temporary folder"],
"volunteer": [],
},
]
Loading
Loading