Skip to content

fix(desktop): record an outcome on every terminal chat tool call - #10599

Merged
kodjima33 merged 8 commits into
mainfrom
fix/tool-call-outcome-telemetry
Jul 26, 2026
Merged

kodjima33 merged 8 commits into
mainfrom
fix/tool-call-outcome-telemetry

Conversation

@skanderkaroui

@skanderkaroui skanderkaroui commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

chat_tool_call_completed fired only on success. The call site removed the tool's start time for any terminal status, then gated the event on toolStatus == .completed, so a failed, cancelled, or interrupted tool call consumed its start time and emitted nothing.

Found by querying the live PostHog corpus (project 302298, Omi desktop macOS, 30 days): 23,682 chat_tool_call_completed events containing only successes, and no tool-failure event anywhere in the project. Tool failure rate was not merely unmeasured but structurally unmeasurable — no dashboard could ever show a tool regression, and the tool_stall errors (p50 102s) had no per-tool attribution.

Change

chat_tool_call_completed now fires for every terminal status and carries a bounded outcome.

The subtlety worth reviewing: ToolCallStatus.fromBridgeStatus maps failed, cancelled, and interrupted all to .failed. Emitting naively would have counted user Stops as tool failures — the same mistake that made the legacy chat_agent_error corpus unreadable, where 530 of 1,893 events over 30 days were user Stops recorded as errors. ChatTelemetryDimension.toolOutcome keeps the three apart and is deliberately independent of ToolCallStatus, with a test pinning that independence.

The bridge now preserves cancelled and interrupted from ACP and local subprocess adapters through the Swift callback. Previously ACP collapsed cancellation into failure and the subprocess adapter converted cancellation/interruption back to started, making the new outcome dimension inaccurate. Unknown future statuses are bounded to unknown rather than inflating successful completions.

Event semantics change: the event now counts all terminal calls, not just successes. Filter outcome == "completed" for the previous meaning. No in-repo consumer reads this event (web/admin/lib/response-reliability.ts reads chat_agent_error only), but an external PostHog dashboard counting it raw will see a superset.

Product invariants

  • INV-AGENT-*: adapter lifecycle status is preserved through the existing outbound protocol; canonical cancelled/interrupted events remain failure-terminal in the runtime journal.
  • INV-CHAT-1: path-matched via Providers/ChatProvider.swift. Telemetry call site only — no chat write-path, projection, or timeline behavior changed.
  • INV-AUTH-1: path-matched. No auth behavior changed.

Failure-Class: none

Verification

  • npm test -- --run tests/acp-tool-activity.test.ts tests/local-subprocess-adapter.test.ts — 13/13 pass
  • npm run build — TypeScript green
  • xcrun swift test --package-path Desktop --filter ChatQueryTelemetryTests — 27/27 pass
  • Failure mode pinned at both adapter boundaries and at the telemetry mapping.

Review in cubic

`ToolCallStatus` collapses cancelled/interrupted into `.failed` for the UI,
which is right for rendering but wrong for telemetry: a user Stop is not a
tool defect. Merging them is the same mistake that made the legacy
`chat_agent_error` corpus unreadable, where 530 of 1,893 events over 30 days
were user Stops recorded as errors.

`toolOutcome` keeps the three terminal bridge statuses apart and collapses
anything unrecognized to `completed`, matching `fromBridgeStatus`, so no
unbounded adapter vocabulary can reach PostHog.
`chat_tool_call_completed` carried only `tool_name` and `duration_ms`, so the
event could not express failure at all.

Filtering on `outcome == "completed"` reproduces the previous success-only
meaning. Note the event now counts every terminal call, so any dashboard
counting it raw sees a superset.
The call site removed the tool's start time for any terminal status but then
gated the event on `toolStatus == .completed`, so a failed, cancelled, or
interrupted tool call consumed its start time and emitted nothing.

Consequence in production: 23,682 `chat_tool_call_completed` events over 30
days contained only successes. Tool failure rate was not merely unmeasured but
structurally unmeasurable — no dashboard could show a tool regression, and the
`tool_stall` errors (p50 102s) had no per-tool attribution.

Passing the raw bridge status keeps failed/cancelled/interrupted distinct
through the bounded dimension, so a user Stop is not counted as a tool failure.
Two cases: every terminal bridge status maps to a bounded outcome (unknown
vocabulary collapses to `completed`), and a Stop stays distinguishable from a
failure even though `ToolCallStatus` maps both to `.failed`.

Verification: `xcrun swift test --package-path Desktop --filter
ChatQueryTelemetryTests/` — 27/27 pass.
Removing the success-only gate around the tool-call telemetry emit made the
file one line shorter. Down-only, via --update-baseline.
The tool-call outcome dimension lives in ChatQueryTelemetry.swift, which the
hermetic chat flow already exercises through ChatProvider — it just was not
listed as covered.
Failure-Class: none

