feat: surface allowlisted OpenCode remediation links in recovery surfaces (#2396)

This commit is contained in:
Carlos Florêncio
2026-08-07 21:27:43 +01:00
committed by GitHub
parent 9e6c2098b1
commit 9e503c5e6b
41 changed files with 2159 additions and 44 deletions
@@ -0,0 +1,234 @@
---
spec: docs/specs/agent-stall-recovery/spec.md
decision: docs/decisions/2026-08-07-allowlisted-provider-action-links.md
created: 2026-08-07
status: implemented
---
# Implementation Plan: OpenCode Actionable Error Links
## Outcome
Carry an optional, validated OpenCode remediation URL from an ACP/managed
diagnostic into Kandev's existing recoverable-error lifecycle, then render it
as a localized external link in every recovery surface. The short error remains
the primary copy; raw stderr and raw ACP error payloads remain excluded.
This plan is an incremental repair to the completed OpenCode terminal-error
surfacing work. It does not change prompt correlation, retry behavior, session
states, or recovery actions.
## Mobile design contract
The recovery link is an inline addition to the existing recovery cards and
notices; there is no new navigation or surface.
- Entry point: same chat/office surface on every viewport.
- Nearest shipped exemplar: the provider-quota recovery card
(`mobile-provider-quota-recovery.spec.ts`); the link reuses its inline
composition and 44px phone touch sizing (`min-h-11` below `sm`, `min-h-8`
above).
- Presentation: inline text link next to the existing recovery actions —
no drawer, dialog, or new route (content depth does not justify one).
- Scroll owner: unchanged chat panel; the link is `break-words`-safe and adds
no horizontal scroll.
- Touch/focus: minimum 44px phone target, native anchor keyboard reachability,
`target="_blank"` + `rel="noopener noreferrer"`.
- Mobile Playwright: `mobile-provider-remediation-link.spec.ts` proves the
link, focus, 44px target, URL-free details, and zero document overflow.
## Root-cause constraint
The reported OpenCode 1.18.5 ACP failure contains only the short message in
Kandev's ACP error, logs, and managed stderr. OpenCode's TUI has additional
provider-side context, including the workspace URL, but that context is not
transported by the ACP service-failure response. No Kandev-only parser can
display bytes that never crossed the managed process boundary.
The Kandev half therefore supports the optional field now and keeps a truthful
fallback. A separate upstream OpenCode change is required for the exact
1.18.5-style failure to produce a link: OpenCode must emit an optional
`action_url` in its ACP service-failure data or in its already-supported
structured error-only stderr record. The plan must not add a private-log tail or
raw-error side channel to work around that dependency.
## Contract and security rules
- Add optional `remediation_url` to the normalized safe provider diagnostic and
persist the same field in `LastAgentError` and recovery metadata.
- Accept only `https://opencode.ai/workspace/<safe-workspace-id>/go` with an
exact host, HTTPS scheme, no userinfo/query/fragment, bounded identifier, and
bounded total length.
- Extract the URL before sanitizing the provider message; the message must
remain URL-free and identifier-redacted.
- For a future ACP `RequestError`, read only the structured `action_url` and
safe message fields; never derive a browser link by copying `err.Error()`.
- Keep the URL out of generic logs, recent-stderr projections, raw ACP payloads,
and technical text. Render it as a separate link with `noopener noreferrer`.
- If validation or transport fails, preserve the current generic recovery card
and current short message.
## Backend work
### 1. Normalize transport-provided action URLs
Extend the existing OpenCode stderr parser and ACP prompt-error projection with
one shared allowlist validator. Structured stderr extracts a valid URL from the
provider error before sanitization; future ACP service-failure data accepts only
the explicit structured field. The provider diagnostic remains bounded and
optional, and all existing session/generation correlation rules stay intact.
### 2. Persist and publish the safe field
Extend `LastAgentError` with the validated URL and add the URL to generic
recovery-message metadata independently of quota classification. Reuse the
existing session metadata and `session.state_changed` snapshot so reloads,
Kanban banners, and Office failed-session rows see the same value. Do not change
the session's plain `error_message` contract.
### 3. Preserve existing classification behavior
Keep quota classification and `error_output` URL-free. A provider diagnostic may
carry a remediation URL even when it is not quota-classified, so the generic
recoverable card can still show the link. Tests must prove that URL-bearing
metadata never appears for invalid or untrusted inputs.
## Frontend work
### 4. Render one shared, mobile-safe link affordance
Add defense-in-depth URL validation at the browser boundary and a small shared
localized link component. Use it from:
- Kanban `ActionMessageDetails` and the persistent last-agent-error notice;
- Office `RunErrorEntry`, including the live `session.state_changed` metadata
projection.
The link is separate from the collapsed technical text, opens in a new tab with
`rel="noopener noreferrer"`, and has a minimum 44px touch target on phones.
The existing recovery buttons, error copy, and chat scroll ownership remain
unchanged. New labels go through the existing `task`/`chat` translation files
and their pseudo-locale counterparts.
## Tests and verification
### Backend focused tests
- Parser accepts the observed OpenCode workspace route, stores it only in
`remediation_url`, and keeps the URL/workspace ID out of `message` and
sanitized stderr.
- Parser rejects wrong hosts, schemes, paths, query/fragment components,
malformed IDs, overlong values, and unrelated URLs.
- ACP structured error data with `action_url` follows the same allowlist; absent
or malformed data keeps the current generic error path.
- Lifecycle and orchestrator tests prove the field survives only through the
winning error event, is persisted in `LastAgentError`/recovery metadata, and
is absent for invalid input.
### Frontend unit tests
- `ActionMessage` renders a validated link for generic and quota recovery while
preserving collapsed technical details and existing actions.
- `readLastAgentError` and the persistent notice retain/render the safe field.
- Office session mapping and `buildRunErrorsFromSessions` preserve the field;
`RunErrorEntry` renders the same link and remains safe for invalid metadata.
- English and pseudo-locale checks pass; no hardcoded user-facing copy is added.
### E2E tests
Add seeded desktop and `mobile-chrome` scenarios that inject only the safe
`remediation_url` metadata. Verify the link destination, no URL in the
sanitized message, keyboard/touch reachability, 44px controls, and no
horizontal overflow. Add a no-link case for the current short ACP failure.
These tests must not invoke a real provider, exhaust quota, or read an
OpenCode log.
Targeted commands:
```text
cd apps/backend && go test ./internal/agentctl/server/adapter/transport/acp ./internal/agentctl/server/api ./internal/agent/runtime/lifecycle ./internal/agent/runtime/routingerr ./internal/orchestrator -run 'Test(OpenCode|ProviderError|RecoverableFailure|RecoveryStatus)' -count=1
cd apps && pnpm --filter @kandev/web test -- --run components/task/chat/messages/action-message.test.tsx lib/session-last-agent-error.test.ts components/task/simple/chat-entries.test.ts lib/remediation-url.test.ts
cd apps/web && pnpm run typecheck && pnpm run i18n:check && pnpm run i18n:ratchet
cd apps/web && pnpm e2e:run --no-build tests/session/provider-remediation-link.spec.ts
cd apps/web && pnpm e2e:run --no-build --project mobile-chrome tests/session/mobile-provider-remediation-link.spec.ts
cd apps/web && pnpm e2e:run --no-build tests/office/provider-remediation-link.spec.ts
```
## Likely files
Backend:
- `apps/backend/internal/agentctl/types/streams/provider_error.go`
- `apps/backend/internal/agentctl/server/adapter/transport/acp/opencode_stderr.go`
- `apps/backend/internal/agentctl/server/adapter/transport/acp/opencode_stderr_test.go`
- `apps/backend/internal/agentctl/server/adapter/transport/acp/adapter_prompt.go`
- `apps/backend/internal/agentctl/server/api/agent.go`
- `apps/backend/internal/agentctl/server/api/agent_test.go`
- `apps/backend/internal/task/models/models.go`
- `apps/backend/internal/orchestrator/event_handlers_agent.go`
- `apps/backend/internal/orchestrator/event_handlers_test.go`
- `apps/backend/internal/orchestrator/recovery_actions_test.go`
Frontend:
- `apps/web/lib/session-last-agent-error.ts`
- `apps/web/components/task/chat/messages/action-message.tsx`
- `apps/web/components/task/chat/messages/action-message.test.tsx`
- `apps/web/components/task/chat/message-list-shared.tsx`
- `apps/web/app/office/tasks/[id]/page.tsx`
- `apps/web/app/office/tasks/[id]/types.ts`
- `apps/web/components/task/simple/chat-entries.ts`
- `apps/web/components/task/simple/components/run-error-entry.tsx`
- `apps/web/src/locales/en/task.json`
- `apps/web/src/locales/en/chat.json`
- matching pseudo-locale files and focused tests
## Sequencing and handoff
The work is sequential because the frontend consumes the persisted metadata
contract. There is no safe parallel implementation wave:
1. Normalize and test the transport contract.
2. Persist/publish it through the existing lifecycle.
3. Render both recovery surfaces and live Office updates.
4. Run focused unit, backend, i18n, desktop, and mobile verification.
The external OpenCode emission change is a prerequisite for live URL coverage
of the reported 1.18.5 error, but not for Kandev's parser, persistence, or
seeded UI tests. If upstream does not emit the field, Kandev must retain the
short-error fallback and report that limitation rather than exposing private
logs.
## Verification Results
Implemented 2026-08-07.
- Backend allowlist validator `NormalizeOpenCodeActionURL` in
`apps/backend/internal/agentctl/server/adapter/transport/acp/opencode_remediation.go`,
shared by the stderr parser (inline URL or `action_url` field) and the
structured ACP `RequestError` projection. `ProviderError.RemediationURL`,
`LastAgentError.RemediationURL`, recovery-message `remediation_url`, and the
`task_session.error_changed` event all carry the field; `session.state_changed`
carries it via the persisted `session_metadata`.
- Frontend: `lib/remediation-url.ts` browser-edge validation, shared
`components/task/remediation-link.tsx` (`target="_blank"`, `rel="noopener noreferrer"`,
min-h-11 touch target), wired into `ActionMessageDetails` (generic + quota
cards), the persistent `LastAgentErrorNotice`, and Office `RunErrorEntry`
(initial API data + live `session.state_changed` metadata merge).
- Generic logs: the `session.state_changed` metadata debug echo redacts
`remediation_url` (`redactRemediationURL` in `task_notifications.go`).
- Verification runs (all green):
- `cd apps/backend && go test ./internal/agentctl/server/adapter/transport/acp ./internal/agentctl/server/api ./internal/agent/runtime/lifecycle ./internal/agent/runtime/routingerr ./internal/orchestrator -run 'Test(OpenCode|ProviderError|RecoverableFailure|RecoveryStatus)' -count=1` — passed.
- Full touched-package backend suites (acp, streams, task/models, orchestrator,
lifecycle, agentctl api/process, gateway/websocket) — passed.
- `golangci-lint run ./... --new-from-rev=<base> --timeout=5m` — no issues.
- `pnpm --filter @kandev/web test -- --run lib/remediation-url.test.ts lib/session-last-agent-error.test.ts components/task/chat/messages/action-message.test.tsx components/task/chat/message-list-shared.test.tsx components/task/simple/chat-entries.test.ts` — 106 passed.
- Full web unit suite — 1236 files / 9669 tests passed.
- `pnpm run typecheck`, `pnpm run i18n:check`, `pnpm run i18n:ratchet` — all clean (pseudo locale regenerated).
- Desktop E2E `tests/session/provider-remediation-link.spec.ts` — 3 passed (link render + keyboard focus, short-error fallback, last-agent-error notice).
- Mobile E2E `tests/session/mobile-provider-remediation-link.spec.ts` (mobile-chrome) — 1 passed (44px target, focus, overflow).
- Office E2E `tests/office/provider-remediation-link.spec.ts` — 2 passed (link on RunErrorEntry, no-link for invalid/absent metadata).
External dependency stands: OpenCode must emit `action_url` (ACP structured
error data or structured stderr) for the live 1.18.5-style failure to show the
TUI workspace URL; Kandev keeps the short-error fallback until then.
@@ -0,0 +1,70 @@
---
id: "01-normalize-action-url"
title: "Normalize OpenCode action URLs"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/agent-stall-recovery/spec.md"
---
# Task 01: Normalize OpenCode Action URLs
## Acceptance
- `ProviderError` has an optional `remediation_url` field with the existing
bounded/sanitized contract.
- The OpenCode parser extracts only
`https://opencode.ai/workspace/<safe-workspace-id>/go`; it removes the URL and
identifiers from `message` and never returns arbitrary URLs.
- Future structured ACP error data may supply `action_url`, but only the same
validator accepts it; missing, malformed, wrong-host, query-bearing, and
oversized values produce no URL.
- Existing correlation, prompt races, stderr projection, and generic error
behavior remain unchanged.
## Verification
```text
cd apps/backend && go test ./internal/agentctl/server/adapter/transport/acp ./internal/agentctl/server/api -run 'Test(OpenCode|ProviderError|Prompt.*Error|HandleWSPrompt)' -count=1
```
Use TDD with the observed URL as a fixture and table-driven rejection cases.
Include a structured ACP error fixture without requiring a live OpenCode
process. Assert no raw URL or workspace identifier appears in the sanitized
message or generic stderr projection.
## Files likely touched
- `apps/backend/internal/agentctl/types/streams/provider_error.go`
- `apps/backend/internal/agentctl/server/adapter/transport/acp/opencode_stderr.go`
- `apps/backend/internal/agentctl/server/adapter/transport/acp/opencode_stderr_test.go`
- `apps/backend/internal/agentctl/server/adapter/transport/acp/adapter_prompt.go`
- `apps/backend/internal/agentctl/server/api/agent.go`
- `apps/backend/internal/agentctl/server/api/agent_test.go`
## Dependencies and risks
None inside Kandev. The live current-version path still depends on OpenCode
emitting `action_url` through ACP or structured stderr. Do not read its private
log directory or widen the parser to arbitrary prose.
## Results
Implemented 2026-08-07.
- `streams.ProviderError.RemediationURL` added (`remediation_url,omitempty`);
new `ProviderErrorSourceOpenCodeACP` source for the structured ACP path.
- Shared allowlist `NormalizeOpenCodeActionURL` accepts only
`https://opencode.ai/workspace/<safe-workspace-id>/go` (exact host, HTTPS,
no userinfo/query/fragment/port/percent-encoding, bounded identifier and
URL). Stderr parser captures it from a dedicated `action_url` field or from
the provider error text before sanitization; `ProviderErrorFromError`
projects a future ACP `RequestError` carrying structured `action_url`, and
the message runs through the existing sanitizer so no URL or workspace
identifier leaks.
- Table-driven tests cover the observed fixture URL, the explicit field,
wrong hosts/schemes/paths, query/fragment/userinfo/port, traversal IDs,
oversized values, malformed ACP data, and wrapped generic errors.
Verification: `go test ./internal/agentctl/server/adapter/transport/acp ./internal/agentctl/server/api -run 'Test(OpenCode|ProviderError|Prompt.*Error|HandleWSPrompt)' -count=1` — passed (plus the full acp package suite, 787 tests).
@@ -0,0 +1,64 @@
---
id: "02-persist-recovery-link"
title: "Persist recovery links"
status: done
wave: 2
depends_on: ["01-normalize-action-url"]
plan: "plan.md"
spec: "../../specs/agent-stall-recovery/spec.md"
---
# Task 02: Persist Recovery Links
## Acceptance
- `LastAgentError` persists a validated `remediation_url` without changing the
plain `TaskSession.error_message` contract.
- Generic recoverable errors and quota-specialized errors both carry the link
when the normalized provider diagnostic has one.
- The existing lifecycle generation guards still select the winning provider
error; stale or invalid diagnostics cannot overwrite the persisted link.
- `session.state_changed` includes the structured metadata so connected Office
clients receive the same value as a reload.
## Verification
```text
cd apps/backend && go test ./internal/task/models ./internal/orchestrator ./internal/agent/runtime/lifecycle -run 'Test(LastAgentError|HandleRecoverableFailure|CreateRecoveryStatusMessage|.*ProviderError)' -count=1
```
Assert the URL is present only in the dedicated field, while `message`,
`error_output`, `error_message`, and generic logs remain URL-free.
## Files likely touched
- `apps/backend/internal/task/models/models.go`
- `apps/backend/internal/orchestrator/event_handlers_agent.go`
- `apps/backend/internal/orchestrator/event_handlers_test.go`
- `apps/backend/internal/orchestrator/recovery_actions_test.go`
- relevant lifecycle/session-state event tests
## Dependencies and risks
Task 01. Reuse the existing `ProviderError` propagation; do not create a second
diagnostic event or a parallel session state. Preserve local dismissal and
last-error stamping behavior.
## Results
Implemented 2026-08-07.
- `models.LastAgentError.RemediationURL` persisted under
`SessionMetaKeyLastAgentError`; plain `TaskSession.error_message` contract
unchanged and URL-free.
- `providerRemediationURL` copies only the adapter-validated field from the
normalized `ProviderError`; `createRecoveryStatusMessage` carries
`remediation_url` in the action-message metadata independently of quota
classification (ACP-sourced diagnostics are not quota-classified but still
show the link). The `task_session.error_changed` event carries it, and
`session.state_changed` includes it via the persisted `session_metadata`.
- Tests: quota + generic cards carry the URL; nil/invalid diagnostics produce
no metadata key; `handleRecoverableFailure` persists the URL and keeps
`error_message` URL-free; absent diagnostics omit the field.
Verification: `go test ./internal/task/models ./internal/orchestrator ./internal/agent/runtime/lifecycle -run 'Test(LastAgentError|HandleRecoverableFailure|CreateRecoveryStatusMessage|.*ProviderError)' -count=1` — passed; full orchestrator (3094 tests) and lifecycle (1962 tests) suites passed.
@@ -0,0 +1,76 @@
---
id: "03-render-recovery-link"
title: "Render recovery links"
status: done
wave: 3
depends_on: ["02-persist-recovery-link"]
plan: "plan.md"
spec: "../../specs/agent-stall-recovery/spec.md"
---
# Task 03: Render Recovery Links
## Acceptance
- Kanban action messages and persistent last-agent-error notices render a
localized external link when `remediation_url` is present.
- Office failed-session entries render the same link from initial API data and
live `session.state_changed` metadata.
- Browser-side defense-in-depth validation rejects invalid URLs before creating
an `href`; valid links use `target="_blank"` and
`rel="noopener noreferrer"`.
- The existing sanitized message, collapsed technical details, recovery
buttons, keyboard navigation, and mobile chat scroll owner remain intact.
## Verification
```text
cd apps && pnpm --filter @kandev/web test -- --run components/task/chat/messages/action-message.test.tsx lib/session-last-agent-error.test.ts components/task/simple/chat-entries.test.ts lib/remediation-url.test.ts
cd apps/web && pnpm run typecheck && pnpm run i18n:check && pnpm run i18n:ratchet
```
Add focused tests for generic/quota cards, dismissed notices, Office mapping,
invalid metadata, translated labels, and the minimum 44px phone affordance.
## Files likely touched
- `apps/web/lib/session-last-agent-error.ts`
- `apps/web/components/task/chat/messages/action-message.tsx`
- `apps/web/components/task/chat/messages/action-message.test.tsx`
- `apps/web/components/task/chat/message-list-shared.tsx`
- `apps/web/app/office/tasks/[id]/page.tsx`
- `apps/web/app/office/tasks/[id]/types.ts`
- `apps/web/components/task/simple/chat-entries.ts`
- `apps/web/components/task/simple/components/run-error-entry.tsx`
- focused Office/chat tests
- `apps/web/src/locales/en/task.json`
- `apps/web/src/locales/en/chat.json`
- matching pseudo-locale files
## Dependencies and risks
Task 02. The external URL is a user-visible security boundary; keep validation
at the backend and browser edges. Do not render the raw diagnostic message as
HTML or use translated text for control flow.
## Results
Implemented 2026-08-07.
- `lib/remediation-url.ts` mirrors the backend allowlist at the browser edge
(host, scheme, path shape, bounded identifier, no port/query/fragment/
userinfo); `components/task/remediation-link.tsx` renders the localized
`chat:openProviderPage` link with `target="_blank"`, `rel="noopener noreferrer"`
and a 44px phone touch target, and returns null for invalid input.
- Wired into `ActionMessageDetails` (generic + quota recovery cards), the
persistent `LastAgentErrorNotice` (`readLastAgentError` reads
`remediation_url`/`remediationUrl`), and Office `RunErrorEntry` via
`buildRunErrorsFromSessions`; the office page maps `metadata` from the API
and merges live `session.state_changed` metadata.
- Unit tests: validator table, action-message link cases (quota/generic/
invalid), notice link cases, session-last-agent-error parsing, and
`buildRunErrorsFromSessions` preservation.
Verification: targeted vitest run (106 tests) and the full web unit suite
(1236 files / 9669 tests) passed; `typecheck`, `i18n:check`, `i18n:ratchet`
clean (en/pt-pt/zh-cn catalogs + regenerated pseudo).
@@ -0,0 +1,72 @@
---
id: "04-verify-actionable-error-links"
title: "Verify actionable error links"
status: done
wave: 4
depends_on: ["02-persist-recovery-link", "03-render-recovery-link"]
plan: "plan.md"
spec: "../../specs/agent-stall-recovery/spec.md"
---
# Task 04: Verify Actionable Error Links
## Acceptance
- Backend tests prove the observed OpenCode route is preserved only as
`remediation_url`, and all rejected URL classes are omitted.
- Seeded desktop E2E proves the recovery link, short sanitized message, and
existing recovery actions; the no-link short-ACP fallback is covered.
- Seeded `mobile-chrome` E2E proves keyboard/touch reachability, 44px controls,
bounded details, and no horizontal overflow.
- Tests never invoke a real quota failure, read a developer's OpenCode logs, or
add a production-only test hook.
## Verification
```text
cd apps/backend && go test ./internal/agentctl/server/adapter/transport/acp ./internal/agentctl/server/api ./internal/agent/runtime/lifecycle ./internal/orchestrator -run 'Test(OpenCode|ProviderError|RecoverableFailure|RecoveryStatus)' -count=1
cd apps/web && pnpm e2e:run --no-build tests/session/provider-remediation-link.spec.ts
cd apps/web && pnpm e2e:run --no-build --project mobile-chrome tests/session/mobile-provider-remediation-link.spec.ts
cd apps/web && pnpm e2e:run --no-build tests/office/provider-remediation-link.spec.ts
```
Inspect the phone viewport in addition to assertions and record exact results
in the plan's Verification Results section.
## Files likely touched
- `apps/web/e2e/tests/session/provider-remediation-link.spec.ts`
- `apps/web/e2e/tests/session/mobile-provider-remediation-link.spec.ts`
- existing E2E page/fixture helpers only if a reusable seeded metadata path is
required
- backend lifecycle/orchestrator regression tests
## Dependencies and risks
Tasks 02 and 03. Seed the safe contract with a non-sensitive test workspace
identifier; assert no invalid URL reaches the DOM. A seeded UI test proves
rendering, not OpenCode upstream emission, so preserve the explicit external
dependency in the final report.
## Results
Implemented 2026-08-07.
- Desktop `tests/session/provider-remediation-link.spec.ts` (3 tests): link
href/target/rel + keyboard focus, sanitized message and technical details
stay URL/identifier-free, existing recovery actions intact, no horizontal
overflow; short-error fallback renders no link; persistent
last-agent-error notice renders the link.
- Mobile `tests/session/mobile-provider-remediation-link.spec.ts`
(mobile-chrome): 44px touch target, focus reachability, URL-free details,
in-viewport actions, no horizontal overflow.
- Office `tests/office/provider-remediation-link.spec.ts` (2 tests):
RunErrorEntry renders the link from seeded `last_agent_error` metadata;
invalid or absent metadata renders no link.
- All seeds inject only safe `remediation_url` metadata; no real provider,
quota exhaustion, or OpenCode log access.
Verification: `cd apps/backend && go test ... -run 'Test(OpenCode|ProviderError|RecoverableFailure|RecoveryStatus)' -count=1` — passed; desktop + mobile-chrome + office E2E — all passed (run via `pnpm e2e:run --no-build`).
External dependency preserved: OpenCode must emit `action_url` for the live
1.18.5 failure to show its TUI URL; Kandev shows the short error until then.