Each request runs in its own systemd user unit and survives the shell restarting; the chat reopens on a running job or an unseen result. Auto picks the subscription with the most usage left (ai-usagebar). Runs are snapshotted so Undo can restore files and revert commits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
134 lines
6.7 KiB
Python
134 lines
6.7 KiB
Python
#!/usr/bin/env python3
|
|
import json,os,subprocess,sys,tempfile,unittest
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0,str(ROOT/'helpers'))
|
|
import quickfix
|
|
|
|
class QuickFix(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
base = Path(self.tmp.name)
|
|
self.repo = base / 'repo'
|
|
self.repo.mkdir()
|
|
self.patches = [patch.object(quickfix, 'STATE', base / 's'), patch.object(quickfix, 'SESSIONS', base / 's/sessions'),
|
|
patch.object(quickfix, 'SNAPSHOTS', base / 's/snapshots'), patch.object(quickfix, 'RULES', base / 'r/AGENTS.md')]
|
|
for p in self.patches:
|
|
p.start()
|
|
env = {'GIT_AUTHOR_NAME': 't', 'GIT_AUTHOR_EMAIL': 't@t', 'GIT_COMMITTER_NAME': 't', 'GIT_COMMITTER_EMAIL': 't@t'}
|
|
self.env = patch.dict(os.environ, env)
|
|
self.env.start()
|
|
self.git('init', '-q')
|
|
(self.repo / 'clean').write_text('clean')
|
|
(self.repo / 'dirty').write_text('old')
|
|
self.git('add', '.')
|
|
self.git('-c', 'commit.gpgsign=false', 'commit', '-qm', 'one')
|
|
(self.repo / 'dirty').write_text('mine')
|
|
(self.repo / 'untracked').write_text('also mine')
|
|
self.options = {'repositories': [str(self.repo)]}
|
|
|
|
def tearDown(self):
|
|
for p in self.patches:
|
|
p.stop()
|
|
self.env.stop()
|
|
self.tmp.cleanup()
|
|
|
|
def git(self, *a):
|
|
subprocess.run(['git', '-C', str(self.repo), *a], check=True, capture_output=True)
|
|
|
|
def text(self, name):
|
|
return (self.repo / name).read_text()
|
|
|
|
def test_undo_restores_uncommitted_work(self):
|
|
record = quickfix.snapshot('run', self.options)
|
|
for name in ('clean', 'dirty'):
|
|
(self.repo / name).write_text('agent')
|
|
(self.repo / 'untracked').unlink()
|
|
(self.repo / 'new').write_text('agent')
|
|
self.git('add', '-N', 'new')
|
|
self.assertTrue(quickfix.finish_snapshot('run', record))
|
|
self.assertEqual(quickfix.undo('run', self.options), [])
|
|
self.assertEqual([self.text(n) for n in ('clean', 'dirty', 'untracked')], ['clean', 'mine', 'also mine'])
|
|
self.assertFalse((self.repo / 'new').exists())
|
|
|
|
def test_undo_refuses_files_edited_since(self):
|
|
record = quickfix.snapshot('run', self.options)
|
|
(self.repo / 'clean').write_text('agent')
|
|
(self.repo / 'dirty').write_text('agent')
|
|
quickfix.finish_snapshot('run', record)
|
|
(self.repo / 'dirty').write_text('mine again')
|
|
with self.assertRaisesRegex(ValueError, 'dirty'):
|
|
quickfix.undo('run', self.options)
|
|
self.assertEqual((self.text('clean'), self.text('dirty')), ('agent', 'mine again'))
|
|
|
|
def test_undo_reverts_commits(self):
|
|
(self.repo / 'untracked').unlink()
|
|
self.git('checkout', '-q', '--', 'dirty')
|
|
remote = Path(self.tmp.name) / 'remote'
|
|
subprocess.run(['git', 'init', '-q', '--bare', str(remote)], check=True)
|
|
self.git('remote', 'add', 'origin', str(remote))
|
|
self.git('push', '-qu', 'origin', 'HEAD')
|
|
self.git('config', 'commit.gpgsign', 'false')
|
|
record = quickfix.snapshot('run', self.options)
|
|
(self.repo / 'clean').write_text('agent')
|
|
self.git('commit', '-qam', 'fix')
|
|
self.assertTrue(quickfix.finish_snapshot('run', record))
|
|
self.assertEqual(quickfix.undo('run', self.options), [])
|
|
self.assertEqual(self.text('clean'), 'clean')
|
|
|
|
def test_unchanged_run_has_nothing_to_undo(self):
|
|
self.assertFalse(quickfix.finish_snapshot('run', quickfix.snapshot('run', self.options)))
|
|
|
|
def test_auto_takes_the_most_usage_left(self):
|
|
have = {'claude': True, 'gpt': True, 'local': True}
|
|
with patch.object(quickfix, 'installed', return_value=have), patch.object(quickfix, 'local_models', return_value=['m']):
|
|
for left, expected in (({'claude': 30, 'gpt': 100}, 'gpt'), ({'claude': 30, 'gpt': 0}, 'claude'),
|
|
({'claude': 0, 'gpt': 0}, 'local'), ({'gpt': 5}, 'gpt')):
|
|
with patch.object(quickfix, 'remaining', return_value=left):
|
|
self.assertEqual(quickfix.choose('auto', {})[0], expected)
|
|
|
|
def test_usage_is_limited_by_the_tightest_window(self):
|
|
report = {'entries': [{'id': 'anthropic', 'status': 'ready', 'metrics': [{'percent': 3}, {'percent': 70}]},
|
|
{'id': 'openai', 'status': 'error', 'metrics': []}]}
|
|
done = subprocess.CompletedProcess([], 0, json.dumps(report), '')
|
|
with patch.object(quickfix.shutil, 'which', return_value='x'), patch.object(quickfix.subprocess, 'run', return_value=done):
|
|
self.assertEqual(quickfix.remaining(), {'claude': 30})
|
|
|
|
def test_replies(self):
|
|
self.assertEqual(quickfix.tidy('OK: Installed X.'), (True, 'Installed X.'))
|
|
self.assertEqual(quickfix.tidy('**FAILED:** no'), (False, 'no'))
|
|
self.assertEqual(quickfix.tidy('Six containers.'), (None, 'Six containers.'))
|
|
out = '{"type":"thread.started","thread_id":"t"}\n{"type":"turn.completed"}'
|
|
last = Path(self.tmp.name) / 'last'
|
|
last.write_text('OK: hi')
|
|
self.assertEqual(quickfix.parse_output('gpt', out, last), ('OK: hi', 't', False))
|
|
self.assertEqual(quickfix.parse_output('claude', '{"type":"result","result":"x","session_id":"s","is_error":false}', last), ('x', 's', False))
|
|
|
|
def test_requests_are_validated(self):
|
|
for bad in ('../x', '', None, '20260101-000000-zzzz'):
|
|
with self.assertRaises(ValueError):
|
|
quickfix.session_path(bad)
|
|
with self.assertRaises(ValueError):
|
|
quickfix.clean_options({'gptModel': '--danger'})
|
|
with patch.object(quickfix, 'start_unit') as start:
|
|
for request in ({'op': 'send', 'text': ' ', 'provider': 'auto'}, {'op': 'send', 'text': 'x', 'provider': 'sh'}):
|
|
with self.assertRaises(ValueError):
|
|
quickfix.handle(request)
|
|
start.assert_not_called()
|
|
|
|
def test_one_run_at_a_time_and_dead_runs_recover(self):
|
|
request = {'op': 'send', 'text': 'x', 'provider': 'claude', 'options': {}}
|
|
with patch.object(quickfix, 'start_unit'), patch.object(quickfix, 'unit_active', return_value=False):
|
|
quickfix.handle(request)
|
|
with self.assertRaisesRegex(ValueError, 'already running'):
|
|
quickfix.handle(request)
|
|
quickfix.save_state(started=0)
|
|
state = quickfix.handle({'op': 'state'})
|
|
self.assertFalse(state['running'])
|
|
self.assertFalse(state['seen'])
|
|
self.assertEqual(state['session']['messages'][-1]['status'], 'failed')
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|