Quick Fix: reopen after a restart only when its own rebuild caused it
The chat reopened on every shell start while a stale "unseen" result was left over. Now the helper checks the job's unit for a running rebuild (zcli, nixos-rebuild, nh, home-manager) and only then reopens; other restarts keep following a running job quietly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f35dbee430
commit
94530d3bd3
4 files changed
+83
-10
No files matched your search
@@ -15,9 +15,11 @@ session and weekly windows counts), then a local model if one is running.
|
||||
|
||||
- Each request runs in its own systemd user unit
|
||||
(`glassmxrph-quickfix-<id>`), so a rebuild that restarts the shell does not
|
||||
stop it. When the shell starts and a job is running, or its result has not
|
||||
been seen, the chat opens again by itself (without taking the keyboard
|
||||
until you point at it) and shows how it went.
|
||||
stop it. When the job's own rebuild (`zcli`, `nixos-rebuild`, `nh`,
|
||||
`home-manager`) restarts the shell, the chat opens again by itself (without
|
||||
taking the keyboard until you point at it) and shows how it went. Other
|
||||
restarts leave it closed; a job still running is followed and announced
|
||||
when it finishes.
|
||||
- Closing the chat and opening it again starts fresh. Earlier conversations
|
||||
are under History; opening one continues it. A follow-up resumes the same
|
||||
agent session.
|
||||
|
||||
@@ -5,8 +5,8 @@ import Quickshell.Io
|
||||
// Shared state for every Quick Fix widget (one per bar): the conversation on
|
||||
// screen, whether a job runs, history. Jobs run in their own systemd user
|
||||
// units (helpers/quickfix.py), so a rebuild that restarts the shell does not
|
||||
// stop them; on start this reopens the chat when a job is running or its
|
||||
// result has not been seen yet.
|
||||
// stop them; on start this reopens the chat only when the running job is the
|
||||
// one whose rebuild restarted the shell, and otherwise keeps following it.
|
||||
Item {
|
||||
id: root
|
||||
|
||||
@@ -192,7 +192,7 @@ Item {
|
||||
onTriggered: root.refresh()
|
||||
}
|
||||
|
||||
// After a restart: reopen on a running job or an unseen result.
|
||||
// After a restart: reopen when the running job's own rebuild restarted the shell.
|
||||
property int summonTries: 0
|
||||
Timer {
|
||||
id: summonRetry
|
||||
@@ -205,9 +205,11 @@ Item {
|
||||
}
|
||||
}
|
||||
Component.onCompleted: call({ op: "state" }, result => {
|
||||
if (!result.ok || !result.session || !(result.running || !result.seen)) return
|
||||
if (!result.ok || !result.session || !result.running) return
|
||||
// Follow a running job either way, so its result is announced.
|
||||
root.session = result.session
|
||||
root.running = result.running
|
||||
root.running = true
|
||||
if (!result.rebuilt) return
|
||||
root.passive = true
|
||||
root.summonTries = 0
|
||||
summonRetry.start()
|
||||
|
||||
@@ -133,6 +133,36 @@ def unit_active(id_):
|
||||
return r.stdout.strip() not in ('inactive', 'failed')
|
||||
|
||||
|
||||
REBUILDERS = {'zcli', 'nixos-rebuild', 'nixos-rebuild-ng', 'nh', 'home-manager', 'switch-to-configuration'}
|
||||
|
||||
|
||||
def rebuilding(id_):
|
||||
"""True when the job's unit is running a system rebuild, i.e. the rebuild
|
||||
that restarted the shell was started by this job."""
|
||||
try:
|
||||
group = subprocess.run(['systemctl', '--user', 'show', f'{UNIT}-{id_}.service', '-p', 'ControlGroup', '--value'],
|
||||
capture_output=True, text=True, timeout=10).stdout.strip()
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
root = Path('/sys/fs/cgroup') / group.lstrip('/')
|
||||
if not group or not root.is_dir():
|
||||
return False
|
||||
for procs in root.rglob('cgroup.procs'):
|
||||
try:
|
||||
pids = procs.read_text().split()
|
||||
except OSError:
|
||||
continue
|
||||
for pid in pids:
|
||||
try:
|
||||
argv = Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0')
|
||||
except OSError:
|
||||
continue
|
||||
# Scripts run as `bash /nix/store/...-zcli/bin/zcli rebuild`.
|
||||
if {os.path.basename(a.decode(errors='replace')) for a in argv[:3] if a} & REBUILDERS:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def alive(pid):
|
||||
if not isinstance(pid, int) or pid <= 0:
|
||||
return False
|
||||
@@ -625,7 +655,7 @@ def begin(session, request_messages, action):
|
||||
session['running'] = True
|
||||
session['updated'] = int(time.time())
|
||||
save_session(session)
|
||||
save_state(current=session['id'], running=True, seen=False, started=int(time.time()))
|
||||
save_state(current=session['id'], running=True, seen=False, rebuilt=False, started=int(time.time()))
|
||||
try:
|
||||
start_unit(session['id'], action)
|
||||
except (OSError, ValueError) as error:
|
||||
@@ -637,9 +667,16 @@ def handle(request):
|
||||
op = request.get('op')
|
||||
recover()
|
||||
if op == 'state':
|
||||
# Called when the shell starts. Remember if the running job is the one
|
||||
# rebuilding (and so restarting) the shell: only then does it reopen.
|
||||
with locked():
|
||||
state = read_state()
|
||||
if state.get('running') and state.get('current') and not state.get('rebuilt') and rebuilding(state['current']):
|
||||
save_state(rebuilt=True)
|
||||
state['rebuilt'] = True
|
||||
session = read_json(session_path(state['current'])) if state.get('current') else None
|
||||
return {'session': session, 'running': bool(state.get('running')), 'seen': bool(state.get('seen', True))}
|
||||
return {'session': session, 'running': bool(state.get('running')), 'seen': bool(state.get('seen', True)),
|
||||
'rebuilt': bool(state.get('rebuilt'))}
|
||||
if op == 'send':
|
||||
text = str(request.get('text') or '').strip()
|
||||
if not text or len(text) > 8000:
|
||||
|
||||
@@ -143,5 +143,37 @@ class QuickFix(unittest.TestCase):
|
||||
with patch.object(quickfix.subprocess, 'run', return_value=stopped):
|
||||
self.assertTrue(quickfix.handle({'op': 'state'})['running']) # worker process alive
|
||||
|
||||
def test_reopens_only_when_its_own_rebuild_restarted_the_shell(self):
|
||||
request = {'op': 'send', 'text': 'x', 'provider': 'claude', 'options': {}}
|
||||
with patch.object(quickfix, 'start_unit'), patch.object(quickfix, 'unit_active', return_value=True):
|
||||
quickfix.handle(request)
|
||||
with patch.object(quickfix, 'rebuilding', return_value=False):
|
||||
self.assertFalse(quickfix.handle({'op': 'state'})['rebuilt'])
|
||||
with patch.object(quickfix, 'rebuilding', return_value=True):
|
||||
self.assertTrue(quickfix.handle({'op': 'state'})['rebuilt'])
|
||||
# Remembered for the rest of the job, e.g. a second restart.
|
||||
with patch.object(quickfix, 'rebuilding', return_value=False):
|
||||
self.assertTrue(quickfix.handle({'op': 'state'})['rebuilt'])
|
||||
quickfix.save_state(running=False)
|
||||
with patch.object(quickfix, 'rebuilding', return_value=False):
|
||||
quickfix.handle(request)
|
||||
self.assertFalse(quickfix.handle({'op': 'state'})['rebuilt'])
|
||||
|
||||
def test_rebuilding_spots_a_rebuild_in_the_job_unit(self):
|
||||
base = Path(self.tmp.name) / 'cg'
|
||||
(base / 'job').mkdir(parents=True)
|
||||
(base / 'job/cgroup.procs').write_text(str(os.getpid()) + '\n')
|
||||
group = subprocess.CompletedProcess([], 0, '/job\n', '')
|
||||
real = Path
|
||||
def fake_path(*parts):
|
||||
path = real(*parts)
|
||||
return base if str(path) == '/sys/fs/cgroup' else path
|
||||
with patch.object(quickfix.subprocess, 'run', return_value=group), patch.object(quickfix, 'Path', side_effect=fake_path):
|
||||
self.assertFalse(quickfix.rebuilding('x'))
|
||||
argv = b'bash\0/nix/store/abc-zcli/bin/zcli\0rebuild\0'
|
||||
real_read = real.read_bytes
|
||||
with patch.object(real, 'read_bytes', lambda self: argv if self.name == 'cmdline' else real_read(self)):
|
||||
self.assertTrue(quickfix.rebuilding('x'))
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user