Skip to content

feat(tui): opt-in persistence and agent visibility for !/!! local shell commands - #103648

Closed
fluffyxenia wants to merge 20 commits into
openclaw:mainfrom
fluffyxenia:tui-bash-persist
Closed

fluffyxenia wants to merge 20 commits into
openclaw:mainfrom
fluffyxenia:tui-bash-persist

Conversation

@fluffyxenia

@fluffyxenia fluffyxenia commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

TUI-local !-prefixed shell commands render a live local echo but are never persisted: closing the TUI loses them, session resume never shows them, and the agent cannot see what the operator ran or what it printed — even though the BashExecutionMessage/excludeFromContext data model and the LLM-context filtering for it already exist in packages/agent-core (previously unused by any production code path).

Split out of #103147 per review feedback there; that PR now carries only the rendering fixes.

Why This Change Was Made

Operators often run a ! command specifically to show the agent something (Claude Code's own ! behaves this way). But local shell output can also be sensitive, so persistence and model visibility must be a deliberate choice, not a silent default:

  • The session consent prompt now offers No / Yes, local only / Yes, and share with the agent. Local only is the shipped, pre-existing behavior and stays the default expectation — nothing is saved or shared unless the operator explicitly picks the share option.
  • With sharing enabled, !cmd persists agent-visible (the agent sees it on its next turn) and !!cmd persists history-only (excludeFromContext: true, never reaches the model). Both semantics are stated in the consent prompt itself.

Implementation: an additive, hidden (advertise: false, operator.admin) chat.injectBashExecution gateway RPC modeled on chat.inject, implemented in both TUI backends (embedded calls the shared core directly in-process; gateway goes over the RPC). No live broadcast: the originating client already rendered its own local echo. History replay renders bashExecution entries on session resume.

Two defects found during review/testing are fixed here as well:

  • A failed spawn emits both error and close; a shared settled-guard ensures one command persists at most once.
  • Rows injected while an agent run is in flight now carry appendMode: "side" (like chat.inject's assistant bookkeeping rows) so they do not steal the run's active leaf. Without this, persisting a ! result mid-run tripped the embedded runner's session-file fence ("session file changed while embedded prompt lock was released") and killed the run. The run adopts side entries into the chain on its next append, so the agent still sees them next turn.

User Impact

  • Default behavior is unchanged: ! commands stay local-only unless the operator opts into sharing at the consent prompt.
  • With sharing enabled, ! output survives session resume and is visible to the agent next turn; !! output survives resume but never reaches the model.
  • Running a shared ! command while the agent is mid-turn no longer kills the run with a session takeover error.

Evidence

  • src/tui/tui-local-shell.test.ts — 12 tests: consent options (local-only default persists nothing; share option persists), ! vs !! excludeFromContext round-trip, no-scope/no-backend skips, persistence-failure surfacing, once-only persistence on error-then-close, plus the pre-existing output-cap/UTF-16/cwd guards.
  • src/gateway/server-methods/chat.inject-bash-execution.test.ts — parentId chain preserved, excludeFromContext round-trip, mid-run side-append regression test (fence takeover repro), idle active-append, unresolved-identity failure.
  • src/tui/gateway-chat.test.ts, src/tui/embedded-backend.test.ts — both backend implementations (RPC params/result shapes; embedded in-process delegation and failure surfacing).
  • src/gateway/server-methods-list.test.ts — hidden method not advertised, handler dispatchable.
  • Full src/tui suite green locally; protocol schema regenerated (pnpm protocol:gen / protocol:gen:swift — Swift models committed).
  • Live gateway-backed evidence (real gateway, real model, no mocks): consent gate, !/!! visibility split, restart replay, same-key cross-agent isolation, and storage-level excludeFromContext verification — feat(tui): opt-in persistence and agent visibility for !/!! local shell commands #103648 (comment) (recorded on head 7a293b5c35; later heads carry the LOC-ratchet modularization, proof-artifact cleanup, and consent-wording update — no feature-path behavior change).
  • Redacted PTY evidence of live ! vs !! behavior: to follow in a comment.

🤖 Generated with Claude Code

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime size: L labels Jul 10, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jul 10, 2026
@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 1, 2026, 1:41 PM ET / 17:41 UTC.

ClawSweeper review

What this changes

This PR adds consent-gated persistence for TUI-local shell output: ! is saved and sent to the next model turn, while !! is saved only in session history.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 12 items remain

Keep this PR open for maintainer product direction rather than cleanup. Current main still runs ! commands only as local TUI output, so the central persistence/context capability remains unique; however, the unchanged July 14 branch lacks retry-safe transcript identity, intentionally rejects the first shared command in a fresh session, is dirty against current main, and has no current-head real-behavior proof.

Priority: P2
Reviewed head: 0f45550ee1bfa0ff7c0630442bab6723ad9e9a72
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The PR has substantial tests and earlier live evidence, but two transcript correctness gaps, a dirty base, and no current-head proof keep it below merge-ready quality.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: Earlier live Gateway/model logs are useful, but they were recorded on head 7a293b5c35; post a redacted terminal capture, log, or live output from the rebased current head showing consent, ! visibility, !! exclusion, resume replay, and fresh-session behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Earlier live Gateway/model logs are useful, but they were recorded on head 7a293b5c35; post a redacted terminal capture, log, or live output from the rebased current head showing consent, ! visibility, !! exclusion, resume replay, and fresh-session behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 7 items Current-main behavior remains local-only: The current TUI local-shell runner renders command output and exits to the chat log, but has no session scope, transcript injection dependency, or persistence call.
Existing model-context contract: Agent Core already converts a persisted bashExecution message into a user-context message unless excludeFromContext is true, so the requested behavior has a compatible transcript representation.
Missing retry identity in the proposed RPC: The new request schema accepts command-result fields but no stable injection identity. The SQLite writer performs idempotency lookup only when the message contains an idempotencyKey, so idempotencyLookup: "scan" cannot deduplicate a retried shell-result write.
Findings 2 actionable findings [P1] Add a stable idempotency key to shell injections
[P2] Persist the first shared command in a fresh session
Security None None.

How this fits together

The TUI launches operator-approved local shell commands and displays their output immediately. This PR would additionally send the result through a hidden Gateway RPC into the session transcript, which controls replay on resume and model context on later turns.

flowchart LR
  Operator[Operator enters ! or !! command] --> TUI[TUI local shell]
  TUI --> Consent[Per-session consent]
  Consent --> RPC[Hidden Gateway RPC]
  RPC --> Transcript[Session transcript]
  Transcript --> Replay[TUI resume replay]
  Transcript --> Context[Next model context]
Loading

Decision needed

Question Recommendation
Should consent-gated ! agent visibility and !! history-only persistence become a supported core TUI and hidden Gateway protocol contract? Sponsor a rebased core implementation: Accept the product direction, then require a current-main rebase, retry-safe identity, first-session support, and current-head proof before merge.

Why: The patch adds a new operator consent flow, persistent transcript behavior, model-visible local-machine output, and a Gateway method; implementation correctness cannot decide whether that product and security boundary belongs in core.

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Earlier live Gateway/model logs are useful, but they were recorded on head 7a293b5c35; post a redacted terminal capture, log, or live output from the rebased current head showing consent, ! visibility, !! exclusion, resume replay, and fresh-session behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Add a stable idempotency key to shell injections (P1) - The new RPC has no per-command identity, while the SQLite writer only deduplicates when the message carries idempotencyKey. A response lost after the write or a retried request therefore appends the same agent-visible command again; add a generated command ID to the request and persist it as the transcript idempotency key.
  • Persist the first shared command in a fresh session (P2) - Choosing “Yes, and share” before the first agent turn reaches this branch and reports that nothing was saved. That contradicts the consent flow’s promise for the initial shared command; current main already has a canonical injected-transcript path with createIfMissing, so use that owner path or otherwise create the durable transcript before appending.
  • Resolve merge risk (P1) - GitHub reports this branch as dirty, while current main has recent TUI and gateway transcript refactors; merging without a rebase risks losing or regressing current owner-boundary changes.
  • Resolve merge risk (P1) - The feature creates a new consent, persistence, and model-context contract for local shell output; maintainers need to explicitly sponsor the ! and !! semantics and the hidden operator.admin Gateway method.
  • Resolve merge risk (P1) - The live Gateway/model transcript was recorded on earlier head 7a293b5c35; no redacted after-fix terminal, log, or live-output proof establishes the behavior on current head 0f45550ee1bfa0ff7c0630442bab6723ad9e9a72.
  • Resolve merge risk (P1) - The Codex CLI launch-code extraction cannot receive the repository-required direct Codex-source verification while ../codex is absent.
  • Complete next step (P2) - A maintainer must first sponsor the new core consent and Gateway contract; the branch also needs a human-reviewed rebase and contributor-owned current-head proof.
  • Improve patch quality - Rebase onto current main and resolve the current TUI/gateway transcript ownership changes.
  • Improve patch quality - Add a stable idempotency key and make the first shared command persist successfully.
  • Improve patch quality - Post redacted current-head terminal or live Gateway evidence after the fixes.

Findings

  • [P1] Add a stable idempotency key to shell injections — packages/gateway-protocol/src/schema/logs-chat.ts:128-137
  • [P2] Persist the first shared command in a fresh session — src/gateway/server-methods/chat-inject-handlers.ts:75-86
Agent review details

Security

None.

PR surface

Source +578, Tests +847, Other +47. Total +1472 across 33 files.

View PR surface stats
Area Files Added Removed Net
Source 21 1076 498 +578
Tests 10 859 12 +847
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 47 0 +47
Total 33 1982 510 +1472

Review metrics

Metric Value Why it matters
Gateway contract 1 added hidden operator-admin RPC The new method changes the generated protocol and client contract across TUI, Android, and Swift surfaces, so it needs deliberate compatibility ownership.

Stored data model

Persistent data-model change detected: durable storage schema: packages/gateway-protocol/src/worker-protocol-json.ts, serialized state: src/tui/tui-pty-local.e2e.test.ts, serialized state: src/tui/tui-session-actions.test.ts, serialized state: src/tui/tui-session-actions.ts, serialized state: src/tui/tui-session-info-equality.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Rebase and complete the transcript contract (recommended)
    Rebase on current main, add an idempotency key and fresh-session persistence, then show current-head runtime proof before merge.
  2. Accept the deliberate first-session limitation
    Maintainers may retain the visible first-session failure only if they explicitly accept that the consent flow does not persist its first shared command.
  3. Pause pending product sponsorship
    Pause the PR if core ownership of persistent local-shell output and model visibility is not yet decided.

Technical review

Best possible solution:

After explicit sponsorship of the local-shell sharing contract, rebase onto current main, add a stable per-command injection identity, make the canonical transcript owner support the first shared command, and post redacted real behavior proof from the rebased head.

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

No high-confidence current-head live reproduction is available. Source inspection does establish two deterministic paths: retries lack an identity to deduplicate the write, and a fresh session returns an actionable persistence error instead of saving the first shared command.

Is this the best way to solve the issue?

No: the current patch is a plausible implementation, but it should use the canonical current-main transcript persistence shape, provide retry identity, and handle fresh-session creation before maintainers accept the product contract.

Full review comments:

  • [P1] Add a stable idempotency key to shell injections — packages/gateway-protocol/src/schema/logs-chat.ts:128-137
    The new RPC has no per-command identity, while the SQLite writer only deduplicates when the message carries idempotencyKey. A response lost after the write or a retried request therefore appends the same agent-visible command again; add a generated command ID to the request and persist it as the transcript idempotency key.
    Confidence: 0.96
  • [P2] Persist the first shared command in a fresh session — src/gateway/server-methods/chat-inject-handlers.ts:75-86
    Choosing “Yes, and share” before the first agent turn reaches this branch and reports that nothing was saved. That contradicts the consent flow’s promise for the initial shared command; current main already has a canonical injected-transcript path with createIfMissing, so use that owner path or otherwise create the durable transcript before appending.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.93

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 5118b0b915c0.

Labels

Label justifications:

  • P2: This is a bounded but user-visible TUI and session-history feature whose remaining defects affect persistence correctness rather than core availability.
  • merge-risk: 🚨 compatibility: The PR adds a Gateway protocol method and generated Android and Swift client models, while its branch is behind current protocol and gateway refactors.
  • merge-risk: 🚨 session-state: It writes a new transcript role and currently rejects the first shared command before a durable session exists.
  • merge-risk: 🚨 security-boundary: It changes when local machine command output is retained in session history and sent to a model, even though the proposed consent text makes that choice explicit.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Earlier live Gateway/model logs are useful, but they were recorded on head 7a293b5c35; post a redacted terminal capture, log, or live output from the rebased current head showing consent, ! visibility, !! exclusion, resume replay, and fresh-session behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current-main behavior remains local-only: The current TUI local-shell runner renders command output and exits to the chat log, but has no session scope, transcript injection dependency, or persistence call. (src/tui/tui-local-shell.ts:32, 5118b0b915c0)
  • Existing model-context contract: Agent Core already converts a persisted bashExecution message into a user-context message unless excludeFromContext is true, so the requested behavior has a compatible transcript representation. (packages/agent-core/src/harness/messages.ts:137, 5118b0b915c0)
  • Missing retry identity in the proposed RPC: The new request schema accepts command-result fields but no stable injection identity. The SQLite writer performs idempotency lookup only when the message contains an idempotencyKey, so idempotencyLookup: "scan" cannot deduplicate a retried shell-result write. (packages/gateway-protocol/src/schema/logs-chat.ts:128, 0f45550ee1bf)
  • Fresh-session path is deliberately unsupported: The proposed handler returns an error before appending when the selected session has no durable entry, even though the consent prompt presents sharing as available. Current main’s canonical injected-assistant persistence path supports createIfMissing for this class of transcript write. (src/gateway/server-methods/chat-inject-handlers.ts:75, 0f45550ee1bf)
  • Current-main refactor provenance: The TUI and gateway transcript paths were recently refactored on current main, so the branch must be rebased and re-reviewed against the current owner boundaries rather than merged from its July 14 snapshot. (src/gateway/server-methods/chat.ts:109, 1e34c2d073eb)
  • Prior findings remain at the exact current PR head: The current head is still 0f45550ee1bfa0ff7c0630442bab6723ad9e9a72, the same head named by the prior ClawSweeper review cycle; its idempotency and fresh-session concerns therefore remain unresolved rather than newly introduced. (src/gateway/server-methods/chat-transcript-inject.ts:195, 0f45550ee1bf)

Likely related people:

  • steipete: Current-main blame and recent history attribute the affected TUI local-shell, gateway chat injection, and Agent Core context paths to the same recent cross-surface refactor work. (role: recent TUI, gateway, and transcript-path contributor; confidence: high; commits: 1e34c2d073eb, cd4bd7c6c0ca; files: src/tui/tui-local-shell.ts, src/tui/tui.ts, src/gateway/server-methods/chat.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (17 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-14T12:28:17.967Z sha d26f444ee5d757d76ed368497a894fd605d3601c :: needs real behavior proof before merge. :: [P1] Require idempotency for transcript injection | [P2] Make sharing work in a fresh session | [P2] Remove live proof transcripts from the branch
  • reviewed 2026-07-15T01:10:37.884Z sha 0f45550 :: needs real behavior proof before merge. :: [P1] Add retry-safe idempotency to transcript injection | [P2] Support sharing before the first completed turn
  • reviewed 2026-07-15T02:23:08.908Z sha 0f45550 :: needs real behavior proof before merge. :: [P1] Require retry identity for the transcript write | [P2] Persist shared commands before the first agent turn
  • reviewed 2026-07-15T03:38:13.512Z sha 0f45550 :: needs real behavior proof before merge. :: [P1] Add retry-safe identity to transcript injection | [P2] Persist shared commands before the first agent turn
  • reviewed 2026-07-15T04:51:40.524Z sha 0f45550 :: needs real behavior proof before merge. :: [P1] Add retry-safe identity to transcript injection | [P2] Persist shared commands before the first agent turn
  • reviewed 2026-07-15T06:07:04.934Z sha 0f45550 :: needs real behavior proof before merge. :: [P1] Add retry-safe identity to transcript injection | [P2] Persist shared commands before the first agent turn
  • reviewed 2026-07-15T07:26:46.753Z sha 0f45550 :: needs real behavior proof before merge. :: [P1] Add retry-safe identity to transcript injection | [P2] Persist shared commands before the first agent turn
  • reviewed 2026-07-30T05:16:32.473Z sha 0f45550 :: needs real behavior proof before merge. :: [P1] Add a retry-safe identity to each transcript injection | [P2] Support sharing before the first agent turn

@fluffyxenia

Copy link
Copy Markdown
Contributor Author

Proof of behavior, from the committed PTY e2e test (src/tui/tui-pty-local.e2e.test.ts, "persists shared ! output into model context and keeps !! output history-only") — it drives a real tui --local backend where only the model HTTP endpoint is mocked, and asserts against the captured model request body, not the UI:

  1. Consent prompt offers No / Yes, local only / Yes, and share with the agent; the test arrow-selects the share option.
  2. !echo PROOF_AGENT_VISIBLE_123 → persisted bashExecution transcript row without excludeFromContext.
  3. !!echo PROOF_HISTORY_ONLY_456 → persisted row with excludeFromContext: true.
  4. The next model request contains PROOF_AGENT_VISIBLE_123 and does not contain PROOF_HISTORY_ONLY_456.
  5. A sibling unit test proves local-only consent persists nothing at all (default = shipped behavior).

Terminal excerpt from the passing run (ANSI control sequences stripped; fixture data only):

 Allow local shell commands for this session?
 This runs commands on YOUR machine (not the gateway) and may delete files or reveal secrets.
 Sharing also saves commands+output to session history; the agent sees `!` output next turn (`!!`
 stays history-only).
 Select an option (arrows + Enter), Esc to cancel.
   No
   Yes, local only
 → Yes, and share with the agent
 local shell: enabled; output is saved to history and `!` output is shared with the agent
 [local] $ echo PROOF_AGENT_VISIBLE_123
 [local] PROOF_AGENT_VISIBLE_123
 [local] exit 0
 [local] $ echo PROOF_HISTORY_ONLY_456
 [local] PROOF_HISTORY_ONLY_456
 [local] exit 0
 Test Files  1 passed | 1 skipped (2)
      Tests  1 passed | 27 skipped (28)
   Duration  39.83s

Additional hardening landed while producing this proof:

  • Mid-run injection fix: persisting a ! result while an agent run was in flight tripped the embedded runner's session-file fence ("session file changed while embedded prompt lock was released") and killed the run. Rows injected mid-run now carry appendMode: "side" like chat.inject's assistant bookkeeping rows; regression test in src/gateway/server-methods/chat.inject-bash-execution.test.ts.
  • Once-only persistence: a failed spawn emits both error and close; a shared settled-guard prevents duplicate transcript rows, with an error-then-close regression test.
  • Known v1 limitation (documented in code): in a session that has never completed a turn there is no durable session entry yet, and the first turn rewrites the transcript — the same limitation chat.inject has. The persist fails visibly ([local] not saved to session history: session not found) rather than silently dropping the row.

🤖 Generated with Claude Code

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 10, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Jul 12, 2026
@fluffyxenia
fluffyxenia force-pushed the tui-bash-persist branch 3 times, most recently from e4a409f to 4284528 Compare July 12, 2026 17:42
@fluffyxenia

Copy link
Copy Markdown
Contributor Author

On the open product question (whether ! agent-visible / !! history-only should become a convention): some context on why I think this belongs in OpenClaw on its own merits.

The motivating problem is straightforward: today a ! command's output vanishes on TUI restart, and the agent never knows the command happened — even when the user ran it specifically to affect what the agent does next (checking state, reproducing an error, fixing something the agent was blocked on). Persisting it closes a real gap in the local-shell workflow, not a cosmetic one.

To be clear, this isn't an attempt to copy any particular client. That said, it's fair to note the pattern is already proven elsewhere: Claude Code's ! prefix has shipped essentially these semantics (command, output, and exit status visible to the model and persisted across session resume) for a while now, so there's real-world evidence users find this behavior natural rather than surprising.

Where this PR deliberately goes further on safety than that precedent:

  • Consent-first: default behavior is unchanged from shipped OpenClaw (purely local, nothing persisted). Sharing is a per-session opt-in with a prompt that spells out exactly what gets saved and what the agent sees. Approval never carries across sessions.
  • !! as an escape hatch: history-only persistence keeps sensitive output (!!cat secrets.env) in the user's scrollback and resume history while guaranteeing it never enters the model's context.

Happy to adjust semantics/naming if maintainers prefer a different shape; the mechanical layers (transcript role, RPC, consent UI) are largely shape-agnostic.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added the app: android App: android label Jul 14, 2026
Comment thread src/gateway/server-methods/chat.ts Fixed
@fluffyxenia

Copy link
Copy Markdown
Contributor Author

Gateway-backed behavior proof — sharing, resume replay, cross-agent isolation

Evidence recorded against head 7a293b5c35, with provenance in-band: !openclaw --version runs inside the recorded session and returns OpenClaw 2026.7.2 (7a293b5), and the agent independently repeats that string after reading the shared output (resume log below).

Setup — no mocks anywhere in this run:

  • openclaw gateway built from this PR's head, running as a systemd user service on a Raspberry Pi 4 (aarch64, Node 22), loopback ws://127.0.0.1:18789, token auth
  • openclaw tui connected over real Gateway WebSocket transport (status bars in every capture show connected and the session identity)
  • Live inference: openrouter/deepseek/deepseek-v4-flash (real OpenRouter API, not a mocked model endpoint)

Formatting disclosure: captures are verbatim except trailing whitespace stripped, consecutive blank lines collapsed, and unrelated conversation/tool sections removed behind explicit [... removed ...] markers. Raw unmodified logs are retained and available on request.


1. Consent gate + ! sharing — agent sees the output through the gateway

First ! in a session raises the three-option prompt (nothing runs before an answer):

Allow local shell commands for this session?
This runs commands on YOUR machine (not the gateway) and may delete files or reveal secrets.
Sharing also saves commands+output to session history; the agent sees `!` output next turn (`!!` stays history-only).
Select an option (arrows + Enter), Esc to cancel.
   No
   Yes, local only
 → Yes, and share with the agent

After choosing share, !uname -a ran, and the agent — asked in natural conversation — quotes the output back:

user: Quick question, what's the most recent command I've run here?
agent: That'd be the uname -a you just ran — popped back Linux rpi4 6.12.75+.... Want me to check your shell history for anything before that?

The command between uname -a and that question was !!echo test (history-only) — so this single answer proves both directions: ! output reached model context, !! output did not (the agent names uname -a, not echo test, as most recent).

Full capture: first session (consent + sharing + !! exclusion)
openclaw tui - ws://127.0.0.1:18789 - agent main - session tuitestcmd
session agent:main:tuitestcmd

Hello Rune! Are you there?

[... memory-search tool card removed (unrelated index warning) ...]

🜁 I'm here. Late night (or early morning) for you — everything okay?

[local] $ uname -a
[local] Linux rpi4 6.12.75+rpt-rpi-v8 #1 SMP PREEMPT Debian 1:6.12.75-1+rpt1 (2026-03-11) aarch64 GNU/Linux
[local] exit 0

Yes! Evething is alright.

Good — glad everything's alright. And yep, that's me humming along on the Pi 4 over there. Confirmations of life received.
What's on your mind? Or just making sure the box is breathing?

[local] $ echo test
[local] test
[local] exit 0

Just making sure everything is up and running. Quick question, what's the most recent command I've run here?

That'd be the uname -a you just ran — popped back Linux rpi4 6.12.75+.... Want me to check your shell history for anything before that?

Nah, don't worry about it.

(echo test was submitted as !!echo test; the TUI renders ! and !! rows identically as [local] $.)

Full capture: consent prompt with status bar (gateway identity in-frame)
openclaw tui - ws://127.0.0.1:18789 - agent main - session tuitestcmd
session agent:main:tuitestcmd

Allow local shell commands for this session?
This runs commands on YOUR machine (not the gateway) and may delete files or reveal secrets.
Sharing also saves commands+output to session history; the agent sees `!` output next turn (`!!` stays history-only).
Select an option (arrows + Enter), Esc to cancel.
connected | idle
agent main | session tuitestcmd | openrouter/deepseek/deepseek-v4-flash | think high | verbose on | tokens ?/200k
─────────────────────────────────────────────
search: >
   No
   Yes, local only
 → Yes, and share with the agent

2. Resume replay — persisted rows survive a full TUI restart

The TUI was fully quit and relaunched into the same session. The replayed scrollback contains the complete prior conversation including both [local] rows with their output (see full capture). Post-resume, persisted rows are also queryable, not just replayed pixels — asked again after restart, the agent answers via its Session History tool:

agent: Well, you keep catching me on this one — the most recent command you typed in this session is still uname -a at 03:28 EDT.

(!!pwd had run in between; the agent correctly doesn't count it.)

Two design behaviors visible in the same capture:

  • Consent does not survive a TUI restart — the relaunched session re-prompts before the next ! runs (consent is per-process by design; it is never persisted).
  • In-band provenance: !openclaw --version → OpenClaw 2026.7.2 (7a293b5), and the agent's next reply confirms it saw that output: "Same version it just spat back at you — OpenClaw 2026.7.2 (7a293b5)." — which is the !-visibility proof repeated on the exact evidence head.
Full capture: resume session (replay + re-consent + recall + in-band version)
openclaw tui - ws://127.0.0.1:18789 - agent main - session tuitestcmd
session agent:main:tuitestcmd

Hello Rune! Are you there?

[... memory-search tool card removed (unrelated index warning) ...]

🜁 I'm here. Late night (or early morning) for you — everything okay?

[local] $ uname -a
[local] Linux rpi4 6.12.75+rpt-rpi-v8 #1 SMP PREEMPT Debian 1:6.12.75-1+rpt1 (2026-03-11) aarch64 GNU/Linux
[local] exit 0

Yes! Evething is alright.

Good — glad everything's alright. And yep, that's me humming along on the Pi 4 over there. Confirmations of life received.
What's on your mind? Or just making sure the box is breathing?

[local] $ echo test
[local] test
[local] exit 0

Just making sure everything is up and running. Quick question, what's the most recent command I've run here?

That'd be the uname -a you just ran — popped back Linux rpi4 6.12.75+.... Want me to check your shell history for anything before that?

Nah, don't worry about it.

No worries. I'm here if you need anything else — or if you want company while the rest of the world sleeps.

[... unrelated tool-diagnostics exchange removed (exec/web-search/process tool cards) ...]

Allow local shell commands for this session?
This runs commands on YOUR machine (not the gateway) and may delete files or reveal secrets.
Sharing also saves commands+output to session history; the agent sees `!` output next turn (`!!` stays history-only).
Select an option (arrows + Enter), Esc to cancel.

local shell: enabled; output is saved to history and `!` output is shared with the agent

[local] $ pwd
[local] /home/foxo/openclaw-dev
[local] exit 0

Right. One more time, what was the most recent command I've run in this session?

🧾 Session History
session current, limit 10, tools true

Well, you keep catching me on this one — the most recent command you typed in this session is still uname -a at 03:28 EDT. Everything else since has been me calling my own tools in response.
Are you testing my memory, or was there something else you ran that I might've missed?

[local] $ uname -r
[local] 6.12.75+rpt-rpi-v8
[local] exit 0

Your memory is fine, I'm just gathering proof for a merge request to OpenClaw. You're all good.

Ahhh — that makes sense now. You've been running me through my paces to gather screenshots and logs for an MR. Consistency check (asking the same question twice), tool diagnostics, heartbeat flow, late-night availability — all good signal.
Glad to be the test subject. 🜁 Tell me when the MR lands — I'd love to know what it addresses.

[local] $ openclaw --version
[local] OpenClaw 2026.7.2 (7a293b5)
[local] exit 0

It's OpenClaw PR number 103648 that is being tested now. What version are you running?

Same version it just spat back at you — OpenClaw 2026.7.2 (7a293b5). Running on this very Pi 4.
Good luck with PR #103648. If there's anything else you need for the merge request (specific tool output, error states, edge cases), just say the word.

(Everything above the removed diagnostics marker is the replayed scrollback from before the restart. pwd was submitted with !!; uname -r and openclaw --version with !.)

Storage-level verification — excludeFromContext flags in the canonical store

Rather than trusting operator memory of which commands used which prefix, the flags were read directly from the per-agent SQLite transcript (agents/main/agent/openclaw-agent.sqlite, transcript_events, read-only node:sqlite query) after the sessions above:

command persisted excludeFromContext submitted as
uname -a false !
echo test true !!
pwd true !!
uname -r false !
openclaw --version false !

Every row matches the observed agent-visibility behavior in the captures (this query also corrected one operator misremembering — the data is the attestation, not memory).

One semantics nuance found during this verification, disclosed for the product decision: excludeFromContext is context hygiene, not confidentiality. A !! row is excluded from the model's context assembly (proven by the recall answers above), but it remains a session-history row — and an agent that explicitly queries history via the sessions-history tool can see it (observed: the agent's history tool result listed the !!pwd row even as its context-based recall correctly omitted it). The consent prompt originally said "!! stays history-only", which under-communicated this; the branch now words it explicitly: "!! skips the model's context but stays in history the agent can query." If maintainers want hard exclusion from agent-facing history projections too, that's a separate decision — filtering agent-visible history diverges user-visible and agent-visible history views, and the local shell runs on the TUI host either way (anything truly secret shouldn't be typed into an agent client's composer at all).

3. Same-key cross-agent isolation — the P1 finding, reproduced against the fix

The exact P1 shape: session key global (the literal shared key, preserved across agents), share approved under agent main, then agent switched. Five sequential frames; note the header line in each — the session key stays global while the agent changes:

Frame 1 — agent main, session global, consent prompt, selecting share:

openclaw tui - ws://127.0.0.1:18789 - agent main - session global
session global
...
agent main | session global | openrouter/deepseek/deepseek-v4-flash | think high | tokens ?/200k
   No
   Yes, local only
 → Yes, and share with the agent

Frame 2 — share approved under main; command runs (persistence fails loudly because this fresh session has no completed turn yet — see note below):

local shell: enabled; output is saved to history and `!` output is shared with the agent
[local] $ uname -r
[local] 6.12.75+rpt-rpi-v8
[local] exit 0
[local] not saved to session history: session has no history yet; send the agent a message first

Frame 3 — /agent test (the TUI hops to that agent's own main session; getting back onto the shared key requires an explicit /session global):

session agent:test:main
agent set to test; use /crestodian to return

Frame 4 — agent test, session global again → fresh consent prompt instead of inherited approval:

openclaw tui - ws://127.0.0.1:18789 - agent test (test) - session global
session global
Allow local shell commands for this session?
...
agent test (test) | session global | openrouter/openrouter/auto | tokens ?/200k
   No
 → Yes, local only
   Yes, and share with the agent

Frame 5 — test answers "Yes, local only"; the command runs and no persistence is attempted (no [local] not saved line, no injected row — local-only means local-only):

local shell: enabled for this session (local only)
[local] $ uname -a
[local] Linux rpi4 6.12.75+rpt-rpi-v8 #1 SMP PREEMPT Debian 1:6.12.75-1+rpt1 (2026-03-11) aarch64 GNU/Linux
[local] exit 0

Before the consent-key fix (ab1a792), frame 4 would not have prompted: agent test would have silently inherited main's share approval on the same global key. The regression test for this lives in src/tui/tui-local-shell.test.ts ("re-prompts when a different agent uses the same session key").

An additional capture (not shown) demonstrates the prompt also re-fires across per-agent sessions (agent:test:main after switching from main's session).

Note on frame 2: a session with no completed first turn has no durable transcript entry; persistence into it fails visibly rather than silently dropping the row (same precondition as the existing chat.inject). The actionable message shown in the frame replaced a confusing session not found — a rough edge found and fixed while gathering this evidence (now commit 6662539037 after the rebase).


Summary of what these captures cover: consent gate before first execution; ! output visible to the agent through real Gateway transport with live inference; !! excluded from model context while remaining in history; persisted rows replayed after full TUI restart and queryable via session history; consent never persisted across restarts; share approval not inherited across agents on the same global session key; local-only consent attempts no persistence; fail-visible behavior when the first-turn precondition isn't met.

The branch has since been rebased onto current main (the recurring additive-tail conflicts in the gateway method table / protocol index, plus upstream's chat.ts modularization). Delta between evidence head 7a293b5c35 and the current head: upstream integration, the consent-prompt wording update described above, and a Kotlin protocol-enum regeneration — no behavior change to the feature paths shown here. The captures display the pre-update consent wording because that is what was on screen when they were recorded.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 14, 2026
fluffyxenia added a commit to fluffyxenia/openclaw that referenced this pull request Jul 15, 2026
- record a segment boundary for replayed tool calls even when verbose is
  off, so a turn's later cumulative text cannot rewrite pre-tool text in
  place on the default resume path; replay now routes through the same
  activity-summary path a live verbose-off run uses
- truncate the combined tool-card header to the render width (ANSI-aware)
  instead of letting it wrap and break the condensed card layout
- drop the bashExecution history-replay branch: shell persistence and its
  replay rendering belong to the persistence PR (openclaw#103648)
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 30, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Jul 30, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jul 31, 2026
@fluffyxenia

Copy link
Copy Markdown
Contributor Author

Not stale — still fully green (CI including mobile), just parked awaiting a maintainer review pass. Real-terminal and gateway-backed proof are already posted above (head 7a293b5c35); happy to refresh proof against current main if that helps unblock review.

@fluffyxenia

Copy link
Copy Markdown
Contributor Author

Following up on the sponsorship question ClawSweeper flagged above:

Should consent-gated ! agent visibility and !! history-only persistence become a supported core TUI and hidden Gateway protocol contract?

Not asking for a code re-review here — I know the branch is stale against current main and the proof is from an old head, and I'm intentionally holding off on that work (rebase + the two flagged fixes) until there's a maintainer answer on whether the feature itself is wanted. Redoing it now only to have main shift underneath it again before anyone looks isn't a good use of anyone's time.

If the direction is "yes, sponsor it" I'll do the rebase, fix the idempotency and fresh-session issues, and post fresh current-head proof. If it's "no" or "not now," happy to close it out — just don't want it sitting in limbo indefinitely on either side.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Aug 28, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

@openclaw-barnacle openclaw-barnacle Bot closed this Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: android App: android app: web-ui App: web-ui gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants