Repository navigation
Done
Description
Before submitting
- I searched existing issues and did not find a duplicate (related to [Bug]: Antigravity thread permanently fails with Internal error after localharness disconnect drops in-memory session #30594, PR fix(server): Antigravity resumes after its local harness fails #23654, and PR fix(antigravity): resume threads after internal prompt errors #30707, which cover the follow-up
-32603/ stderr symptoms, but not the root.agents/hooks.jsontrigger or the silentend_turn+ synthetic assistant message corruption). - I included enough detail to reproduce or investigate the problem.
Area
apps/server
Summary
When an Antigravity (gemini-4-argon / agy_acp_server.par) session runs in a workspace containing .agents/hooks.json (or .gemini/hooks.json) and a background command (run_command that went async after WaitMsBeforeAsync) is cancelled via manage_task(Action="kill") while the next model invocation is starting, a 4-stage compounding bug across localharness_external, agy_acp_server.par, and T3 Code's AntigravityAdapterV2 / AcpAdapterV2 causes:
- Silent turn truncation (Turn N):
localharness_externalexits its execution loop and closes the local WebSocket with code1000 (OK).agy_acp_server.partreats1000 (OK)as a normal stream EOF (CLOSE_SENTINEL) and returnsPromptResponse(stop_reason="end_turn")without emitting any error, so T3 Code marks Turn N ascompletedwith no final assistant response. - Broken session rebuild (Turn N+1): On the next
session/prompt,agy_acp_server.parcatcheswebsockets.exceptions.ConnectionClosedOKand callsself._rebuild_session_agent(session_id). Because.agents/hooks.jsonexists in the workspace,acp_serverregisteredExternalOnSessionEndHookintoon_session_end_hooks. Duringawait session_info.stack.aclose(),LocalConnection.disconnect()attempts to sendInputEvent(session_end_request=True)over the already-closed WebSocket, raisingConnectionClosedOK("received 1000 (OK); then sent 1000 (OK)")and aborting_rebuild_session_agentbefore a replacementlocalharness_externalis spawned. - Synthetic assistant message & poisoned session state (Turn N+1): Instead of returning a JSON-RPC error,
agy_acp_server.pardeletessession_idinself.cleanup(session_id), emits"Agent connection was lost and could not be re-established: Failed to rebuild agent: received 1000 (OK); then sent 1000 (OK)"as a normalagent_message_chunk, and returnsPromptResponse(stop_reason="end_turn"). - Permanent session bricking (Turn N+2+): Because
stopReasonwas"end_turn",AcpAdapterV2records the error string as a normal completed assistant message and keepsactiveSessionIdcached on the aliveagy_acp_server.parprocess—so neither PR fix(antigravity): resume threads after internal prompt errors #30707 (restartRuntimeAfterPromptErroron-32603) nor PR fix(server): Antigravity resumes after its local harness fails #23654 (without--alsologtostderr) prevents Turn N+1 from completing with fake assistant prose.
Steps to reproduce
- Open a workspace containing a non-empty
.agents/hooks.json(for example, Cursor's.agents/hooks.jsonwith{"version": 1, "hooks": {"subagentStop": [...]}}). - Start an Antigravity thread (
gemini-4-argon-medium) in T3 Code. - Have the agent run a command via
run_commandwithWaitMsBeforeAsync: 5000so it moves to the background (<session_id>/task-<step_idx>). - Have the agent immediately cancel that background task via
manage_task({"Action": "kill", "TaskId": "<session_id>/task-<step_idx>"}). - Send a follow-up prompt (or let a PR watch / system wake-up trigger the next turn).
Root-Cause Analysis (4 Compounding Bugs)
1. localharness_external + local_connection.py: Mid-turn WebSocket close with code 1000 (OK) is silently treated as normal turn completion
- When
manage_task(Action="kill")cancels the backgroundrun_commandstep (CortexStepStatus = 6/CORTEX_STEP_STATUS_CANCELED,context canceled by manage_task),stepmanager.(*StepManager).Cancelcancels the step context while the next model invocation (gen_metadata) is starting, causing the invocation to fail withcontext canceled: context canceled(termination_reason = 2). - In
localharness_external((*localHarnessServer).handleConnection), when the agent output channel closes (io.EOF),handleConnectionunconditionally sends a WebSocket Close frame withCloseNormalClosure(1000 (OK)). - In
agy_acp_server.par(google/antigravity/connections/local/local_connection.py):LocalConnection._ws_reader_loop(lines 643–675) iteratesasync for raw_msg in self._ws:.- In Python's
websocketslibrary,async forcatchesConnectionClosedOK(codes1000/1001) and exits the loop without raisingwebsockets.ConnectionClosed! _ws_reader_looptherefore skipsexcept websockets.ConnectionClosed:(never pushingAntigravityConnectionErrortostep_queue) and goes straight tofinally:, pushingCLOSE_SENTINEL(None).LocalConnection.receive_steps()(lines 531–534) seesstep_obj is None(CLOSE_SENTINEL) and returns normally without checkingif not self.is_idle:.- Consequently,
AgyAdapter.prompt(acp_server/server.pyline 5119) returnsPromptResponse(stop_reason='end_turn')for Turn N and leaves the deadsdk_agentinself._sessions[session_id].
2. acp_server/hooks.py + local_connection.py + acp_server/server.py: _rebuild_session_agent crashes during await session_info.stack.aclose() when .agents/hooks.json exists
- On Turn N+1,
agent.chat(chat_prompt)->connection.send(chat_prompt)->self._ws.send(...)immediately raiseswebsockets.exceptions.ConnectionClosedOK: received 1000 (OK); then sent 1000 (OK). AgyAdapter.prompt(server.pyline 5135) catcheswebsockets.ConnectionClosedand callsawait self._rebuild_session_agent(session_id)(line 5147).- Why does
await session_info.stack.aclose()inside_rebuild_session_agent(server.pyline 1982) raiseConnectionClosedOK?- In
acp_server/hooks.py(load_single_hooks_file, lines 142–150), any.agents/hooks.jsonwith a top-level"hooks"dict is normalized to{"default": {"enabled": True, "PreToolUse": []}}(truthy), andacp_hooks.has_workspace_hooks(resolved_cwd)returnsTruewhenever.agents/hooks.jsonis non-empty. - In
AgyAdapter._create_agent_config(server.pyline 4135),if hooks_config or acp_hooks.has_workspace_hooks(resolved_cwd):unconditionally registersExternalOnSessionEndHookintoself._hook_runner.on_session_end_hooks. - When
session_info.stack.aclose()callsLocalConnection.disconnect()(local_connection.pylines 587–635):Sendingif self._hook_runner and self._hook_runner.on_session_end_hooks: try: await self._send_input_event( localharness_pb2.InputEvent(session_end_request=True) ) await self._processor.session_end_done.wait() except Exception as e: hook_error = e ... finally: if hook_error is not None: raise hook_error
session_end_requeston the already-closed WebSocket raisesConnectionClosedOK("received 1000 (OK); then sent 1000 (OK)"), whichdisconnect()stores inhook_errorand re-raises infinally:! - Because
_rebuild_session_agentdoes not catch/suppress exceptions fromawait session_info.stack.aclose()before creating the new stack, it aborts and callsawait self.cleanup(session_id), raising:
RuntimeError: Failed to rebuild agent: received 1000 (OK); then sent 1000 (OK).
- In
3. acp_server/server.py + T3 Code AntigravityAdapterV2: Fatal rebuild failure is emitted as a normal assistant message chunk with stopReason: "end_turn"
- In
AgyAdapter.prompt(server.pylines 5269–5278, 5360–5390), when_rebuild_session_agentraisesRuntimeError,_send_connection_lost_message(session_id, e)emits:as a normalAgent connection was lost and could not be re-established: Failed to rebuild agent: received 1000 (OK); then sent 1000 (OK)agent_message_chunk(session/update) and returnsPromptResponse(stop_reason="end_turn")instead of raising a JSON-RPC error! - On the T3 Code side:
- In
0.1.6(without--alsologtostderr),agy_acp_server.parwrites itsE... server.py] Failed to rebuild agent for session ...log to$TMPDIR/agy_acp_server.par.ERRORon disk rather thanstderr, so T3 Code sees only theagent_message_chunkandstopReason: "end_turn". - Even with PR fix(antigravity): resume threads after internal prompt errors #30707 (
restartRuntimeAfterPromptErroron-32603), Turn N+1 still completes with"end_turn"and pollutes the thread transcript with the synthetic"Agent connection was lost..."assistant message;-32603(ValueError: Session not found) only happens on Turn N+2. - Even with PR fix(server): Antigravity resumes after its local harness fails #23654 (
--alsologtostderr),agy_acp_server.parsends theagent_message_chunk("Agent connection was lost and could not be re-established: ...") over stdout before or concurrently with thestderrlog line, so the synthetic error text can still be appended to the assistant message stream before termination is recorded.
- In
Expected behavior & Suggested Fix in T3 Code
- Intercept synthetic connection-lost chunks / stderr in
AntigravityAdapterV2:- In addition to passing
--alsologtostderr(PR fix(server): Antigravity resumes after its local harness fails #23654) and restarting on-32603(PR fix(antigravity): resume threads after internal prompt errors #30707),AntigravityAdapterV2/AntigravitySessionUpdateshould not recordagent_message_chunkupdates matching^Agent connection was lost and could not be re-established:as normal assistant prose; instead, treat that signal as a transport/session failure that fails/retries the turn and retires the ACP runtime sosession/resumeruns cleanly in a fresh process.
- In addition to passing
- Isolate or filter non-Gemini
.agents/hooks.json:- When
.agents/hooks.jsonin the workspace only contains Cursor/Claude hook keys (such assubagentStop) and no Gemini-compatible hooks,agy_acp_server.parstill treats.agents/hooks.jsonas non-empty and registersExternalOnSessionEndHook, which is what triggersLocalConnection.disconnect()to sendsession_end_requeston a closed WebSocket during_rebuild_session_agent.
- When
Version or commit
0.1.6 (2359643cffa6)
Environment
macOS Darwin 25.5.0 (arm64), T3 Code (Beta) 0.1.6, Antigravity ACP (7cd97045f7b4fe81175a107cdf16f9c51484e3c78a5162cae415338bb6aa5b88), model gemini-4-argon-medium.
Metadata
Metadata
Assignees
Labels
No labels
Activity
Lahai-Roi commentedon Nov 18, 2026
Another reproduction, with one difference that may widen the trigger: no workspace
.agents/hooks.jsonor.gemini/hooks.json— only a user-level~/.gemini/config/hooks.json.Environment
t3 serve --langemini-4-carbonandgemini-4-hydrogen(thinking_level medium/high)~/.gemini/config/hooks.jsonwith a singlePreToolUsehook (matcher"*", a node script that blocks delete commands). NoSessionEndor other events configured. The workspaces themselves have no.agents/or.gemini/hooks file.What happens (3 times in 2 days, different threads)
session/prompt→succeeded).session/promptfor turn N+1 returnssucceededafter ~55 ms with no work done, and the thread showsAgent connection was lost and could not be re-established: Failed to rebuild agent: received 1000 (OK); then sent 1000 (OK)as the assistant message.AcpRequestError: Internal error(matches [Bug]: Antigravity thread permanently fails with Internal error after localharness disconnect drops in-memory session #30594).From the server trace for one occurrence (0.1.10):
AcpAdapterV2.startTurn→session/prompt(55 ms) →AntigravityTurnOutcome.check→ProviderSessionManager.scheduleThreadUnload; no error is raised on the T3 side, consistent with step 3 of your analysis (syntheticagent_message_chunk+end_turn).It is intermittent: another Carbon thread on the same machine took 6 follow-ups in a row (gaps 15 s – 5 min) without hitting it. All failing turns N involved
run_commandcalls, but I have not confirmed whether a background command was killed at the end of turn N.So the
ExternalOnSessionEndHookregistration (or whatever makesLocalConnection.disconnect()send on the closed socket) seems to apply to the user-level hooks config too, not only workspace files — worth covering in the fix. Happy to provide more trace excerpts if useful.cmwoodal commentedon Nov 20, 2026
Another reproduction with a different trigger: a 429 capacity storm, not a killed background task. As in the earlier comment, the only hooks file is user-level (
~/.gemini/config/hooks.json,PreToolUse+PostToolUsecommand hooks). The workspace has none.Environment: T3 Code server
0.1.4-nightly.20261028.3824, Linux x64, managedagy_acp_server.par(9fb60956…),gemini-4-neon-high, full access.Timeline (UTC, 2026-11-20)
Error 429 RESOURCE_EXHAUSTED, reason: HIGH_DEMANDon nearly every tool call for about 28 minutes. The turn ends with the assistant message "We are currently experiencing high demand…", andsession/promptreturns succeeded.session/promptreturnssucceededafter 25 ms. The assistant message isAgent connection was lost and could not be re-established: Failed to rebuild agent: received 1000 (OK); then sent 1000 (OK).session/promptfails within about 4 ms withAcpRequestError, which is the [Bug]: Antigravity thread permanently fails with Internal error after localharness disconnect drops in-memory session #30594 symptom. 0.1.4 predates fix(server): Antigravity resumes after its local harness fails #23654.So a turn that ends on upstream 429s also seems to leave
localharness_externalclosed with 1000. The hook teardown then breaks the rebuild on the next prompt, as described above. Moving the user-level hooks file aside and updating to a build with #23654 are the workarounds I'm using.juliusmarminge commentedon Nov 23, 2026
#23654, now on main: The merge forwards native harness logs, detects the reported terminal rebuild failure, and retires the broken process so a follow-up can resume the saved session.
Not done: The issue also asks to suppress synthetic connection-lost assistant messages and isolate incompatible hooks; neither is implemented, and a failure arriving after end_turn can still leave the preceding turn marked completed.
Closing; open a new issue if what is left still matters to you.