Repository navigation
fix(agent-proxy): stop persisting an unresolved VM IP as a ready address - #10600
Conversation
When the GCE external-IP poll timed out, `_start_vm_and_wait` returned the
literal string "unknown" and the caller wrote it to Firestore alongside
`status: "ready"`.
"unknown" is truthy, so the poisoned record satisfied every reader:
1. connect takes the fast path (`status == "ready" and vm_ip`)
2. the health probe dials http://unknown:8080/health and fails
3. `_ensure_vm_running(health_failed=True)` finds GCE reporting RUNNING
4. so it hard-resets a healthy VM, then writes `vm.get("ip")` — still
"unknown" — back with `status: "ready"`
No writer anywhere repaired the field, so every later reconnect reset the
user's VM again and never recovered the real address.
Repairs the ownership boundary rather than the call site: `_update_firestore_vm`
owns `agentVm.ip`, so it now refuses any value that is not dialable and a
future caller cannot reintroduce the placeholder. The poll failure raises
instead of returning a sentinel, reusing the callers' existing
`except -> status: "error"` path rather than adding a second one.
Already-poisoned records self-heal: the ready fast path now requires a usable
IP, so such a record is re-provisioned through `_start_vm_and_wait` — the only
path that resolves a real address.
`routers/agent_tools.py` carries a byte-identical copy of the VM start and Firestore update logic, with the same "unknown" sentinel defect. Fixing only the proxy would leave the same poisoned record reachable through `/v1/agent/vm-ensure`. Same shape as the proxy fix: raise rather than return a sentinel, and refuse to persist a non-dialable address at the writer that owns the field. The RUNNING branch re-provisions instead of reporting a placeholder record ready, since that is the only path that resolves a real address.
Covers the property that made the placeholder dangerous — "unknown" is truthy, so it passed every `if ip:` reader — plus the writer-level rejection and a static guard that the literal is only ever bound to the named constant. Confirmed to fail on the unfixed source: "'unknown' assigned to ['ip'] at line 213"
Failure-Class: none Verification: 23 focused backend tests passed
|
Nice fix — this addresses a genuinely nasty production loop cleanly and at the right boundary. The root cause (truthy sentinel Tests look solid — the behavioral test mocks httpx and exercises Leaving a positive signal rather than formal approval since this touches Firestore user-data persistence ( (automated maintainer review — glm-5.2) by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
kodjima33
left a comment
There was a problem hiding this comment.
Backend bug fix: agent-proxy persisted the literal 'unknown' as a ready VM IP, causing repeated hard-resets of healthy VMs; write path now rejects non-dialable IPs and poisoned records self-heal. Tests added.
…ements Seven conflicts, all semantic — #10599/#10600/#10601 landed on main while this branch was in review, and they touch the same files. - agent-proxy/main.py: keeps this branch's restart circuit-breaker (the restart_failed/restart_succeeded fields) AND main's usable-IP guards. Both are needed: the breaker stops hammering GCE, the guard stops persisting a placeholder address as ready. - routers/agent_tools.py: takes main's executor offload and bounded error logging, and keeps this branch's record_fallback on the degraded-toolset path — AGENTS.md requires it on a fail-open branch and main has no equivalent. - routers/integrations.py: the registry supersedes the inline OAUTH_CONFIGS / AUTH_PROVIDERS tables (neither is referenced elsewhere in the file), but GMAIL_READONLY_SCOPE, GOOGLE_INTEGRATION_KEY and google_integration_has_scope each still have a live caller, so their import is kept. - agent-cloud/agent.mjs: main fixed the /sync row-schema data loss (#10602) by grouping rows by column set; this branch added a SQL-identifier guard on the interpolated column names. Kept both — the guard now runs against the union of every row's columns, which is a superset of the old rows[0] check. - utils/llm/app_generator.py: took main's deletion of _generate_app_icon_via_openai. It has no callers and main removed it deliberately in "enforce gateway-only LLM routing" (bbbdf3b). - chat-hermetic.yaml: union of both covers lists. - desktop-swift-providers.json: line-count baseline, regenerated below.
…andling (#10256) # Agent reliability & performance overhaul One PR, four measured iterations on the agent stack (cloud VM lane + desktop kernel + desktop error UX). Every change traces to an instrumented experiment, a telemetry corpus, or a live reproduction — the evidence loop ran ~90 live agent runs and session simulations against a real 27MB database copy, plus a 30-day PostHog `chat_agent_error` deep dive. ## Headline results (same 8-turn conversation, real data, before → after) | Metric | Before | After | |---|---|---| | Conversation wall time | 256s | 155s (−39%) | | Conversation cost | | −55% | | Worst client silent gap | 46s | ~13s, typical 1–4s | | Stop mid-turn | error / indistinguishable partial | `interrupted: true` partial | | Reconnect | total context amnesia | full context retained | | Task battery (5 heavy tasks) | 519s, 53 tool calls | 199s, 20 tool calls (−62%) | ## What's in here, by area ### Subagent architecture (desktop kernel + cloud) - `researcher` subagent (SDK `agents` option): row-heavy data exploration runs in a disposable child context and returns distilled prose findings — Haiku-pinned (measured fastest, ~3× cheaper, accuracy parity) and routed by row-volume. A typed handoff remains parked because this SDK stream exposes no production interception point. - Kernel: run cancellation cascades to delegated children (background floating-bar agents deliberately exempt — product behavior pinned by test); spawn-time `toolPolicy.allowedToolNames` enforced at the capability broker (narrow-only, fail-closed, no schema changes). ### Streaming & session reliability (cloud lane) - `includePartialMessages` was never enabled — all streaming code was dead; every turn had 17–46s of total client silence (the stall→Stop churn mechanism). Now: real deltas, subagent progress as `subagent:*` tool_activity, bounded ephemeral researcher snippets in status events (never the answer/transcript), and a 10s turn heartbeat capping any remaining gap. - Sessions survive WebSocket reconnects (server-scope session, swappable sink, `session_state` hello); reconnect amnesia reproduced live before the fix ("I don't have any earlier conversation context") and re-verified fixed. - Real-SDK interrupts map to `interrupted: true` partial results instead of errors; pending tools terminalize as `interrupted` rather than false `completed`; a prewarm race that made Stop a silent no-op on fast first queries is fixed. - Supersede queue-of-1: a query arriving mid-turn parks, interrupts, and starts only at the turn boundary — double-taps can no longer interleave two answers. ### Tool system (both sides of the VM↔backend boundary) - `get_daily_recap` gains explicit date ranges (it could only anchor to "now" — root cause of 13+ SQL-turn fallbacks), authoritative empty-range statements, hourly timeline/top windows; new `get_app_usage` day×app matrix; batch `execute_sql`; task near-duplicate guidance (the store carries ~63% duplicate extractions). - SQL guard: `stmt.readonly` replaces a prefix guard that rejected CTE reads and false-positived on user data containing words like "create"; row cap moved to iteration. - Backend-tool loading: per-definition isolation + name validation + dedupe at fetch time (local tool names are reserved); 30s retry on failure (a boot blip previously lost calendar/gmail for the VM's lifetime, silently); `resp.ok` checked; Pydantic `Optional` accepts explicit `null`; results bounded at 10K chars; `agent_tools.py` gets per-tool schema isolation + `record_fallback` on degraded toolsets. ### Two-plane error handling & resilience - Bounded 7-category taxonomy shared JS↔Python: users get fixed calm copy + automatic backoff on transient failures; the internal plane gets maximum structured detail (full stacks, JSON lines). Raw SDK and integration-connect response details stay off the model/user plane. - Owned-abort grace window replaces blanket "aborted" string suppression; session-loop death notifies the client and recovers on the next query instead of hanging forever; crash exits flush a synchronous post-mortem. - agent-proxy: Firestore-resident VM restart circuit breaker (3 failures → 30min cooldown, honest user copy instead of an infinite spinner), VM connect retry ×3 with progress events, auth-push retry + degraded-tools notice, all broad catches split with `exc_info=True`, breaker reads off the event loop. - Context ceilings: `maxTurns: 10` per user turn + tool-result truncation (SDK compaction is API-beta only in 0.2.39 — tracked for 0.2.40+). ### Desktop error UX (from the PostHog deep dive) - The opaque "Something went wrong. Please try again." bucket (401 events/108 users) fully decomposed via `raw_error`; the three "unexplained" error spikes were retry storms caused by the copy itself (users with exhausted Anthropic credits obeying "please try again"). - `AgentErrorClassifier`: 12 bounded codes with honest copy and retryable verdicts — "try again" only when a retry can help; `chat_agent_error` telemetry gains `error_code`/`retryable`/`failure_code`/`failure_source`/`adapter_id`/`provider` (closed vocabularies, never raw exception text — test-pinned). - Also unwedges main: two files from an upstream refactor had swift-format drift, one wedged against its frozen line-count ratchet. ## Product invariants - **INV-AGENT-***: touched `desktop/macos/agent/src/runtime/**`. Lifecycle affected by the cascade; guard tests updated (`cancellation.test.ts` +3 behavioral cases, `run-tool-capability.test.ts` +3, `control-tools.test.ts` schema cases, new `spawn-tool-policy.test.ts`). toolPolicy strengthens leaf-worker restrictions (narrow-only, kernel-internal checks). - **INV-CHAT-1**: path-matched (`ChatProvider.swift` telemetry call site, regenerated `Sources/Generated/*`); no chat write-path, projection, or timeline behavior changed. - **INV-AUTH-1**: path-matched; no session-death behavior changed — auth-classified errors alter copy and telemetry only. - **INV-INT-1**: path-matched by the connector guidance overlay; connector disclosure behavior remains explicit. - **INV-MEM-1**: path-matched only by `web/app/src/components/memories/MemoriesPage.tsx` (and `useMemories.ts`), which this PR touches as Prettier reformatting with zero logic change. No tier vocabulary, canonical collection, or default Short-term+Long-term access policy is altered; Archive remains excluded from default access. Failure-Class: none ## Deliberate non-changes (on record) `bypassPermissions` stays — the per-user VM is a single-tenant sandbox; SDK-level tool gating is intentionally off (maintainer decision). No Sentry (not in the backend stack); no chat-save outbox (the write target is the failure domain); no cross-language error library (7-string contract, ~15 lines per side); prompt-level turn-discipline and batching rejected by experiment (model-dependent). ## Integration order Merge #10600, #10601, and #10599 first, then merge current `main` into this branch before clearing the final review. Those focused PRs repair the VM-IP recovery boundary, the backend event-loop/error plane, and end-to-end tool outcome transport that this larger branch also touches. ## Verification - agent-cloud: vitest 41/41 (6 files incl. hermetic WS e2e that spawns the real server against a scripted SDK — now also pins interrupted tool terminalization); CI-wired via `agent-cloud-tests` in the checks manifest (first CI coverage for the package). - Desktop agent: 587/587 + agent-logic harness green; Swift: build green, `AgentErrorClassifierTests` + `ChatQueryTelemetryTests` 34/34; backend units 12/12 (breaker transitions, classification, per-tool isolation). - Full preflight 55/55 locally (Mac mini cross-validation pending — machine offline). Cascade regression test verified to fail on unfixed code. Live GCE breaker trip is the one non-CI-coverable path; manual verification planned and declared per DoD.
…ks (#11029) ## Summary - Make the durable `account_deletions/{uid}` marker a single fail-closed admission policy across Firebase, developer/MCP keys, OAuth issuance, HTTP/WebSocket entry points, Agent proxy sessions, and Agent VM provisioning. Completed and unknown markers remain fenced so an old token cannot revive a deleted UID. - Make deletion admission atomic at `pending`, revoke UID-bearing API/OAuth credentials, delete the account's GCE Agent VM before its Firestore pointer disappears, and transactionally fence late proxy/VM writes so in-flight work cannot recreate owner data. - Make accepted macOS cleanup durable across restart, drain owner-bound VM/sync work before deleting storage, remove the legacy anonymous fallback, upload a consistent SQLite snapshot with cancellable compression and bounded retries, and preserve typed startup errors in Flutter. Repeated delete requests during `pending`/`running` intentionally receive typed `403 account_deletion_in_progress` responses without marker rollback or requeue. The deletion fence is preserved. Canonical project: [BasedHardware Project #15](https://github.com/orgs/BasedHardware/projects/15) ## Sanitized incident evidence - A delete confirmation preceded a later same-provider sign-in/onboarding sequence by nine days. - The deleted UID's user document and GCE instance were gone, while its durable deletion marker completed after retried queue acceleration failures. - No verified event proves old server memory reads after deletion. This PR treats legacy local-database migration, still-valid old credentials, and late owner-scoped work as identity-isolation risks; typed readiness failures remain timeout-class evidence rather than proof of server data disclosure. Related lineage: #10444, #7696, #9632, #10597, #9821, #6891, #6892, #10600, and #10694. ## Failure class Failure-Class: none This is an audit-driven hardening sweep across durable deletion admission, credential revocation, local owner-data disposal, and Agent VM/proxy lifecycle safety. The reusable prevention surfaces are the shared fail-closed policy, transactional admission/CAS writers, the durable local cleanup journal, the effective-owner generation fence, and behavioral regression tests. ## Product invariants affected - INV-AUTH-1 — preserves the exclusive effective-owner transition, clears accepted-deletion storage before credential/session publication, blocks every credential family after durable admission, and rejects late owner-bound Agent VM continuations. - INV-CHAT-1 — drains Agent VM/sync work at the existing owner transition, transactionally fences late proxy message/session writes, and preserves typed startup failures without changing canonical transcript ownership. ## Changed paths - `.github/scripts/product_file_line_count_ratchet_baseline/backend-database.json` - `.github/scripts/product_file_line_count_ratchet_baseline/backend-routers.json` - `.github/scripts/product_file_line_count_ratchet_baseline/desktop-swift-root.json` - `app/lib/services/agent_chat_service.dart` - `app/test/services/agent_chat_service_test.dart` - `backend/agent-proxy/Dockerfile` - `backend/agent-proxy/main.py` - `backend/database/account_deletion_projection_fence.py` - `backend/database/mcp_oauth.py` - `backend/database/users.py` - `backend/dependencies.py` - `backend/routers/apps.py` - `backend/routers/desktop_agent_vm.py` - `backend/routers/mcp_sse.py` - `backend/routers/oauth.py` - `backend/routers/transcribe.py` - `backend/services/users/account_deletion.py` - `backend/testing/e2e/test_account_deletion_cloud_tasks.py` - `backend/tests/services/users/test_account_deletion.py` - `backend/tests/unit/test_account_deletion_auth_fence.py` - `backend/tests/unit/test_agent_proxy_async_boundaries.py` - `backend/tests/unit/test_agent_proxy_startup_client_gone.py` - `backend/tests/unit/test_byok_security.py` - `backend/tests/unit/test_dependency_async_boundaries.py` - `backend/tests/unit/test_desktop_agent_vm.py` - `backend/tests/unit/test_mcp_api_key_auth_context.py` - `backend/tests/unit/test_mcp_oauth.py` - `backend/tests/unit/test_oauth_token_async_boundaries.py` - `backend/utils/account_deletion_access.py` - `backend/utils/other/endpoints.py` - `desktop/macos/Desktop/Sources/AgentSyncService.swift` - `desktop/macos/Desktop/Sources/AgentVMService.swift` - `desktop/macos/Desktop/Sources/AuthService.swift` - `desktop/macos/Desktop/Sources/Chat/RuntimeOwnerIdentity.swift` - `desktop/macos/Desktop/Sources/DefaultsKey.swift` - `desktop/macos/Desktop/Sources/DesktopAutomationBridge.swift` - `desktop/macos/Desktop/Sources/MainWindow/Pages/Settings/Components/SettingsContentView+SettingsUpdates.swift` - `desktop/macos/Desktop/Sources/Rewind/Core/RewindDatabase+AccountDeletion.swift` - `desktop/macos/Desktop/Tests/AgentSyncBatchQueryTests.swift` - `desktop/macos/Desktop/Tests/AgentVMLifecycleFenceTests.swift` - `desktop/macos/Desktop/Tests/AuthSessionCoordinatorTests.swift` - `desktop/macos/Desktop/Tests/OnboardingPersistenceClearingTests.swift` - `desktop/macos/Desktop/Tests/RewindDatabaseLifecycleTests.swift` - `desktop/macos/changelog/unreleased/20260802-account-deletion-local-data.json` - `desktop/macos/e2e/flows/logout.yaml` ## Verification - Focused backend deletion/auth/proxy/VM suite: `194 passed`. - Hermetic Cloud Tasks deletion suite: `5 passed`; repeated pending/running requests are asserted as typed `403` without requeue. - Focused macOS deletion, owner-fence, snapshot, and sync suite: `32 tests`, `0 failures`. - Focused Flutter Agent Chat suite: `2 passed`. - Follow-up MCP OAuth consent suite: `37 passed`. - Follow-up macOS cleanup/bridge compile suite: `17 tests`, `0 failures`. - Python runtime sources compile cleanly; pinned Python/Dart/Swift formatters and `git diff --check` are clean. - Required CI-lane PR-body preflight: `34 checks passed` in `108.01s`. Backend Hermetic Merge Gate: in scope because backend runtime and hermetic contract code changed. ## Limitations - No production Firebase/Auth, Firestore, Cloud Tasks, GCE, deployment, release, or customer-data mutation was performed. - Same-provider recreation is covered hermetically at the UID/auth boundary; no live Google sign-in was attempted. - Agent readiness and teardown are covered through backend state-machine, proxy protocol, owner-generation, snapshot/upload, credential cleanup, and stale-pointer tests; no live GCE VM was provisioned. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/11029?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…andling (#10256) # Agent reliability & performance overhaul One PR, four measured iterations on the agent stack (cloud VM lane + desktop kernel + desktop error UX). Every change traces to an instrumented experiment, a telemetry corpus, or a live reproduction — the evidence loop ran ~90 live agent runs and session simulations against a real 27MB database copy, plus a 30-day PostHog `chat_agent_error` deep dive. ## Headline results (same 8-turn conversation, real data, before → after) | Metric | Before | After | |---|---|---| | Conversation wall time | 256s | 155s (−39%) | | Conversation cost | | −55% | | Worst client silent gap | 46s | ~13s, typical 1–4s | | Stop mid-turn | error / indistinguishable partial | `interrupted: true` partial | | Reconnect | total context amnesia | full context retained | | Task battery (5 heavy tasks) | 519s, 53 tool calls | 199s, 20 tool calls (−62%) | ## What's in here, by area ### Subagent architecture (desktop kernel + cloud) - `researcher` subagent (SDK `agents` option): row-heavy data exploration runs in a disposable child context and returns distilled prose findings — Haiku-pinned (measured fastest, ~3× cheaper, accuracy parity) and routed by row-volume. A typed handoff remains parked because this SDK stream exposes no production interception point. - Kernel: run cancellation cascades to delegated children (background floating-bar agents deliberately exempt — product behavior pinned by test); spawn-time `toolPolicy.allowedToolNames` enforced at the capability broker (narrow-only, fail-closed, no schema changes). ### Streaming & session reliability (cloud lane) - `includePartialMessages` was never enabled — all streaming code was dead; every turn had 17–46s of total client silence (the stall→Stop churn mechanism). Now: real deltas, subagent progress as `subagent:*` tool_activity, bounded ephemeral researcher snippets in status events (never the answer/transcript), and a 10s turn heartbeat capping any remaining gap. - Sessions survive WebSocket reconnects (server-scope session, swappable sink, `session_state` hello); reconnect amnesia reproduced live before the fix ("I don't have any earlier conversation context") and re-verified fixed. - Real-SDK interrupts map to `interrupted: true` partial results instead of errors; pending tools terminalize as `interrupted` rather than false `completed`; a prewarm race that made Stop a silent no-op on fast first queries is fixed. - Supersede queue-of-1: a query arriving mid-turn parks, interrupts, and starts only at the turn boundary — double-taps can no longer interleave two answers. ### Tool system (both sides of the VM↔backend boundary) - `get_daily_recap` gains explicit date ranges (it could only anchor to "now" — root cause of 13+ SQL-turn fallbacks), authoritative empty-range statements, hourly timeline/top windows; new `get_app_usage` day×app matrix; batch `execute_sql`; task near-duplicate guidance (the store carries ~63% duplicate extractions). - SQL guard: `stmt.readonly` replaces a prefix guard that rejected CTE reads and false-positived on user data containing words like "create"; row cap moved to iteration. - Backend-tool loading: per-definition isolation + name validation + dedupe at fetch time (local tool names are reserved); 30s retry on failure (a boot blip previously lost calendar/gmail for the VM's lifetime, silently); `resp.ok` checked; Pydantic `Optional` accepts explicit `null`; results bounded at 10K chars; `agent_tools.py` gets per-tool schema isolation + `record_fallback` on degraded toolsets. ### Two-plane error handling & resilience - Bounded 7-category taxonomy shared JS↔Python: users get fixed calm copy + automatic backoff on transient failures; the internal plane gets maximum structured detail (full stacks, JSON lines). Raw SDK and integration-connect response details stay off the model/user plane. - Owned-abort grace window replaces blanket "aborted" string suppression; session-loop death notifies the client and recovers on the next query instead of hanging forever; crash exits flush a synchronous post-mortem. - agent-proxy: Firestore-resident VM restart circuit breaker (3 failures → 30min cooldown, honest user copy instead of an infinite spinner), VM connect retry ×3 with progress events, auth-push retry + degraded-tools notice, all broad catches split with `exc_info=True`, breaker reads off the event loop. - Context ceilings: `maxTurns: 10` per user turn + tool-result truncation (SDK compaction is API-beta only in 0.2.39 — tracked for 0.2.40+). ### Desktop error UX (from the PostHog deep dive) - The opaque "Something went wrong. Please try again." bucket (401 events/108 users) fully decomposed via `raw_error`; the three "unexplained" error spikes were retry storms caused by the copy itself (users with exhausted Anthropic credits obeying "please try again"). - `AgentErrorClassifier`: 12 bounded codes with honest copy and retryable verdicts — "try again" only when a retry can help; `chat_agent_error` telemetry gains `error_code`/`retryable`/`failure_code`/`failure_source`/`adapter_id`/`provider` (closed vocabularies, never raw exception text — test-pinned). - Also unwedges main: two files from an upstream refactor had swift-format drift, one wedged against its frozen line-count ratchet. ## Product invariants - **INV-AGENT-***: touched `desktop/macos/agent/src/runtime/**`. Lifecycle affected by the cascade; guard tests updated (`cancellation.test.ts` +3 behavioral cases, `run-tool-capability.test.ts` +3, `control-tools.test.ts` schema cases, new `spawn-tool-policy.test.ts`). toolPolicy strengthens leaf-worker restrictions (narrow-only, kernel-internal checks). - **INV-CHAT-1**: path-matched (`ChatProvider.swift` telemetry call site, regenerated `Sources/Generated/*`); no chat write-path, projection, or timeline behavior changed. - **INV-AUTH-1**: path-matched; no session-death behavior changed — auth-classified errors alter copy and telemetry only. - **INV-INT-1**: path-matched by the connector guidance overlay; connector disclosure behavior remains explicit. - **INV-MEM-1**: path-matched only by `web/app/src/components/memories/MemoriesPage.tsx` (and `useMemories.ts`), which this PR touches as Prettier reformatting with zero logic change. No tier vocabulary, canonical collection, or default Short-term+Long-term access policy is altered; Archive remains excluded from default access. Failure-Class: none ## Deliberate non-changes (on record) `bypassPermissions` stays — the per-user VM is a single-tenant sandbox; SDK-level tool gating is intentionally off (maintainer decision). No Sentry (not in the backend stack); no chat-save outbox (the write target is the failure domain); no cross-language error library (7-string contract, ~15 lines per side); prompt-level turn-discipline and batching rejected by experiment (model-dependent). ## Integration order Merge #10600, #10601, and #10599 first, then merge current `main` into this branch before clearing the final review. Those focused PRs repair the VM-IP recovery boundary, the backend event-loop/error plane, and end-to-end tool outcome transport that this larger branch also touches. ## Verification - agent-cloud: vitest 41/41 (6 files incl. hermetic WS e2e that spawns the real server against a scripted SDK — now also pins interrupted tool terminalization); CI-wired via `agent-cloud-tests` in the checks manifest (first CI coverage for the package). - Desktop agent: 587/587 + agent-logic harness green; Swift: build green, `AgentErrorClassifierTests` + `ChatQueryTelemetryTests` 34/34; backend units 12/12 (breaker transitions, classification, per-tool isolation). - Full preflight 55/55 locally (Mac mini cross-validation pending — machine offline). Cascade regression test verified to fail on unfixed code. Live GCE breaker trip is the one non-CI-coverable path; manual verification planned and declared per DoD.
…ements Seven conflicts, all semantic — BasedHardware#10599/BasedHardware#10600/BasedHardware#10601 landed on main while this branch was in review, and they touch the same files. - agent-proxy/main.py: keeps this branch's restart circuit-breaker (the restart_failed/restart_succeeded fields) AND main's usable-IP guards. Both are needed: the breaker stops hammering GCE, the guard stops persisting a placeholder address as ready. - routers/agent_tools.py: takes main's executor offload and bounded error logging, and keeps this branch's record_fallback on the degraded-toolset path — AGENTS.md requires it on a fail-open branch and main has no equivalent. - routers/integrations.py: the registry supersedes the inline OAUTH_CONFIGS / AUTH_PROVIDERS tables (neither is referenced elsewhere in the file), but GMAIL_READONLY_SCOPE, GOOGLE_INTEGRATION_KEY and google_integration_has_scope each still have a live caller, so their import is kept. - agent-cloud/agent.mjs: main fixed the /sync row-schema data loss (BasedHardware#10602) by grouping rows by column set; this branch added a SQL-identifier guard on the interpolated column names. Kept both — the guard now runs against the union of every row's columns, which is a superset of the old rows[0] check. - utils/llm/app_generator.py: took main's deletion of _generate_app_icon_via_openai. It has no callers and main removed it deliberately in "enforce gateway-only LLM routing" (bf36684). - chat-hermetic.yaml: union of both covers lists. - desktop-swift-providers.json: line-count baseline, regenerated below.
…andling (BasedHardware#10256) # Agent reliability & performance overhaul One PR, four measured iterations on the agent stack (cloud VM lane + desktop kernel + desktop error UX). Every change traces to an instrumented experiment, a telemetry corpus, or a live reproduction — the evidence loop ran ~90 live agent runs and session simulations against a real 27MB database copy, plus a 30-day PostHog `chat_agent_error` deep dive. ## Headline results (same 8-turn conversation, real data, before → after) | Metric | Before | After | |---|---|---| | Conversation wall time | 256s | 155s (−39%) | | Conversation cost | | −55% | | Worst client silent gap | 46s | ~13s, typical 1–4s | | Stop mid-turn | error / indistinguishable partial | `interrupted: true` partial | | Reconnect | total context amnesia | full context retained | | Task battery (5 heavy tasks) | 519s, 53 tool calls | 199s, 20 tool calls (−62%) | ## What's in here, by area ### Subagent architecture (desktop kernel + cloud) - `researcher` subagent (SDK `agents` option): row-heavy data exploration runs in a disposable child context and returns distilled prose findings — Haiku-pinned (measured fastest, ~3× cheaper, accuracy parity) and routed by row-volume. A typed handoff remains parked because this SDK stream exposes no production interception point. - Kernel: run cancellation cascades to delegated children (background floating-bar agents deliberately exempt — product behavior pinned by test); spawn-time `toolPolicy.allowedToolNames` enforced at the capability broker (narrow-only, fail-closed, no schema changes). ### Streaming & session reliability (cloud lane) - `includePartialMessages` was never enabled — all streaming code was dead; every turn had 17–46s of total client silence (the stall→Stop churn mechanism). Now: real deltas, subagent progress as `subagent:*` tool_activity, bounded ephemeral researcher snippets in status events (never the answer/transcript), and a 10s turn heartbeat capping any remaining gap. - Sessions survive WebSocket reconnects (server-scope session, swappable sink, `session_state` hello); reconnect amnesia reproduced live before the fix ("I don't have any earlier conversation context") and re-verified fixed. - Real-SDK interrupts map to `interrupted: true` partial results instead of errors; pending tools terminalize as `interrupted` rather than false `completed`; a prewarm race that made Stop a silent no-op on fast first queries is fixed. - Supersede queue-of-1: a query arriving mid-turn parks, interrupts, and starts only at the turn boundary — double-taps can no longer interleave two answers. ### Tool system (both sides of the VM↔backend boundary) - `get_daily_recap` gains explicit date ranges (it could only anchor to "now" — root cause of 13+ SQL-turn fallbacks), authoritative empty-range statements, hourly timeline/top windows; new `get_app_usage` day×app matrix; batch `execute_sql`; task near-duplicate guidance (the store carries ~63% duplicate extractions). - SQL guard: `stmt.readonly` replaces a prefix guard that rejected CTE reads and false-positived on user data containing words like "create"; row cap moved to iteration. - Backend-tool loading: per-definition isolation + name validation + dedupe at fetch time (local tool names are reserved); 30s retry on failure (a boot blip previously lost calendar/gmail for the VM's lifetime, silently); `resp.ok` checked; Pydantic `Optional` accepts explicit `null`; results bounded at 10K chars; `agent_tools.py` gets per-tool schema isolation + `record_fallback` on degraded toolsets. ### Two-plane error handling & resilience - Bounded 7-category taxonomy shared JS↔Python: users get fixed calm copy + automatic backoff on transient failures; the internal plane gets maximum structured detail (full stacks, JSON lines). Raw SDK and integration-connect response details stay off the model/user plane. - Owned-abort grace window replaces blanket "aborted" string suppression; session-loop death notifies the client and recovers on the next query instead of hanging forever; crash exits flush a synchronous post-mortem. - agent-proxy: Firestore-resident VM restart circuit breaker (3 failures → 30min cooldown, honest user copy instead of an infinite spinner), VM connect retry ×3 with progress events, auth-push retry + degraded-tools notice, all broad catches split with `exc_info=True`, breaker reads off the event loop. - Context ceilings: `maxTurns: 10` per user turn + tool-result truncation (SDK compaction is API-beta only in 0.2.39 — tracked for 0.2.40+). ### Desktop error UX (from the PostHog deep dive) - The opaque "Something went wrong. Please try again." bucket (401 events/108 users) fully decomposed via `raw_error`; the three "unexplained" error spikes were retry storms caused by the copy itself (users with exhausted Anthropic credits obeying "please try again"). - `AgentErrorClassifier`: 12 bounded codes with honest copy and retryable verdicts — "try again" only when a retry can help; `chat_agent_error` telemetry gains `error_code`/`retryable`/`failure_code`/`failure_source`/`adapter_id`/`provider` (closed vocabularies, never raw exception text — test-pinned). - Also unwedges main: two files from an upstream refactor had swift-format drift, one wedged against its frozen line-count ratchet. ## Product invariants - **INV-AGENT-***: touched `desktop/macos/agent/src/runtime/**`. Lifecycle affected by the cascade; guard tests updated (`cancellation.test.ts` +3 behavioral cases, `run-tool-capability.test.ts` +3, `control-tools.test.ts` schema cases, new `spawn-tool-policy.test.ts`). toolPolicy strengthens leaf-worker restrictions (narrow-only, kernel-internal checks). - **INV-CHAT-1**: path-matched (`ChatProvider.swift` telemetry call site, regenerated `Sources/Generated/*`); no chat write-path, projection, or timeline behavior changed. - **INV-AUTH-1**: path-matched; no session-death behavior changed — auth-classified errors alter copy and telemetry only. - **INV-INT-1**: path-matched by the connector guidance overlay; connector disclosure behavior remains explicit. - **INV-MEM-1**: path-matched only by `web/app/src/components/memories/MemoriesPage.tsx` (and `useMemories.ts`), which this PR touches as Prettier reformatting with zero logic change. No tier vocabulary, canonical collection, or default Short-term+Long-term access policy is altered; Archive remains excluded from default access. Failure-Class: none ## Deliberate non-changes (on record) `bypassPermissions` stays — the per-user VM is a single-tenant sandbox; SDK-level tool gating is intentionally off (maintainer decision). No Sentry (not in the backend stack); no chat-save outbox (the write target is the failure domain); no cross-language error library (7-string contract, ~15 lines per side); prompt-level turn-discipline and batching rejected by experiment (model-dependent). ## Integration order Merge BasedHardware#10600, BasedHardware#10601, and BasedHardware#10599 first, then merge current `main` into this branch before clearing the final review. Those focused PRs repair the VM-IP recovery boundary, the backend event-loop/error plane, and end-to-end tool outcome transport that this larger branch also touches. ## Verification - agent-cloud: vitest 41/41 (6 files incl. hermetic WS e2e that spawns the real server against a scripted SDK — now also pins interrupted tool terminalization); CI-wired via `agent-cloud-tests` in the checks manifest (first CI coverage for the package). - Desktop agent: 587/587 + agent-logic harness green; Swift: build green, `AgentErrorClassifierTests` + `ChatQueryTelemetryTests` 34/34; backend units 12/12 (breaker transitions, classification, per-tool isolation). - Full preflight 55/55 locally (Mac mini cross-validation pending — machine offline). Cascade regression test verified to fail on unfixed code. Live GCE breaker trip is the one non-CI-coverable path; manual verification planned and declared per DoD.
Problem
When the GCE external-IP poll timed out,
_start_vm_and_waitreturned the literal string"unknown"and the caller wrote it to Firestore alongsidestatus: "ready"."unknown"is truthy, so the poisoned record satisfied every reader:status == "ready" and vm_ip)http://unknown:8080/healthand fails_ensure_vm_running(health_failed=True)finds GCE reportingRUNNINGvm.get("ip")— still"unknown"— back withstatus: "ready"No writer anywhere repaired the field, so every later reconnect reset the user's VM again and never recovered the real address. The field was already known to be dangerous: both copies guard
candidate != "unknown"when reading the GCE response, but nothing guarded the write.Change
Repairs the ownership boundary rather than the call site, per the failure-class guidance:
_update_firestore_vmownsagentVm.ip, so it now refuses any value that is not dialable. A future caller cannot reintroduce the placeholder.except -> status: "error"path rather than adding a second one.RUNNINGbranches require a usable IP._start_vm_and_waitfirst checks whether GCE is already running; if so it resolves the external IP without issuing a second start request.Both copies are fixed (
agent-proxy/main.pyandrouters/agent_tools.py); they were byte-identical.Product invariants
None matched by these paths.
Failure-Class: none
Verification
pytest tests/unit/test_agent_proxy_async_boundaries.py tests/unit/test_agent_vm_async.py tests/unit/test_tools_agent_route_response_shape.py tests/unit/test_agent_tool_geolocation_async.py— 23 passed'unknown' assigned to ['ip'] at line 213, plus the writer-rejectionValueErrorcase