main
John Lauer
Preserve native engine selection and rename without a daemon
ccb2edb
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
import json
import os
from pathlib import Path
import sqlite3
import sys
import tempfile
import unittest
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'runtime'))
from thread_names import list_threads, rename_thread, native_names
import runtime
SID = '12345678-1234-1234-1234-123456789abc'
class ThreadNamesTest(unittest.TestCase):
def test_native_name_beats_preview_and_old_schema(self):
with tempfile.TemporaryDirectory() as directory:
for schema, name in [(9, 'stale'), (10, 'User name')]:
with sqlite3.connect(str(Path(directory) / f'state_{schema}.sqlite')) as db:
db.execute('create table threads(id,name,title,cwd,updated_at,archived)')
db.execute('insert into threads values(?,?,?,?,?,0)', (SID, name, 'A very long original prompt', '/project', 100))
self.assertEqual(list_threads(directory)[0]['title'], 'User name')
self.assertEqual(list_threads(directory)[0]['when'], 100000)
self.assertEqual(len(list(Path(directory).glob('state_*.sqlite'))), 2)
def test_legacy_database_and_archived_threads(self):
with tempfile.TemporaryDirectory() as directory:
with sqlite3.connect(str(Path(directory) / 'state_5.sqlite')) as db:
db.execute('create table threads(id,title,cwd,updated_at,archived)')
db.execute('insert into threads values(?,?,?,?,0)', (SID, 'Generated title', '/', 100))
db.execute('insert into threads values(?,?,?,?,1)', ('hidden', 'Archived', '/', 200))
self.assertEqual([r['title'] for r in list_threads(directory)], ['Generated title'])
def test_rename_verifies_native_readback_and_does_not_start_a_backend(self):
class Connection:
def __init__(self): self.reply = None; self.calls = []
def __enter__(self): return self
def __exit__(self, *args): pass
def send(self, data):
request = json.loads(data); self.calls.append(request)
if 'id' not in request: return
result = {'thread': {'id': SID, 'name': 'hello'}} if request['method'] == 'thread/read' else {}
self.reply = json.dumps({'id': request['id'], 'result': result})
def recv(self, **kwargs): return self.reply
with tempfile.TemporaryDirectory() as directory:
Path(directory, 'server.json').write_text(json.dumps({'pid': 1, 'socket': '/test/socket'}))
connection = Connection()
with patch.object(runtime, 'state_dir', return_value=Path(directory)), patch.object(runtime, 'process_matches', return_value=True), patch.object(runtime, 'unix_connect', return_value=connection):
result = rename_thread('hello', SID)
self.assertTrue(result['persisted'])
self.assertFalse(result['tab_verified'])
self.assertEqual(connection.calls[2]['method'], 'thread/name/set')
self.assertEqual(connection.calls[2]['params'], {'threadId': SID, 'name': 'hello'})
def test_no_guessing_or_invalid_names(self):
with patch.dict(os.environ, {'CODEX_THREAD_ID': ''}):
with self.assertRaises(ValueError): rename_thread('hello')
for name in ['', 'line\nbreak', 'x' * 201]:
with self.assertRaises(ValueError): rename_thread(name, SID)
def test_native_name_query_includes_only_requested_ids_and_never_raw_preview(self):
with tempfile.TemporaryDirectory() as directory:
with sqlite3.connect(str(Path(directory) / 'state_5.sqlite')) as db:
db.execute('create table threads(id,name,title)')
db.execute('insert into threads values(?,?,?)', (SID, 'Saved name', 'Long first prompt'))
db.execute('insert into threads values(?,?,?)', ('87654321-1234-1234-1234-123456789abc', None, 'Do not show this raw preview ' * 8))
self.assertEqual(native_names([SID, '87654321-1234-1234-1234-123456789abc', 'bad'], directory), {SID: 'Saved name'})
def test_current_engine_automatic_title_without_explicit_name(self):
with tempfile.TemporaryDirectory() as directory:
with sqlite3.connect(str(Path(directory) / 'state_5.sqlite')) as db:
db.execute('create table threads(id,name,title)')
db.execute('insert into threads values(?,?,?)', (SID, None, 'Explain voltage versus current'))
self.assertEqual(native_names([SID], directory), {SID: 'Explain voltage versus current'})
def test_native_engine_without_daemon_uses_and_reaps_metadata_process(self):
with tempfile.TemporaryDirectory() as directory:
directory = Path(directory)
program = directory / 'metadata-server'
program.write_text('''#!/usr/bin/env python3
import sys,json,os
from pathlib import Path
Path(__file__).with_suffix('.pid').write_text(str(os.getpid()))
name=None
for line in sys.stdin:
request=json.loads(line)
if 'id' not in request:continue
if request['method']=='thread/name/set':name=request['params']['name']
result={'thread':{'id':request.get('params',{}).get('threadId'),'name':name}} if request['method']=='thread/read' else {}
print(json.dumps({'id':request['id'],'result':result}),flush=True)
''')
program.chmod(0o755)
with patch.object(runtime, 'state_dir', return_value=directory), patch('thread_names.name_binary', return_value=program):
result = rename_thread('Native engine name', SID)
self.assertTrue(result['persisted'])
self.assertFalse((directory / 'server.json').exists())
with self.assertRaises(ProcessLookupError): os.kill(int(program.with_suffix('.pid').read_text()), 0)
if __name__ == '__main__': unittest.main()