Skip to content

fix(cli): show session-target remedies for attach failures - #198345

Closed
SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/attach-session-target-remedies-307
Closed

SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/attach-session-target-remedies-307

Conversation

@SunnyShu0925

Copy link
Copy Markdown
Contributor

What Problem This Solves

An operator who points openclaw attach at a short session reference gets no actionable output. openclaw attach "https://gw.example/dashboard/main/movies-a1166b81" --url wss://other.example prints only [openclaw] The CLI command failed. plus For help, run openclaw doctor. — the remedy the resolver already composed ("pass one target: use either the session URL or --url, not both") never reaches the terminal, and the doctor hint sends the operator to the wrong next step. The same collapse hides the formatted ambiguity table for a colliding prefix, the No session found hint, and the gateway-unreachable / stored-device-auth recovery lines.

  • Problem: resolveSessionTarget in src/cli/session-target.ts raises its operator remedies as plain Errors. attach awaits it directly, so they bubble to the root CLI renderer, which prints the message only for expected CLI errors and a narrow show-reason whitelist that does not include attach.
  • Solution: raise those remedy sites through the canonical throwExpectedCliError / ExpectedCliError owner in src/cli/expected-cli-error.ts, message text verbatim.
  • What changed: src/cli/session-target.ts (+16/−9) — six returned remedy errors and three thrown remedy errors now carry humanOutput. Regression assertions folded into the existing cases in src/cli/session-ref.test.ts and src/cli/session-target.test.ts (net −4 test lines, no new test file).
  • What did NOT change: every message string, the exit code (1), the JSON failure envelope (formatCliJsonFailure already kept the message), openclaw tui output, and the internal-invariant error at session-target.ts:199 ("Gateway returned a session without a consistent agent identity.") which stays a plain Error because it names a branch that should not happen.

Why This Change Was Made

The session-target owner already writes these remedies for one purpose — telling the operator what to do next — and one of its two consumers honours that contract while the other discards it. src/cli/tui-cli.ts:96-105 catches around the same resolveSessionTarget call and prints the formatted message; src/cli/attach-cli.ts:103 awaits it unwrapped, so the identical remedy is visible under tui and invisible under attach for the same input. That asymmetry is the strongest signal this is a missed site rather than a deliberate choice, and it is the same reasoning accepted in the merged dns CLI fix #192127 and the hooks CLI fix #190366, which adopted exactly this per-site shape.

Alternatives considered and rejected: adding attach to the renderer's show-reason whitelist would print raw reasons for every attach failure including unforeseen internal errors, a larger blast radius than one guard needs. Putting the conversion in the attach action instead would leave the second consumer (and any future one) re-deriving the contract that the owner already owns. Constructing ExpectedCliError inline at each of the six shapeTargetError return sites would triplicate the long remedy templates in a three-field constructor call, so those sites share one local factory over the owner class; the three throw sites call throwExpectedCliError directly.

User Impact

Operators running openclaw attach with an ambiguous short reference, a mistyped reference, a conflicting URL and --url, or an unreachable gateway now see the remedy — including the already-formatted candidate table and the sessions list hint — instead of a generic failure and a doctor pointer. Successful and JSON-mode invocations are untouched, and every affected path still exits 1.

Evidence

Case (shipped entry, same isolated profile) Before (origin/main 5bdadab2c73, owner file reverted) After (this head 14a4ec8219f)
attach <session URL> --url wss://other.example generic title + doctor hint, remedy hidden (exit 1) pass one target: use either the session URL or --url, not both (exit 1)
attach <ref> --url to a port nothing listens on generic title + doctor hint (exit 1) transport line + Could not reach gateway wss://127.0.0.1:18307. Check whether the gateway is down and whether its tailnet or SSH tunnel is reachable. (exit 1)
tui with the same two inputs (control) remedy printed byte-identical remedy printed — the fix changes nothing on the consumer that already worked
owner unit suite (38 cases) 9 failed / 29 passed 38 passed

Live runs use the shipped source entry (node --import ./scripts/tsx.mjs src/entry.ts …) with OPENCLAW_STATE_DIR and OPENCLAW_CONFIG_PATH on a scratch directory holding a minimal config, so no real state or config is touched; the unreachable cells hit a genuine TCP refusal on loopback port 18307 (nothing listening) and travel the real callGateway transport, with no mocks. All eight runs exit 1, and the two tui control outputs diff byte-identical between base and head.

After (this head), conflict cell:

$ node --import ./scripts/tsx.mjs src/entry.ts attach "https://gw.example/dashboard/main/movies-a1166b81" --url wss://other.example
pass one target: use either the session URL or --url, not both
(exit 1)

Before (same command, origin/main version of the owner file):

$ node --import ./scripts/tsx.mjs src/entry.ts attach "https://gw.example/dashboard/main/movies-a1166b81" --url wss://other.example
[openclaw] The CLI command failed.
[openclaw] For help, run `openclaw doctor`.
(exit 1)

After, unreachable cell (real ECONNREFUSED, remedy plus the transport detail the operator needs):

$ node --import ./scripts/tsx.mjs src/entry.ts attach "https://127.0.0.1:18307/dashboard/main/movies-a1166b81" --token dummy-token
Gateway not reachable at wss://127.0.0.1:18307 (ECONNREFUSED).
Start it with `openclaw gateway run` or check `openclaw gateway status`.
Gateway target: wss://127.0.0.1:18307
Source: cli --url
Config: /tmp/oc307/openclaw.json
Could not reach gateway wss://127.0.0.1:18307. Check whether the gateway is down and whether its tailnet or SSH tunnel is reachable.
(exit 1)

The ambiguity table is the remedy most worth keeping visible, and it is a multi-line block, so the renderer branch matters: expected CLI errors print humanOutput verbatim including newlines. It is pinned at the owner boundary instead — src/cli/session-ref.test.ts "prints bounded ambiguity candidates without listing or describing" asserts the candidate rows and the Pass a longer reference line arrive inside an ExpectedCliError.

Unit invariant, same tests with the owner file swapped (mutation = full production revert, restored by recorded sha256): on base the plain errors carry message but no humanOutput, so the class pins fail while all 29 message-text assertions pass on both sides — proof the messages are byte-identical and only the envelope changed.

FAIL src/cli/session-ref.test.ts > session target resolution > rejects a second explicit URL
AssertionError: expected Error: pass one target: use either the se… to be an instance of ExpectedCliError

FAIL src/cli/session-target.test.ts > session target connection errors > surfaces identity-proxy remediation without tailnet or SSH tunnel advice
AssertionError: expected Error: gateway rejected websocket upgrade… to be an instance of ExpectedCliError

 Test Files  2 failed (2)      Tests  9 failed | 29 passed (38)   # base
      Tests  38 passed (38)                                        # this head

Consumers of the owner file were run, not reasoned about: every importer of src/cli/session-target.js (attach-cli.action.test.ts, sessions-import.test.ts, the doctor config preflight process test, run-main.bare-root.test.ts, run-main.command-dispatch.test.ts) — 132 tests green on this head. attach-cli.action.test.ts already asserted error instanceof Error plus verbatim message on the ambiguity case, and ExpectedCliError extends Error, so that existing contract stayed green without edit.

Open PR collision check (submission-day sweep, 2026-11-13): scanned the changed-file lists of the 60 most recent open PRs for src/cli/session-target.ts, session-ref.ts, attach-cli.ts, expected-cli-error.ts and the two test files — zero hits. Keyword searches (session reference is ambiguous, attach session target, session-target, ExpectedCliError) left #175714 as the only open PR touching src/cli/attach-cli.ts; it changes grant-expiry range validation there and shares no hunk with this owner-side change, and #190362's session-target test lives under src/gateway/, not here. Gate 2.5: nothing in the last 14 days contradicts per-site ExpectedCliError conversion — #192127 and #190366 established it, #196710 (merged three days ago) uses the same shape, and #197508 only threads the signal through. The defect is still present on current origin/main.

What was not tested: local lint and typecheck lanes. The repo wrappers reject this worktree's symlinked install ("Declaration input escapes checkout"), consistent with the sibling CLI PRs, so lint and types are left to CI on this head; the change is confined to one module and the error owner's public constructor. openclaw attach was not proven end to end against a live gateway with two genuinely colliding session prefixes — that path needs a running gateway and a real prefix collision, so the ambiguity cell is pinned at the owner boundary rather than through the shipped entry.

resolveSessionTarget threw plain Errors, so the root CLI renderer hid
attach remedies (ambiguity table, not-found hints, URL conflict,
connection recovery) behind the generic doctor message while tui showed
them. Throw ExpectedCliError at the remedy sites; messages, exit codes,
and JSON output stay unchanged.
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added cli CLI command changes size: S labels Nov 13, 2026
@SunnyShu0925
SunnyShu0925 marked this pull request as ready for review November 13, 2026 15:49
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR makes attach failures display the session resolver’s existing recovery instructions.

Example: Run openclaw attach "https://gw.example/dashboard/main/movies-a1166b81" --url wss://other.example.

  • Before: The CLI prints a generic command failure and suggests running Doctor.
  • After: The CLI prints: pass one target: use either the session URL or --url, not both.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, focused repair with shipped-entry proof and no identified code defect; broad validation remains incomplete.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Contributor terminal output exercises src/entry.ts attach under isolated state, showing the URL-conflict remedy and real connection-refusal recovery after the owner change; TUI controls remain unchanged, and existing resolver tests cover the additional remedy branches.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Attach replaces specific session-selection and connection recovery instructions with a generic failure and an unhelpful Doctor hint.
Reason: Displaying the existing documented remedies restores intended behavior without changing configuration, defaults, authority, or successful requests.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR repairs a current, documented CLI error-reporting defect with a focused change and convincing terminal evidence; no actionable code defect was found.

Priority: P2
Reviewed head: 14a4ec8219fa9b60d8f57b3677f1ef1ebf34bab6

Before merge

None.

Findings

None.

Agent review details

How this fits together

The shared CLI session-target resolver accepts session references and Gateway options, calls Gateway resolution when needed, and returns a resolved session or an error consumed by attach, TUI, and session imports.

flowchart TD
  A[CLI target and options] --> B[Session target resolver]
  B --> C[Gateway transport]
  C --> B
  B --> D[Resolved session]
  B --> E[Expected CLI error]
  E --> F[Root terminal renderer]
Loading

Technical review

Best possible solution:

Keep the focused owner-side ExpectedCliError conversion and land it once the required CI gate passes.

Do we have a high-confidence way to reproduce the issue?

Yes: the current-main resolver, attach caller, and root renderer establish the failure path, and the contributor supplies matching before/after terminal output; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch restores the documented contract at the existing error producer, preserves messages and unexpected-error handling, and avoids broadening the root renderer’s whitelist.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1904c27817b7.

Provenance checked

  • Session-target recovery messages keeps the original intent (055a2dc: The original CLI continuation feature deliberately supplied origin-aware remedies for missing sessions, short-link version skew, device authentication, and unreachable Gateways.)
  • Identity-aware proxy recovery keeps the original intent (d92ebba: Proxy rejection needed specific edge-authentication recovery rather than misleading tailnet or SSH advice; this PR preserves that message and classification.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +7, Tests -4. Total +3 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 16 9 +7
Tests 2 20 24 -4
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 36 33 +3

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: An advanced CLI workflow hides actionable recovery instructions, with limited impact and no change to successful execution.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete the required test, lint, and typecheck CI for the reviewed head.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 13, 2026, 11:06 AM ET / 16:06 UTC.

@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the work here. We're closing this one along with the other open per-command --json error fixes. These PRs all fix the same root cause one command at a time: runCommandWithRuntime rethrows plain errors in JSON mode, so the root renderer prints the generic failure instead of the existing message. We're fixing that once in the shared wrapper instead, which covers this command too. Please don't open more per-command variants of this fix; if you find a case the shared fix doesn't cover, open an issue with a reproduction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor cli CLI command changes P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants