Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-09-02 18:42:40 +03:00
1 parent d3238af8bd
commit c131a1b4f7
16 files changed
+3036 -505

No files matched your search

+421
View File
@@ -0,0 +1,421 @@
"""
core/audio_devices.py — pick which microphone and which speakers JARVIS uses.
WHY
Both audio streams in main.py were opened without a `device=` argument, so
they always took whatever the operating system called "default". On a laptop
with a built-in mic, a webcam mic and a headset that is a coin toss — and on
Windows the default *moves on its own* the moment you plug a headset in.
"JARVIS can't hear me" almost always means "JARVIS is listening to the
monitor's microphone".
WHY NAMES, NOT INDICES
sounddevice identifies devices by integer index, and those indices shift
whenever a device appears or disappears. Storing index 3 means that after
unplugging a USB interface the saved setting silently points at something
else. We store the device *name* and resolve it to an index at open time.
WHY THIS IS CACHED
`sd.query_devices()` talks to the host audio API and can take a few hundred
milliseconds on a Windows machine with many endpoints. Mark LV learned this
lesson the expensive way — a 2.1-second `openwakeword` import on the Qt
thread made the settings drawer look like it was broken. So the list is
fetched once on a background thread at startup and served from cache.
"""
from __future__ import annotations
import threading
import time
# The label shown for "let the OS decide", and the value stored in config for
# it. Empty string, so an untouched install and a deliberately-default install
# are the same thing — nothing changes for anyone who never opens the picker.
DEFAULT_LABEL = "System default"
DEFAULT_VALUE = ""
_cache: dict[str, list[str]] | None = None
_cache_lock = threading.Lock()
# Which host API each direction settled on, so resolve() opens the same endpoint
# the picker listed. Filled in by _query().
_chosen_api: dict = {"input": None, "output": None}
# ── Why the raw list is unusable, and what is filtered out ───────────────────
#
# `sd.query_devices()` returns one entry per (device × host API), not one per
# device. Measured on a normal Windows machine: 41 entries for what the Windows
# sound settings show as 4 microphones and 4 speakers. The same Realtek
# microphone appears four times — once each under MME, DirectSound, WASAPI and
# WDM-KS — and none of the four is labelled to say which is which.
#
# Handing that to a person is not a choice, it is a quiz. So the list is reduced
# the way the operating system's own settings panel does it:
#
# 1. ONE host API per direction — chosen by measurement, not by reasoning.
# See the preference note below.
# 2. No pseudo-devices. "Microsoft Sound Mapper", "Primary Sound Driver",
# ALSA's "default"/"sysdefault"/"dmix" are aliases for "whatever the OS
# picks" — which is precisely the "System default" entry already at the top
# of the list. Offering them again as if they were hardware is noise.
# 3. No zero-channel or unnamed entries (WASAPI reports one of each).
# 4. Deduplicated by name.
#
# Nothing is hidden that a person could actually want: the same hardware is
# still there, listed once, under the name their operating system uses for it.
# ── Preference order, which is only a starting point ─────────────────────────
#
# Two earlier versions of this file were wrong in the same way: they decided
# which host API to use by reasoning about it instead of measuring it.
#
# v1 ranked APIs by how clean their device names were and picked WASAPI.
# WASAPI in shared mode does not resample — the hardware runs at 48 kHz,
# this app streams 16 kHz in and 24 kHz out, and every open failed with
# "Invalid sample rate". The picker looked right and did nothing.
#
# v2 added a rate check and picked DirectSound, which passes that check on
# both sides. PortAudio's DirectSound *output* is a silent sink: the
# stream opens, every write returns success in ~0 ms, and nothing is ever
# heard. Same failure, one layer deeper.
#
# So this list is a preference, not a promise. Which API actually gets used is
# decided below by _usable() (open it for real) and _transport_works() (does
# audio actually move), per direction. On this platform that lands on
# DirectSound for the microphone and MME for the speakers — a split that no
# amount of reasoning would have produced.
_PREFERRED_APIS = {
"Windows": ("directsound", "mme", "wasapi"),
# macOS has only Core Audio, so there is nothing to disambiguate.
"Darwin": ("core audio",),
# PulseAudio/PipeWire present one clean endpoint per device; raw ALSA
# presents dozens of routing permutations of the same card.
"Linux": ("pulse", "pipewire", "jack", "alsa"),
}
# ── "It opens" is not "it works" ─────────────────────────────────────────────
#
# Opening a stream successfully proves nothing. Measured, writing 2.0 s of audio:
#
# device=None (MME) 2.02 s consumed in real time
# DirectSound, any output device 0.00 s swallowed instantly
#
# No flag or capability field reports this. The only thing that separates a real
# sink from a fake one is whether it consumes audio at the rate audio is
# consumed at — so that is what gets measured, once per host API per direction,
# on the background thread at startup, using silence.
#
# Each direction is probed **the way main.py actually uses it**. That is not a
# detail: DirectSound input passes a callback stream and fails a blocking read,
# so an earlier version of this probe rejected a microphone that works perfectly
# in the app. Probe the mode you ship, not the mode that is easier to write.
_PROBE_SECONDS = {"output": 0.6, "input": 0.35}
# Cache: {(api_name_or_None, kind): bool}
_probe_results: dict = {}
def _transport_works(idx: int, kind: str, api_key) -> bool:
"""Does this host API actually move audio, or only pretend to?
Probed once per API per direction and cached. Output writes silence, so the
probe is inaudible; input reads and discards."""
if api_key in _probe_results:
return _probe_results[api_key]
ok = False
try:
import sounddevice as sd
rate = _RATES.get(kind, 16000)
secs = _PROBE_SECONDS.get(kind, 0.5)
# Each direction is probed the way main.py actually uses it. That is not
# a detail: DirectSound input passes a callback stream and fails a
# blocking read, so probing the wrong mode rejected a microphone that
# works perfectly in the app.
if kind == "output":
# main.py writes with stream.write() — a real sink is rate-limited
# by the hardware clock, a fake one swallows the buffer instantly.
st = sd.RawOutputStream(samplerate=rate, channels=1, dtype="int16",
blocksize=1024, device=idx)
st.start()
t0 = time.monotonic()
st.write(bytes(int(rate * secs) * 2)) # silence — inaudible
elapsed = time.monotonic() - t0
st.stop(); st.close()
ok = elapsed > secs * 0.5
if not ok:
print(f"[Audio] output: host API reports success but moves no "
f"audio ({elapsed*1000:.0f} ms for {secs*1000:.0f} ms) "
f"— skipping it")
else:
# main.py reads through a callback — count what arrives.
frames = [0]
def _cb(indata, n, *_a):
frames[0] += n
st = sd.InputStream(samplerate=rate, channels=1, dtype="int16",
blocksize=1024, device=idx, callback=_cb)
st.start()
time.sleep(secs)
st.stop(); st.close()
ok = frames[0] > rate * secs * 0.3
if not ok:
print(f"[Audio] input: host API delivered {frames[0]} frames in "
f"{secs*1000:.0f} ms — skipping it")
except Exception as e:
print(f"[Audio] {kind} transport probe failed: {e}")
ok = False
_probe_results[api_key] = ok
return ok
def _display_name(name: str, devices) -> str:
"""MME truncates device names to 31 characters, so the API that actually
carries the audio may not be the one that can spell. If another host API
knows a longer name that starts with this one, show that instead — the user
reads 'Realtek HD Audio 2nd output (Realtek(R) Audio)' while the stream runs
on the endpoint called 'Realtek HD Audio 2nd output (Re'."""
if len(name) < 30:
return name
best = name
for dev in devices:
other = (dev.get("name") or "").strip()
if len(other) > len(best) and other.startswith(name):
best = other
return best
# The rates the app opens its streams at. Defaults match main.py; main.py calls
# configure() at startup with its own constants so the two can never drift apart
# and silently reintroduce the bug above.
_RATES = {"input": 16000, "output": 24000}
def configure(input_rate: int, output_rate: int) -> None:
"""Tell this module the sample rates the audio streams will use, so the
picker can rule out devices that cannot be opened at them.
Drops any cached list: which devices are usable depends on the rate, so a
list built under the old rates would be stale."""
global _cache
_RATES["input"] = int(input_rate)
_RATES["output"] = int(output_rate)
with _cache_lock:
_cache = None
def _usable(idx: int, kind: str) -> bool:
"""Can this device actually be opened at the rate we need?
Deliberately opens a real stream rather than asking
`check_output_settings`, because that function lies: it passed for an MME
endpoint that then failed to open with "The specified format is not
supported or cannot be translated" [MME error 32]. Opening and immediately
closing costs milliseconds and is the only answer that holds."""
st = None
try:
import sounddevice as sd
rate = _RATES.get(kind, 16000)
if kind == "input":
st = sd.InputStream(samplerate=rate, channels=1, dtype="int16",
blocksize=1024, device=idx,
callback=lambda *_a: None)
else:
st = sd.RawOutputStream(samplerate=rate, channels=1, dtype="int16",
blocksize=1024, device=idx)
st.start()
return True
except Exception:
return False
finally:
if st is not None:
try:
st.stop(); st.close()
except Exception:
pass
# Aliases for "the default device" and internal routing endpoints. Matched
# case-insensitively as substrings against the device name.
_PSEUDO_DEVICES = (
"sound mapper", # Windows MME
"primary sound", # Windows DirectSound ("Primary Sound Capture Driver")
"sysdefault", # ALSA
"default", # ALSA / PulseAudio alias
"dmix", "dsnoop", # ALSA software mixing plugins
"surround", # ALSA channel-layout permutations of one card
"samplerate", "speexrate", "upmix", "vdownmix", "null",
)
def _is_pseudo(name: str) -> bool:
low = name.lower()
return any(tok in low for tok in _PSEUDO_DEVICES)
def _query() -> dict[str, list[str]]:
"""Return {'input': [names...], 'output': [names...]}. Never raises.
Only real, selectable devices — see the note above."""
out: dict[str, list[str]] = {"input": [], "output": []}
try:
import platform
import sounddevice as sd
devices = list(sd.query_devices())
try:
apis = [a.get("name", "") for a in sd.query_hostapis()]
except Exception:
apis = []
preferred = _PREFERRED_APIS.get(platform.system(), ())
def _collect(api_filter, kind) -> list[tuple[int, str]]:
"""(index, name) for named, non-pseudo devices on one side that can
be opened at the rate that side runs at."""
chan = "max_input_channels" if kind == "input" else "max_output_channels"
found, seen = [], set()
for idx, dev in enumerate(devices):
name = (dev.get("name") or "").strip()
if not name or _is_pseudo(name) or name in seen:
continue
if dev.get(chan, 0) <= 0:
continue
if api_filter is not None:
api = apis[dev["hostapi"]].lower() if dev.get("hostapi", -1) < len(apis) else ""
if api_filter not in api:
continue
if not _usable(idx, kind):
continue
seen.add(name)
found.append((idx, name))
return found
# Each direction picks its own host API. They are genuinely different
# problems — on Windows the microphone works on DirectSound while the
# speakers only work on MME — and a single global choice cannot be right
# for both.
for kind in ("input", "output"):
for api_filter in list(preferred) + [None]:
found = _collect(api_filter, kind)
if not found:
continue
# One probe per API per direction, cached, on this thread.
if not _transport_works(found[0][0], kind, (api_filter, kind)):
continue
_chosen_api[kind] = api_filter
out[kind] = [_display_name(n, devices) for _i, n in found]
break
if out[kind]:
print(f"[Audio] {kind}: using "
f"{_chosen_api[kind] or 'any host API'} "
f"({len(out[kind])} devices)")
return out
except Exception as e:
print(f"[Audio] Device enumeration failed: {e}")
return out
def prefetch() -> None:
"""Warm the cache on a background thread. Called once at startup so the
settings drawer never pays for enumeration on the Qt thread."""
def _work():
global _cache
result = _query()
with _cache_lock:
_cache = result
print(f"[Audio] {len(result['input'])} input / "
f"{len(result['output'])} output devices found")
threading.Thread(target=_work, daemon=True, name="audio-devices").start()
def list_devices(kind: str, refresh: bool = False) -> list[str]:
"""Device names for 'input' or 'output'. Falls back to a synchronous query
if the prefetch has not landed yet — correctness over the cache."""
global _cache
with _cache_lock:
cached = None if refresh else _cache
if cached is None:
cached = _query()
with _cache_lock:
_cache = cached
return list(cached.get(kind, []))
def resolve(name: str, kind: str):
"""Turn a saved device name into something sounddevice accepts.
Returns None for "system default" — which is also what we return when the
saved device is gone, because a missing headset must degrade to the built-in
speakers, not to a crash on startup.
Candidates are walked in the same host-API order the picker used, so a name
the user chose from the WASAPI list resolves to the WASAPI endpoint. Without
that ordering a full name would fall through to MME's truncated copy of the
same device — which happens to work, but means the setting quietly refers to
a different endpoint than the one on screen."""
wanted = (name or "").strip()
if not wanted or wanted == DEFAULT_LABEL:
return None
try:
import platform
import sounddevice as sd
devices = list(sd.query_devices())
try:
apis = [a.get("name", "") for a in sd.query_hostapis()]
except Exception:
apis = []
want_in = (kind == "input")
chan_key = "max_input_channels" if want_in else "max_output_channels"
def _candidates(api_filter):
for idx, dev in enumerate(devices):
if dev.get(chan_key, 0) <= 0:
continue
if api_filter is not None:
api = apis[dev["hostapi"]].lower() if dev.get("hostapi", -1) < len(apis) else ""
if api_filter not in api:
continue
yield idx, (dev.get("name") or "").strip()
# The API the picker settled on for this direction comes first — the
# endpoint that was listed must be the endpoint that gets opened, or the
# setting means something different from what it says. list_devices()
# populates it; calling it here is a no-op once the cache is warm.
list_devices(kind)
chosen = _chosen_api.get(kind)
orders = ([chosen] if chosen is not None else []) \
+ [a for a in _PREFERRED_APIS.get(platform.system(), ()) if a != chosen] \
+ [None]
# A candidate only counts if it can be opened at the rate this side runs
# at. The prefix match matters because the API that carries the audio is
# not always the one that can spell: MME truncates names to 31 characters
# while DirectSound and WASAPI do not, so the name shown in the picker
# can be longer than the name of the endpoint it actually opens.
for api_filter in orders:
partial = None
for idx, dev_name in _candidates(api_filter):
if dev_name == wanted:
if _usable(idx, kind):
return idx
continue
if partial is None and (dev_name.startswith(wanted[:24])
or wanted.startswith(dev_name[:24])):
if _usable(idx, kind):
partial = idx
if partial is not None:
return partial
print(f"[Audio] Saved {kind} device '{wanted}' cannot be opened at "
f"{_RATES.get(kind)} Hz on any host API — using system default")
return None
except Exception as e:
print(f"[Audio] resolve({kind}) failed: {e} — using system default")
return None
+161
View File
@@ -0,0 +1,161 @@
"""
core/confirm.py — a confirmation the model cannot forge.
THE PROBLEM WITH THE OLD GATE
computer_settings guarded shutdown and restart like this:
confirmed = str(params.get("confirmed", "")).lower()
if confirmed not in ("yes", "true", "1", "confirm"):
return "Please confirm by calling again with confirmed=yes."
`confirmed` is a tool parameter, which means the *model* writes it. Nothing
stops it from sending confirmed=yes on the first call, and nothing checks
that a human was ever involved. It is a convention, not a gate — and its
coverage was two actions, so deleting files and switching off the WiFi the
assistant is talking over went through with no gate at all.
THE DESIGN HERE
The confirmation token is issued by the *interface*, never by the model:
1. An action calls `request(...)` with a callable that does the real work.
2. This module hands the UI a banner with CONFIRM / CANCEL and returns
IMMEDIATELY with a sentence for the model to say out loud.
3. If — and only if — the user presses CONFIRM, the UI calls `resolve()`,
which runs the stored callable off the Qt thread.
Nothing blocks. The model keeps talking while the banner is up, so this
costs no latency at all; in fact it is cheaper than the old gate, which
burned two tool round trips (reject, then re-call) on every shutdown.
WHAT BELONGS HERE AND WHAT DOES NOT
Only genuinely irreversible things. Anything that can be reversed should be
done at once and pushed onto core/undo.py instead — undo is faster than a
question, and an assistant that asks before every action is one nobody uses.
"""
from __future__ import annotations
import threading
import time
from dataclasses import dataclass
from typing import Callable, Optional
# A pending confirmation is abandoned after this long. Chosen to outlast a
# normal "hang on, let me look at the screen" pause without leaving a live
# shutdown button sitting on the HUD for the rest of the day.
TIMEOUT_SECONDS = 90.0
@dataclass
class _Pending:
key: str
title: str
detail: str
run: Callable[[], str]
at: float
_pending: Optional[_Pending] = None
_lock = threading.Lock()
# Set once at startup by main.py. Signature: (title, detail) -> None for show,
# and () -> None for hide. Both are marshalled onto the Qt thread by the UI.
_show_cb: Optional[Callable[[str, str], None]] = None
_hide_cb: Optional[Callable[[], None]] = None
_log_cb: Optional[Callable[[str], None]] = None
def bind(show, hide, log=None) -> None:
"""Wire this module to the HUD. Called once from main.py at startup."""
global _show_cb, _hide_cb, _log_cb
_show_cb, _hide_cb, _log_cb = show, hide, log
def _log(msg: str) -> None:
if _log_cb:
try:
_log_cb(msg)
except Exception:
pass
def request(key: str, title: str, detail: str, run: Callable[[], str]) -> str:
"""Park an irreversible action behind the on-screen gate.
Returns the sentence the tool should hand back to the model — phrased as an
instruction so the assistant asks the user out loud in their own language,
rather than reading an English string verbatim."""
global _pending
if _show_cb is None:
# No interface bound (headless, or a very early call). Refuse rather
# than silently performing something irreversible.
return (f"I cannot confirm '{title}' right now because the interface is "
f"not available, so I have not done it.")
with _lock:
_pending = _Pending(key=key, title=title, detail=detail,
run=run, at=time.monotonic())
try:
_show_cb(title, detail)
except Exception as e:
with _lock:
_pending = None
return f"Could not ask for confirmation: {e}. Nothing was done."
_log(f"SYS: Awaiting confirmation — {title}")
return (
f"[CONFIRMATION_PENDING] I have put a confirmation on screen for: {title}. "
f"Say ONE short sentence in the user's own language telling them you need "
f"them to confirm it on the HUD before you do it. Do not claim it is done."
)
def resolve(accepted: bool) -> None:
"""Called by the UI when the user presses CONFIRM or CANCEL.
Runs the stored callable on a worker thread — this is invoked from the Qt
thread, and shutting the machine down from inside a button handler would
freeze the interface on its way out."""
global _pending
with _lock:
p, _pending = _pending, None
if _hide_cb:
try:
_hide_cb()
except Exception:
pass
if p is None:
return
if time.monotonic() - p.at > TIMEOUT_SECONDS:
_log(f"SYS: Confirmation expired — {p.title}")
return
if not accepted:
_log(f"SYS: Cancelled — {p.title}")
return
def _worker():
try:
result = p.run() or "Done."
_log(f"SYS: Confirmed — {p.title}. {result}")
except Exception as e:
_log(f"ERR: {p.title} failed — {e}")
threading.Thread(target=_worker, daemon=True,
name=f"confirm-{p.key}").start()
def pending_title() -> str:
"""'' when nothing is waiting. Lets an action avoid stacking two banners."""
with _lock:
if _pending is None:
return ""
if time.monotonic() - _pending.at > TIMEOUT_SECONDS:
return ""
return _pending.title
+18 -5
View File
@@ -6,21 +6,32 @@ EXECUTION RULES:
Vision (screen_process): Call the tool ONCE per user request. Never call it again due to echo, ambient sound, or uncertainty. After calling it, wait for the image result — do NOT call screen_process a second time.
One-Call Policy: Never guess. Call tools exactly once. No retries.
Memory: Store critical user preferences/context automatically.
Recall: Your memory block holds what fits. Anything listed under [ALSO REMEMBERED] is stored but NOT shown — if the user asks about one of those names, or about anything personal you cannot see, call recall_memory BEFORE saying you don't know. It is a local file search: instant, free, no round trip to anyone.
Undo: You can take back your own changes — files you moved, renamed, created or wrote, and settings you adjusted. If the user says undo / revert / put it back / cancel that / "no, not that one", call the undo tool. Do not apologise and leave it broken; reverse it.
Confirmation: restart, shutdown and toggle_wifi put a button on the user's screen and DO NOT happen until they press it. When such a tool returns [CONFIRMATION_PENDING], say one short sentence asking them to confirm on the HUD. Never say it is done — it is not.
Exit: Only call shutdown_jarvis if session termination is explicit.
Response time: Respond as fast as you can.
ADDRESS: When speaking Turkish → always say "efendim". When speaking English → say "sir". Never mix languages.
Act: Always act like Jarvis from Iron Man — professional, efficient, slightly witty. ("Welcome home, efendim" etc.)
Act: Always act like Jarvis from Iron Man — professional, efficient, slightly witty. (greet the user warmly in their own language)
Length: Match response length to the task. Briefing = short. Complex analysis = thorough.
LANGUAGE:
The language of your reply is the language of the user's MOST RECENT message. Nothing else decides it — not what is stored in memory, not the language of these instructions, not the language of a tool's result.
Memory may say which language this person has used before. That is a record of the past, not an instruction for now: if they write or speak in another language today, answer in that one.
Tool results, log lines and this prompt are in English because that is what code is written in. None of them is a reason to switch language.
Never answer in a language the user has not used in this conversation.
Address the user with the ordinary respectful form of the language you are speaking in that sentence — never the form from a different language.
Do not mix two languages in one reply.
TOOL ROUTING:
computer_settings: ALL single OS actions (volume, brightness, wifi, close, shortcuts, power).
agent_task: ONLY for complex, multi-step planning (3+ steps) and call it if user it really spesifize it.
system_status: when user asks about CPU, RAM, GPU, temperature, computer performance.
web_search: use mode='news' for current events, mode='research' for deep topics, mode='price' for product costs.
Language: Respond in user's language; extract parameters in English.
Tool parameters are always extracted in English; see the LANGUAGE section above for what you SPEAK.
Do not call agent_task while you can accomplish it with a tool
wants to open a video = youtube. Always know the context for better User Experience
If user wants to do a taks more than 1, attain them and do them one by one(f.e: User: "open a relax rainy video and make it full screen" that means that you should open a video first, and then always wait 3-4 seconds to load the video and then press 'F' button to make it full screen) always know the context and attain them(Video opened in youtube, full screen means 'F' button).
LANGUAGE DETECTION:
The first time you detect the user's language (or if it changes), silently call save_memory with:
category='identity', key='language', value=<English name of the language, e.g. 'Turkish', 'French', 'Spanish'>
@@ -42,4 +53,6 @@ Say something genuinely useful, timely, or caring in 1-3 short sentences.
Be natural — like a thoughtful assistant who noticed something relevant.
Never read the [PROACTIVE_CHECK] tag aloud. Do NOT call any tools during a proactive check.
CRITICAL: Speak/Take action immediately based on available info. Assume and proceed.
CRITICAL: Speak/Take action immediately based on available info. Assume and proceed.
Always react fast, speed is your number 1 priority, don't make it complicated and slow.
+121
View File
@@ -0,0 +1,121 @@
"""
core/undo.py — one shared undo stack for every action that changes state.
WHY THIS EXISTS
A voice assistant misunderstands. When it does, "sorry" is not a remedy —
the file is already in another folder and the brightness is already at 10%.
Before this module the only recovery was to fix it by hand.
The alternative — asking "are you sure?" before everything — is worse. Every
confirmation is a round trip to the model and back, and an assistant that
checks with you before turning the volume down is one you stop talking to.
So: act immediately, remember how to reverse it, and let the user say
"undo". Confirmation is then reserved for the handful of actions that
genuinely cannot be reversed (see core/confirm.py).
HOW AN ACTION OPTS IN
Actions do not have to know anything about this file's internals. They
capture the "before" state and hand back a zero-argument callable:
from core.undo import push_undo
old = volume_get()
volume_set(new)
push_undo(f"volume → {new}%", lambda: volume_set(old))
Only the action itself can know that the reverse of "move A to B" is "move
B to A", which is why this cannot be fully centralised. What IS central is
the stack, the ordering, the thread safety and the tool the model calls.
COST
Pushing is a list append behind a lock: microseconds. Nothing in here runs
until the user actually asks to undo something. This module cannot make the
assistant slower.
"""
from __future__ import annotations
import threading
import time
from dataclasses import dataclass, field
from typing import Callable
# How many reversible operations we keep. Ten is roughly "this conversation":
# far enough back to catch a mistake you noticed a few commands later, short
# enough that a closure holding a file's old contents cannot pile up in RAM.
MAX_DEPTH = 10
@dataclass
class _Entry:
label: str # human sentence, spoken back to the user
undo: Callable[[], str] # returns a short result string
at: float = field(default_factory=time.monotonic)
_stack: list[_Entry] = []
_lock = threading.Lock()
def push_undo(label: str, undo_fn: Callable[[], str]) -> None:
"""Record that `label` just happened and `undo_fn()` reverses it.
Called from action handlers, which run in executor threads — hence the
lock. Never raises: a broken undo registration must not take down the
action that actually succeeded."""
if not callable(undo_fn):
return
try:
with _lock:
_stack.append(_Entry(label=str(label)[:120], undo=undo_fn))
# Drop the oldest rather than refusing the newest: the recent past
# is what people ask to undo.
while len(_stack) > MAX_DEPTH:
_stack.pop(0)
except Exception as e: # pragma: no cover
print(f"[Undo] push failed: {e}")
def can_undo() -> bool:
with _lock:
return bool(_stack)
def peek() -> str:
"""Label of the operation that `undo_last()` would reverse, or ''."""
with _lock:
return _stack[-1].label if _stack else ""
def history() -> list[str]:
"""Most recent first — used by the UI panel and the `undo` tool's list mode."""
with _lock:
return [e.label for e in reversed(_stack)]
def undo_last() -> str:
"""Reverse the most recent reversible operation.
The entry is popped *before* running so a failing undo cannot be retried
forever against a world that has already moved on (the file the user is
trying to restore may have been deleted by something else since)."""
with _lock:
entry = _stack.pop() if _stack else None
if entry is None:
return ("There is nothing to undo. I only track things I changed myself — "
"files I moved or wrote, and settings I adjusted.")
try:
detail = entry.undo() or ""
except Exception as e:
return f"Could not undo '{entry.label}': {e}"
return f"Undone: {entry.label}." + (f" {detail}" if detail else "")
def clear() -> None:
"""Forget the stack. Called when the app shuts down so closures holding old
file contents do not outlive the session."""
with _lock:
_stack.clear()