The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui,gateway): /compress on a short session prints main's "No changes" report
Teknium952a3268c09e
diff --git a/gateway/session_mutation_compress.py b/gateway/session_mutation_compress.pyindex f7fc50711bf..227c664fb06 100644--- a/gateway/session_mutation_compress.py+++ b/gateway/session_mutation_compress.py@@ -74,12 +74,25 @@ async def prepare_compress(authority, live, payload, prepared):compressed = compressor.compress(json.loads(json.dumps(head)), force=True,focus_topic=request.focus_topic, memory_context=memory_context)if not any(m.get('_compressed_summary') for m in compressed):- raise RuntimeStoreError('nothing_to_compress')+ return None, compressorreturn rejoin_compressed_head_and_tail(compressed, tail), compressorcompressed, compressor = await asyncio.to_thread(summarize)# The same report every native /compress prints ("Compressed: N → M messages").from agent.manual_compression_feedback import summarize_manual_compression+ if compressed is None:+ # Nothing removable (a short session keeps every message): main's read-only+ # "No changes from compression" report, estimated like main's (system prompt + tools).+ tokens = _request_tokens(resident, messages)+ return {'status': 'noop', 'summary': summarize_manual_compression(+ messages, messages, tokens, tokens, compression_state=compressor)}summary = summarize_manual_compression(messages, compressed, estimate_request_tokens_rough(messages),estimate_request_tokens_rough(compressed), compression_state=compressor)return dict(prepared, messages=compressed, summary=summary,in_place=is_truthy_value(options.get('in_place'), default=True))+++def _request_tokens(agent, messages):+ """Main's /compress request estimate: the agent's system prompt and tool schemas plus the messages."""+ from agent.model_metadata import estimate_request_tokens_rough+ return estimate_request_tokens_rough(messages, system_prompt=getattr(agent, '_cached_system_prompt', '') or '',+ tools=getattr(agent, 'tools', None) or None)diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex e9eb086994a..6f944a8a1f3 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -155,9 +155,10 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):prepare = {'model': prepare_model, 'compress': prepare_compress, **PREPARE}[operation]prepared = await prepare(authority, live, params['payload'], prepared)applied = False- if prepared.get('status') in {'preview', 'confirmation_required'}:- # ``--preview`` is a read-only report and a guarded model target awaits the user's- # confirmation: no receipt, no publication, no eviction.+ if prepared.get('status') in {'preview', 'noop', 'confirmation_required'}:+ # ``--preview`` and a compress that removes nothing are read-only reports, and a+ # guarded model target awaits the user's confirmation: no receipt, no publication,+ # no eviction.return {'session_id': ref.session_id, 'operation': operation, **prepared}async with commit_lock or nullcontext():if prepared is not None and 'snapshot' not in prepared:diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 1f216a9b7d9..1cc01cc7b46 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -277,6 +277,12 @@ class GatewayChatView:self.mutations.acknowledge(original, operation, payload)print('\n'.join(result['lines']))return True+ if result.get('status') == 'noop':+ # Nothing removable: main's report, nothing committed (gateway/session_mutation_compress.py).+ self.mutations.acknowledge(original, operation, payload)+ summary = result.get('summary') or {}+ print('\n'.join(filter(None, (summary.get('headline'), summary.get('token_line'), summary.get('note')))))+ return Truetarget = result.get('branched_session_id', original)await self.adopt(await self.client.rpc('session.resume', session_id=target))self.mutations.acknowledge(original, operation, payload)diff --git a/tests/gateway/test_session_mutation_compress_preview.py b/tests/gateway/test_session_mutation_compress_preview.pyindex cef45d522b9..059a01a45cb 100644--- a/tests/gateway/test_session_mutation_compress_preview.py+++ b/tests/gateway/test_session_mutation_compress_preview.py@@ -180,3 +180,44 @@ async def test_input_is_admitted_while_compress_summarizes_but_not_claimed_untilfinally:release.set()await owner.close()+++async def test_a_compress_that_removes_nothing_reports_mains_no_changes_without_writing(tmp_path, monkeypatch):+ """A short session's ``/compress`` (the summarizer protects every message) is main's+ ``No changes from compression: N messages`` report, read-only like a preview: no receipt, no+ revision bump, no ``nothing_to_compress`` error on the wire (FINDINGS row 25)."""+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from agent.context_compressor import ContextCompressor++ monkeypatch.setattr(run, '_load_gateway_config', dict)+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ db = store._db+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ monkeypatch.setattr(ContextCompressor, '__init__', lambda self, *a, **k: None)+ monkeypatch.setattr(ContextCompressor, 'compress', lambda self, messages, **kw: messages)+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None,+ _resolve_session_agent_runtime=lambda **k: ('frozen', {}))+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db, epoch=epoch)+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})+ ref = create_local_session(authority, owner.actor, dict(request_id='short', source='tui', cwd=str(tmp_path),+ model='frozen', toolsets=[]))+ db.append_message(ref.session_id, 'user', 'hi')+ db.append_message(ref.session_id, 'assistant', 'hello')+ before = db.get_session(ref.session_id)+ try:+ reply = await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {+ 'session_id': ref.session_id, 'request_id': 'noop', 'expected_revision': before['runtime_revision'],+ 'expected_generation': before['runtime_generation'], 'operation': 'compress', 'payload': {}}})+ result = reply.get('result') or {}+ assert result.get('status') == 'noop', reply+ assert result['summary']['headline'] == 'No changes from compression: 2 messages', result+ assert result['summary']['noop'] is True and result['summary']['token_line'].endswith('(unchanged)')+ after = db.get_session(ref.session_id)+ assert (after['runtime_revision'], after['runtime_generation']) == (before['runtime_revision'], before['runtime_generation'])+ assert not db.list_meta_prefix('gateway.mutation.v1.'), 'a no-op left a mutation receipt'+ finally:+ await owner.close()diff --git a/ui-tui/src/__tests__/canonicalSessionControls.test.ts b/ui-tui/src/__tests__/canonicalSessionControls.test.tsindex 9df991899ef..d06dcf70c68 100644--- a/ui-tui/src/__tests__/canonicalSessionControls.test.ts+++ b/ui-tui/src/__tests__/canonicalSessionControls.test.ts@@ -179,3 +179,26 @@ it('a guarded canonical model switch asks; yes re-sends once with the owner tokeexpect(getUiState().info?.model).toBe(accept ? 'pricey' : 'old')}})++it('a /compress that removes nothing prints main\'s "No changes" report without re-hydrating', async () => {+ const { ctx, request, slash } = harness()+ request.mockImplementation(async (method: string) => {+ if (method === 'session.resume') {+ return { session_id: 'owner', revision: 8, execution_generation: 4, info, messages: [] } as any+ }++ return {+ session_id: 'owner', operation: 'compress', status: 'noop',+ summary: { headline: 'No changes from compression: 2 messages', noop: true,+ token_line: 'Approx request size: ~6,547 tokens (unchanged)' }+ } as any+ })++ slash('/compress')+ await flush()+ await flush()+ expect(ctx.transcript.sys).toHaveBeenCalledWith('No changes from compression: 2 messages')+ expect(ctx.transcript.sys).toHaveBeenCalledWith(' Approx request size: ~6,547 tokens (unchanged)')+ expect(ctx.transcript.setHistoryItems).not.toHaveBeenCalled()+ expect(request.mock.calls.filter(([method]) => method === 'session.resume')).toHaveLength(1)+})diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.tsindex 7673569fc5e..bb76011653a 100644--- a/ui-tui/src/app/slash/canonicalSessionControls.ts+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts@@ -236,6 +236,19 @@ function applyModelResult(result: CanonicalControlResult, ctx: SlashRunCtx) {ctx.transcript.sys(t('session.main.modelSwitched', result.model))}+type CompressSummary = { headline?: string; noop?: boolean; note?: string; token_line?: string } | null++/** The authority's report (headline, token line, note), as the native /compress prints it. */+function printCompressSummary(summary: CompressSummary, ctx: SlashRunCtx) {+ ctx.transcript.sys(summary?.headline ? `${summary.noop ? '' : '✓ '}${summary.headline}` : t('canonical.controls.compressed'))++ for (const line of [summary?.token_line, summary?.note]) {+ if (line) {+ ctx.transcript.sys(` ${line}`)+ }+ }+}+async function applyCompressResult(gw: MutationGateway, sid: string, result: CanonicalControlResult, ctx: SlashRunCtx) {const before = getUiState()const snapshot = asRpcResult(await gw.request('session.resume', { session_id: sid }))@@ -259,16 +272,7 @@ async function applyCompressResult(gw: MutationGateway, sid: string, result: Canctx.transcript.setHistoryItems([introMsg(info), ...toTranscriptMessages(snapshot.messages)])patchUiState({ info })- // The authority's report (headline, token line, note), as the native /compress prints it.- const summary = result.summary as { headline?: string; noop?: boolean; note?: string; token_line?: string } | null-- ctx.transcript.sys(summary?.headline ? `${summary.noop ? '' : '✓ '}${summary.headline}` : t('canonical.controls.compressed'))-- for (const line of [summary?.token_line, summary?.note]) {- if (line) {- ctx.transcript.sys(` ${line}`)- }- }+ printCompressSummary(result.summary as CompressSummary, ctx)}export async function runCanonicalSessionControl(@@ -309,6 +313,9 @@ export async function runCanonicalSessionControl(} else if (result.status === 'preview') {// `--preview` is a read-only report; nothing to re-hydrate.ctx.transcript.sys((result.lines as string[]).join('\n'))+ } else if (result.status === 'noop') {+ // Nothing removable: main's "No changes from compression" report; the transcript is untouched.+ printCompressSummary(result.summary as CompressSummary, ctx)} else {await applyCompressResult(gw, ctx.sid, result, ctx)}