Verification: 13 Node tests, TypeScript build, and 27 Swift tests passed

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maintainer automation review: positive signal, not a formal approval because this touches desktop agent/runtime telemetry surfaces that need human maintainer sign-off.

What looks good:

  • The change fixes the original measurement gap by emitting chat_tool_call_completed for every terminal tool-call outcome, while preserving completed, failed, cancelled, and interrupted as separate bounded values.
  • The Swift telemetry mapping avoids counting unknown statuses as successful completions, and the tests pin the user-Stop-vs-failure distinction.
  • The ACP and local subprocess bridge changes preserve cancellation/interruption through the runtime boundary, so the Swift-side outcome dimension should receive the intended terminal status instead of the prior collapsed/started values.
  • I ran the two affected agent adapter test files and the TypeScript build locally: 13/13 tests passed and npm run build succeeded. CI also shows the desktop Swift and agent-runtime checks passing.

No blocking issue found from the static/code review. A human maintainer should still review the telemetry semantics and any external dashboard impact before merge, since the event now counts all terminal calls rather than success-only calls.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior labels Jul 26, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Desktop bug fix: chat_tool_call_completed only fired on success, making tool failures structurally unmeasurable; now emits on every terminal status with a bounded outcome dimension, cancelled/interrupted preserved through the bridge. Tests green.

@kodjima33
kodjima33 merged commit db78304 into main Jul 26, 2026
36 of 37 checks passed
@kodjima33
kodjima33 deleted the fix/tool-call-outcome-telemetry branch July 26, 2026 14:37
skanderkaroui added a commit that referenced this pull request Jul 26, 2026
…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.
Git-on-my-level added a commit that referenced this pull request Jul 27, 2026
…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.
undivisible pushed a commit that referenced this pull request Aug 17, 2026
…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.
undivisible pushed a commit to undivisible/omi that referenced this pull request Sep 29, 2026
…edHardware#10599)

* feat(desktop): add a bounded tool-call outcome dimension

`ToolCallStatus` collapses cancelled/interrupted into `.failed` for the UI,
which is right for rendering but wrong for telemetry: a user Stop is not a
tool defect. Merging them is the same mistake that made the legacy
`chat_agent_error` corpus unreadable, where 530 of 1,893 events over 30 days
were user Stops recorded as errors.

`toolOutcome` keeps the three terminal bridge statuses apart and collapses
anything unrecognized to `completed`, matching `fromBridgeStatus`, so no
unbounded adapter vocabulary can reach PostHog.

* feat(desktop): report an outcome on every terminal tool call

`chat_tool_call_completed` carried only `tool_name` and `duration_ms`, so the
event could not express failure at all.

Filtering on `outcome == "completed"` reproduces the previous success-only
meaning. Note the event now counts every terminal call, so any dashboard
counting it raw sees a superset.

* fix(desktop): emit telemetry for failed tool calls

The call site removed the tool's start time for any terminal status but then
gated the event on `toolStatus == .completed`, so a failed, cancelled, or
interrupted tool call consumed its start time and emitted nothing.

Consequence in production: 23,682 `chat_tool_call_completed` events over 30
days contained only successes. Tool failure rate was not merely unmeasured but
structurally unmeasurable — no dashboard could show a tool regression, and the
`tool_stall` errors (p50 102s) had no per-tool attribution.

Passing the raw bridge status keeps failed/cancelled/interrupted distinct
through the bounded dimension, so a user Stop is not counted as a tool failure.

* test(desktop): cover terminal tool-call outcome mapping

Two cases: every terminal bridge status maps to a bounded outcome (unknown
vocabulary collapses to `completed`), and a Stop stays distinguishable from a
failure even though `ToolCallStatus` maps both to `.failed`.

Verification: `xcrun swift test --package-path Desktop --filter
ChatQueryTelemetryTests/` — 27/27 pass.

* chore(desktop): ratchet the ChatProvider line-count baseline down

Removing the success-only gate around the tool-call telemetry emit made the
file one line shorter. Down-only, via --update-baseline.

* docs(desktop): changelog entry for tool-call outcome telemetry

* test(desktop): cover ChatQueryTelemetry in the hermetic chat flow

The tool-call outcome dimension lives in ChatQueryTelemetry.swift, which the
hermetic chat flow already exercises through ChatProvider — it just was not
listed as covered.

* fix(desktop): preserve terminal tool outcomes

Failure-Class: none

Verification: 13 Node tests, TypeScript build, and 27 Swift tests passed
undivisible pushed a commit to undivisible/omi that referenced this pull request Sep 29, 2026
…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.
undivisible pushed a commit to undivisible/omi that referenced this pull request Sep 29, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants