Skip to content

M3 Turn lock + worktrees (v0.3.0 milestone 3): one agent holds the shell at a time, waiters queue with leases, worktree-scoped commands, and a live foreground command is never handed on - #6

Open
ayushap18 wants to merge 9 commits into
mainfrom
m3-turns

Conversation

@ayushap18

Copy link
Copy Markdown
Owner

Milestone 3 of the v0.3.0 plan, on top of #5 (M2) — includes M2's commits and the vendored tiny_http fix; the diff collapses once #4 and #5 merge.

281 backend tests (was 244) · 56 frontend · zero warnings. agent.rs differs from main by exactly one line (preempt_if_idle() at the top of agent_start); pty_write_internal still 3 callers; enter_approves, agent_propose, MIN_REVIEW, decision_stands, agent_decide byte-identical.

What

  • Pure TurnLock in coord.rs over an injected clock (the module grep test now also forbids Instant::now and lock(): FIFO queue of 8, tickets never reused, holder states Idle | AwaitingHuman | Running | Unknown. The lease measures agent silence only — 60 s idle, 10 min max — and both clocks are frozen in every other state, so there is still no approval timeout and a holder in Unknown is never handed on by the lock. set_state is keyed by ticket so a late Block from a released turn cannot idle the agent's next one.
  • Guard pair (sign-off Hardening, Linux support, MCP in both directions, and evals with real numbers #1, second instance): static TURN + static TURN_GUARD, and apply() is the only place a guard is taken or dropped (grep-asserted). R11 — holder ⇔ AgentState.running — is tested on every transition including a panic in run_gated and a cancel while AwaitingHuman (parked sender dropped → agent_propose false, no PTY write).
  • Tools: request_turn, release_turn (a non-holder's release answers like "no turn"). BUSY is gone: run_command auto-requests, returns {position, holder, holder_state, retry_after_ms} as isError when not granted inside its wait, auto-releases on the Block — never from Unknown. hub_state.turn v2. Sweep on every lock op and every hub_state read; no timer thread.
  • Worktrees: a registry worktree wraps the command as ( cd <wt> && <cmd> ) before parse_run_args, so is_dangerous, the bar, the PTY and the exit-mark matcher see one string. Paths with quote/space/$/backtick/;/backslash/control/invisible chars or relative paths are refused (table test). No tool takes a worktree argument.
  • Surface: per-proposal agent-done with an owner check in the bar; no more thinking… (0/12) on external proposals; /mcp turn and /mcp turn release on all four surfaces (SLASH_ROWS 25 → 28); release refused while Running, allowed from Unknown with a warning; initialize states the turn contract. ⌘J preempts an idle remote holder only.

Found by the adversaries and fixed

  • High: a forged OSC 133;D in an approved command's output ended the turn while the process still held the foreground, so the next waiter's approved command would have gone into its stdin. wait_end now needs the Block and the shell back in the foreground (tcgetpgrp on the master vs shell_pid; unknowable = not ended), for the first wait and the late one.
  • Under ⌘J a granted waiter whose claim failed was dropped, breaking FIFO → requeued at the head.
  • "keep the turn" was inferred from the reply → recorded at request time.
  • A preempted agent got no signal → its next request answers preempted once, before any proposal.

Also in this branch (from #5's last commit)

tiny_http vendored for a one-line pool fix: upstream strands most of a burst of connections on Linux (17 opened at once → as few as 4 seen; 14/20 rounds). CI's Ubuntu leg found it. Regression test pins it; CI jobs get timeout-minutes: 20.

Not verified

Real Codex/Cursor/Claude Code taking turns on one shell, and the 30 s sleep scenario leaving the second agent in command_still_running — needs the app and real clients.

… named in the bar, and no client call ever waits on a human

The hub had ONE bearer token and no identity, so the approval bar could only
say "external agent"; and run_command blocked the client's HTTP call until the
human pressed Enter — Codex and Cursor time out at ~60 s, so two of the three
target agents could not use the hub at all.

REGISTRY. AgentToken { name, token, scopes, worktree } with no Debug derive (a
derived one would put the token into panic messages). Scopes read | journal |
propose | message; journal is deliberately not a default. TOOL_SCOPES is the
authorization table: a tool absent from it is unreachable by anyone. The legacy
single token migrates to an agent named "default" — pure, idempotent, no read
path ever writes; downgrade fails closed (an old binary sees token:"" and
autostart refuses). resolve_bearer folds over every agent with no early exit
and refuses anything that is not 64 lowercase hex. A revoke is visible on the
next request.

IDENTITY. From the bearer only; no tool takes from/as/agent_id. A caller may act
only on its own proposals, and a foreign id answers exactly like an unknown id.
Names are [a-z0-9][a-z0-9_-]{0,31}; reserved words and an adversarial table
(bidi override, ·, whitespace, 33 chars, "run?") are refused by test, because
the name is rendered in the approval bar and must not be able to forge it. The
bar reads "codex · run? ⌘⏎ approve · esc deny"; an external proposal with an
empty agent is not approvable by any key.

ASYNC PROPOSALS. run_command { command, wait_ms } returns within a clamped 25 s
with today's result or a proposal_id; await_decision polls, idempotent, pending
on expiry. There is NO approval timeout: a shown proposal waits as long as the
human takes. The proposal record owns the AgentRunGuard for exactly its
lifetime, released at every terminal state including a panic path; an invariant
test pins PROPOSALS non-terminal <=> AgentState.running. Store bounded at 64.
Abuse limits: 30 s global deny cooldown, 1 pending per agent, 4 total, and a
refusal never emits agent-propose.

Also: a read-only multi-line command block above the bar so a long proposal is
readable in full (closes a documented danger-gate limitation); hub_state, a
read-only IPC command tested to contain no 64-hex substring; protocol hygiene
(2025-11-25, MCP-Protocol-Version, no Mcp-Session-Id); client handshake replays.

Found by the adversarial pass and fixed: initialize disclosed run_command to
every caller regardless of scope; the "chord rule byte-identical" test matched
its own source line and could not fail; a denial cooldown could be outrun by a
caller that read the budget before the Esc landed; the four-surface drift test
ignored descriptions.

agent.rs: zero changed lines. enter_approves, agent_propose, agent_decide,
decision_stands, MIN_REVIEW byte-identical. pty_write_internal: 3 callers, the
write still lexically after the approval check.

183 -> 211 backend tests, 49 -> 55 frontend.
…nd what they read has known secret shapes redacted while the human's view stays byte-identical

Agents that share the shell had no way to talk to each other or divide work,
and everything an agent read from the terminal came back raw — including any
key the human ever echoed.

COORD. src-tauri/src/coord.rs holds the boards as a plain data structure: no
AppHandle, no tauri::, no async, no statics — a source-grep test pins all four,
and the file joins GREPPED with zero pty_write_internal calls. Message ring 500
with a monotonic seq and an exact `missed` for a cursor older than the ring.
Tasks 64 active / 256 total, oldest terminal evicted, ids never reused; open →
claimed → done | failed | cancelled; the 4th claim refused; update by the
holder, cancel by holder or creator; every other caller gets the literal
unknown-id answer. One validator for every text field (control, bidi, empty,
length caps).

TASKS.JSON v1, frozen: read_config/write_config semantics (0600, atomic,
corrupt = Err with bytes untouched). A file that will not load leaves the board
broken — verbs refuse, nothing overwrites it. A crashed holder's task reopens
on load without burning a claim. A failed save rolls the change back and never
acks.

TOOLS under the message scope: post_message, read_messages, list_agents,
create_task, claim_task, update_task, list_tasks. Attribution from the bearer
only — a smuggled `from` is ignored (tested); update_task's schema has no
assignee field; two racing claims → exactly one winner; every board change is
on disk before the reply and announced once on the message board; every
successful tool result carries `unread`. run_command takes an optional task_id
with a 20-proposal budget per task, refused before the bar. parse_text_arg is
lifted from parse_run_args so every string-taking tool shares its refusals.

LIMITS. Per-agent token buckets: 60 messages/min, 30 task changes/min, reads a
burst of 4 refilled at 2/s — isError with retry_after_ms. serve() caps handler
threads at max(16, 4 × agents) with a per-agent share so one agent cannot
starve another; the 17th connection gets 503 without a thread.

REDACT. lib.rs redact(): shape scans, no regex crate — sk-/sk-ant-/gsk_/ghp_/
gho_/ghs_/ghu_/ghr_/github_pat_/xox[bpa]-/xapp-/AKIA/ASIA/AIza/JWT/PEM blocks/
Bearer/Authorization/URL userinfo/password=/token=/secret=/api_key= and their
_-suffixed names. Applied on the agent-facing path only: read_journal,
get_context, read_messages, list_tasks, run_command's own result, hub_state
titles. The human's journal, term_write, ⌘B and the approval bar are
byte-identical (tested); a call-site test pins exactly where redact( may
appear. evals/redaction-corpus.json is read by both the Rust test and the JS
mirror (npm run eval:redact, now a CI step), so the two cannot drift.

Found by the adversarial pass and fixed: task text bypassed redaction and
reached agents and the webview raw; run_command's result and await_decision's
replay were unredacted; keys glued to escape sequences (\n, %3D, (B, SGR)
slipped the word-boundary check; one agent could hold the whole handler cap.
Predating M2: a local process that promised more than 1024 body bytes and never
sent them stalled the accept thread forever, with no token — refuse() now
answers such a request on its own thread.

One M1 function changed: PropGuard::settle frees the approval slot before the
verdict is visible to waiters, which was the source of a rare spurious BUSY and
a flaky test. The gate — agent_propose, MIN_REVIEW, decision_stands,
agent_decide(bool), enter_approves — is unchanged; agent.rs has zero changed
lines; pty_write_internal has exactly 3 callers.

Known limits, documented: a key folded across lines, cut by the 8 KiB output
cap, or split by shell quoting gets through; no entropy scan.

211 -> 244 backend tests, 55 frontend, 0 warnings.
…trands most of them

CI's Ubuntu leg failed one_agent_holding_its_share_does_not_starve_another
("codex was never held to its share") and a rerun then hung in the backend
tests for the job's whole life. macOS passed every time. Reproduced in an
Ubuntu container: 2 of 7 runs failed.

Root cause is in tiny_http 0.12's TaskPool, not in Tachyon. `spawn` queues a
task onto "waiting" workers whenever waiting_tasks > 0, but a worker that has
been notified and not yet woken still counts as waiting, so a burst of
connections is queued onto the same handful of idle workers over and over.
Each worker wakes, pops ONE connection and runs it for the life of that
connection; every task past the first per worker sits in the queue until some
unrelated connection closes. A 40-line program against bare tiny_http on Linux
showed it: 17 connections opened at once, and in 14 of 20 rounds fewer reached
incoming_requests, as few as 4 (MIN_THREADS). Three MCP clients handshaking
together is exactly that burst; the maintained fork (tiny_http_dh) has the same
line.

The fix is one condition: spawn a thread when the queue already has a task per
waiting worker (`waiting_tasks <= queue.len()`), so a queued task always has a
distinct worker to wake. The crate is vendored at src-tauri/vendor/tiny_http —
the crates.io release plus that line, features/benches/examples/dev-deps
dropped, upstream's own lints allowed — and applied through [patch.crates-io].

a_burst_of_connections_all_reach_the_accept_loop pins it: 17 held connections,
all must reach the accept loop within 3 s, five rounds. On unpatched tiny_http
it fails on Linux in most runs; macOS wakes threads fast enough to hide it, so
the Ubuntu leg is the one that guards it. The formerly flaky test passed 9/9 on
Linux with the fix.

CI jobs get timeout-minutes: 20 so a hung test fails the job instead of sitting
on the 6 h default.
…s queue with leases, a worker's commands run visibly in its worktree, and a live foreground command is never handed on

Today a second agent's run_command got BUSY and retried blind; the
AgentRunGuard was owned by each Proposal record.

TURNLOCK. coord.rs gains a pure TurnLock over an injected clock (no
Instant::now, no lock(), no tauri — the module grep test now forbids all of
them): FIFO queue of 8, a 9th refused; tickets monotonic and never reused;
holder states Idle | AwaitingHuman | Running | Unknown. The lease measures
agent silence only — LEASE_IDLE 60 s and MAX_TURN 10 min count Idle time, both
clocks frozen in every other state, so there is no approval timeout and a
holder in Unknown is never handed on by the lock. Silent waiters pruned at
90 s. set_state is keyed by ticket so a late Block from a released turn cannot
idle the agent's next one. Every op returns events; the lock never sees a
guard.

GUARD PAIR (sign-off #1, second instance). mcp_server.rs holds static TURN and
static TURN_GUARD; one function, apply(), is the only place a guard is taken
(Granted → agent_claim) or dropped (Revoked/Pruned), grep-asserted. The
Proposal record now carries the ticket it ran under. R11 is a test on every
transition including a panic in run_gated and a cancel while AwaitingHuman,
which drops the parked sender so agent_propose answers false with no PTY
write. agent.rs changes by exactly one line: agent_start calls
preempt_if_idle() first, so ⌘J takes the shell back from an idle remote holder
and fails fast in every other state.

TOOLS. request_turn { wait_ms } and release_turn (propose scope; a non-holder's
release answers like "no turn"). BUSY is gone: run_command auto-requests a
turn, returns { position, holder, holder_state, retry_after_ms } as isError
when not granted inside its wait, and auto-releases on the Block — never from
Unknown. hub_state.turn = { holder, state, since_ms, queue, expires_in_ms }.
sweep runs on every lock op and every hub_state read; no timer thread.

WORKTREES. A registry worktree wraps the command as `( cd <wt> && <cmd> )` in
call_tool, before parse_run_args, so is_dangerous, the bar, the PTY write and
the exit-mark matcher see one string. /mcp agent add --worktree and /mcp agent
worktree <name> <path|off>; a path with a quote, space, $, backtick, ;,
backslash, control or invisible char, or a relative path, is refused (table
test). No tool has a worktree argument.

SURFACE. agent-done is per proposal {agent, proposal_id}; the bar tracks the
owner it shows so a done for X cannot clear a bar showing Y; run_gated no
longer emits "thinking… (0/12)". /mcp turn and /mcp turn release across all
four surfaces (SLASH_ROWS 25 → 28); release is refused while Running and
allowed from Unknown with a warning. initialize states the turn contract.

Found by the adversarial pass and fixed: a forged OSC 133;D in an approved
command's output could end the turn while the process still held the
foreground, and the next waiter's approved command would have gone into its
stdin — wait_end now requires the Block AND the shell back in the foreground
(tcgetpgrp on the master vs shell_pid; unknown answers "not ended"), for the
first wait and the late one. Under ⌘J a granted waiter whose claim failed was
dropped, breaking FIFO — requeued at the head. "keep the turn" was inferred
from the reply — now recorded at request time. A preempted agent got no
signal — its next request answers `preempted` once, before any proposal.

C12a stress: 8 threads for 5 s over the real statics, ≤1 holder per
observation, every grant matched by one release or revoke, holder ⇔ running at
every observation, a crashed holder freed after the lease, the N-client harness
rerun with queueing.

pty_write_internal: 3 callers. enter_approves, agent_propose, MIN_REVIEW,
decision_stands, agent_decide byte-identical. 244 → 280 backend tests,
55 → 56 frontend, 0 warnings.
@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 842a1331-a4cf-4726-9e94-ec50ee6b79f1


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Add leased agent turns, worktree commands, and secure hub coordination

✨ Enhancement 🐞 Bug fix 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Serialize shell access with FIFO leased turns that never preempt live commands.
• Scope commands to validated worktrees and expose turn controls across the UI.
• Add coordination boards, redaction coverage, and burst-safe HTTP connection handling.
Diagram

graph TD
  A["MCP Agents"] --> B["tiny_http"] --> C["MCP Hub"] --> G["Worktree Wrapper"] --> D["TurnLock"] --> E["Approval Bar"] --> F["PTY Shell"]
  C --> H["Agent Boards"]
Loading
High-Level Assessment

The pure, injected-clock TurnLock plus a single apply boundary is the strongest approach here: it makes lease boundaries deterministic, centralizes guard ownership, and prevents request lifetimes from controlling shell ownership. Timer threads, request-scoped guards, and an ordinary mutex were reasonably avoided because they would complicate testing, lock ordering, and long-running-command safety.

Files changed (37) +6570 / -107

Enhancement (2) +27 / -0
agent.rsLet the built-in agent preempt idle remote turns +1/-0

Let the built-in agent preempt idle remote turns

• Calls 'preempt_if_idle' before the built-in agent claims the approval slot. Active proposals and commands remain non-preemptible.

src-tauri/src/agent.rs

main.cssStyle a readable full-command approval block +26/-0

Style a readable full-command approval block

• Adds a wrapped, scrollable proposal panel above the approval bar so long commands remain inspectable.

ui/assets/main.css

Bug fix (1) +145 / -0
task_pool.rsFix burst connection dispatch in tiny_http +145/-0

Fix burst connection dispatch in tiny_http

• Changes worker selection to account for already queued tasks when measuring available waiting threads. This prevents burst connections from being stranded behind long-lived connection tasks.

src-tauri/vendor/tiny_http/src/util/task_pool.rs

Tests (2) +135 / -1
redact.mjsAdd a JavaScript mirror of credential redaction +130/-0

Add a JavaScript mirror of credential redaction

• Implements the Rust redaction rules in JavaScript and checks exact positive and negative corpus results. Exits unsuccessfully on any behavioral drift.

evals/redact.mjs

theme.rsRequire proposal text to remain theme-readable +5/-1

Require proposal text to remain theme-readable

• Extends theme contrast tests to cover the command proposal panel displayed over terminal content.

ui/src/theme.rs

Documentation (2) +137 / -28
README.mdDocument agent registration, worktrees, and turn controls +15/-5

Document agent registration, worktrees, and turn controls

• Expands the MCP command reference with per-agent registration, scope, worktree, and turn commands. Updates server-mode guidance to describe named proposals and asynchronous decision polling.

README.md

architecture.mdDescribe the multi-agent MCP hub architecture +122/-23

Describe the multi-agent MCP hub architecture

• Documents scoped identities, redaction, asynchronous proposals, leased shell turns, coordination boards, rate limits, handler caps, persistence, and the vendored HTTP fix. Defines holder states and their lease behavior.

docs/architecture.md

Other (30) +6126 / -78
ci.ymlBound CI duration and validate the redaction mirror +5/-0

Bound CI duration and validate the redaction mirror

• Adds a 20-minute job timeout so hung connection tests fail promptly. Runs the JavaScript redaction corpus alongside the Rust implementation.

.github/workflows/ci.yml

danger-gate.mdExpand the MCP threat model and turn-lock guarantees +151/-40

Expand the MCP threat model and turn-lock guarantees

• Documents identified approval prompts, denial cooldowns, worktree limitations, redaction boundaries, and task-board injection risks. Explains why running or unknown foreground commands are never automatically handed to another agent.

docs/danger-gate.md

redaction-corpus.jsonDefine the shared credential-redaction corpus +63/-0

Define the shared credential-redaction corpus

• Adds positive cases for common provider keys, JWTs, authorization values, private keys, named secrets, and URL passwords. Includes false-positive cases that must remain byte-identical.

evals/redaction-corpus.json

package.jsonRegister the redaction evaluation command +1/-0

Register the redaction evaluation command

• Adds the 'eval:redact' npm script for running the shared redaction corpus.

package.json

Cargo.lockResolve tiny_http from the vendored source +0/-2

Resolve tiny_http from the vendored source

• Removes the registry source and checksum metadata so Cargo uses the local patched crate.

src-tauri/Cargo.lock

Cargo.tomlPatch tiny_http to the vendored implementation +5/-0

Patch tiny_http to the vendored implementation

• Adds a crates.io patch directing 'tiny_http' to the local vendor directory and records why the fork is required.

src-tauri/Cargo.toml

coord.rsAdd bounded agent boards and the leased FIFO turn lock +1430/-0

Add bounded agent boards and the leased FIFO turn lock

• Introduces validated message and persistent task boards with ownership, retention, claim, and proposal limits. Adds a pure injected-clock TurnLock with stable tickets, FIFO queuing, idle leases, frozen active states, safe preemption, and extensive adversarial tests.

src-tauri/src/coord.rs

lib.rsIntegrate coordination commands and agent-facing redaction +284/-8

Integrate coordination commands and agent-facing redaction

• Registers the coordination module and hub-state IPC command, adds agent and turn slash help, and implements credential-shape redaction for agent-facing reads. Adds corpus and source-boundary tests to keep redaction off human-facing terminal paths.

src-tauri/src/lib.rs

Cargo.tomlDefine the minimized vendored tiny_http crate +25/-0

Define the minimized vendored tiny_http crate

• Adds the tiny_http 0.12.0 package manifest with only required dependencies and documents the single task-pool fix.

src-tauri/vendor/tiny_http/Cargo.toml

LICENSE-APACHEVendor tiny_http's Apache license +201/-0

Vendor tiny_http's Apache license

• Includes the Apache 2.0 license required for redistribution of the vendored dependency.

src-tauri/vendor/tiny_http/LICENSE-APACHE

LICENSE-MITVendor tiny_http's MIT license +25/-0

Vendor tiny_http's MIT license

• Includes the MIT license required for redistribution of the vendored dependency.

src-tauri/vendor/tiny_http/LICENSE-MIT

client.rsVendor tiny_http client connection parsing +309/-0

Vendor tiny_http client connection parsing

• Adds upstream request-line, header, connection-state, and pipelining handling for accepted client sockets.

src-tauri/vendor/tiny_http/src/client.rs

common.rsVendor tiny_http protocol primitives +440/-0

Vendor tiny_http protocol primitives

• Adds upstream HTTP status, header, method, and version types with parsing and validation tests.

src-tauri/vendor/tiny_http/src/common.rs

connection.rsVendor tiny_http socket abstractions +194/-0

Vendor tiny_http socket abstractions

• Adds upstream unified TCP and Unix listener, connection, and address abstractions.

src-tauri/vendor/tiny_http/src/connection.rs

lib.rsVendor the tiny_http server implementation +445/-0

Vendor the tiny_http server implementation

• Adds upstream server construction, request acceptance, dispatch, receive APIs, and graceful shutdown behavior.

src-tauri/vendor/tiny_http/src/lib.rs

request.rsVendor tiny_http request handling +518/-0

Vendor tiny_http request handling

• Adds upstream request body framing, expectation handling, response dispatch, protocol upgrades, and automatic cleanup.

src-tauri/vendor/tiny_http/src/request.rs

response.rsVendor tiny_http response serialization +574/-0

Vendor tiny_http response serialization

• Adds upstream response builders, header rules, transfer-encoding selection, and body serialization.

src-tauri/vendor/tiny_http/src/response.rs

ssl.rsVendor tiny_http TLS module selection +20/-0

Vendor tiny_http TLS module selection

• Adds upstream feature-gated aliases for OpenSSL and Rustls server implementations.

src-tauri/vendor/tiny_http/src/ssl.rs

openssl.rsVendor tiny_http OpenSSL support +110/-0

Vendor tiny_http OpenSSL support

• Adds upstream OpenSSL context construction, certificate loading, stream splitting, and I/O forwarding.

src-tauri/vendor/tiny_http/src/ssl/openssl.rs

rustls.rsVendor tiny_http Rustls support +120/-0

Vendor tiny_http Rustls support

• Adds upstream Rustls certificate and key loading, server configuration, and synchronized stream handling.

src-tauri/vendor/tiny_http/src/ssl/rustls.rs

test.rsVendor tiny_http request test builder +127/-0

Vendor tiny_http request test builder

• Adds the upstream 'TestRequest' builder for constructing in-memory HTTP requests.

src-tauri/vendor/tiny_http/src/test.rs

custom_stream.rsVendor the split custom stream adapter +39/-0

Vendor the split custom stream adapter

• Adds the upstream adapter that combines independent readers and writers into one stream.

src-tauri/vendor/tiny_http/src/util/custom_stream.rs

equal_reader.rsVendor fixed-length request-body reading +131/-0

Vendor fixed-length request-body reading

• Adds the upstream reader that enforces a byte limit and drains unread request data on drop.

src-tauri/vendor/tiny_http/src/util/equal_reader.rs

fused_reader.rsVendor fused EOF handling +48/-0

Vendor fused EOF handling

• Adds the upstream reader wrapper that permanently transitions to EOF after its source finishes.

src-tauri/vendor/tiny_http/src/util/fused_reader.rs

messages_queue.rsVendor the blocking server message queue +96/-0

Vendor the blocking server message queue

• Adds the upstream mutex and condition-variable queue used for requests, errors, timeouts, and unblocking.

src-tauri/vendor/tiny_http/src/util/messages_queue.rs

mod.rsVendor tiny_http utility exports and header parsing +64/-0

Vendor tiny_http utility exports and header parsing

• Wires the vendored utility modules and includes weighted HTTP header-value parsing.

src-tauri/vendor/tiny_http/src/util/mod.rs

refined_tcp_stream.rsVendor split HTTP and HTTPS stream handling +152/-0

Vendor split HTTP and HTTPS stream handling

• Adds the upstream clonable stream wrapper with independent read and write shutdown semantics.

src-tauri/vendor/tiny_http/src/util/refined_tcp_stream.rs

sequential.rsVendor pipelined I/O ordering utilities +174/-0

Vendor pipelined I/O ordering utilities

• Adds upstream sequential reader and writer builders that preserve HTTP pipelining order.

src-tauri/vendor/tiny_http/src/util/sequential.rs

ai_bar.rsHarden identified proposal rendering and ownership +254/-23

Harden identified proposal rendering and ownership

• Names external requesters, rejects approval of unidentified proposals, displays commands in a read-only wrapped block, and keys completion events by proposal ID. It also loads safe agent names for completion and adds regression tests for approval invariants.

ui/src/ai_bar.rs

complete.rsAdd completion for agent and turn commands +121/-5

Add completion for agent and turn commands

• Expands slash-command rows and grammar for agent registration, worktree management, and turn inspection. Suggests existing agent names only where appropriate and verifies all command surfaces remain synchronized.

ui/src/complete.rs

@qodo-code-review

qodo-code-review Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (4) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Built-in commands run unseen 🐞 Bug ⛨ Security
Description
proposal_block truncates commands after MAX_COMMAND_CHARS and labels the omitted suffix as
running unseen, but the approval handler still approves the original proposal. The built-in agent
passes an unbounded parsed reply to agent_propose and later writes that same full cmd to the
PTY, so a model-generated suffix beyond 4096 characters can execute without human review.
Code

ui/src/ai_bar.rs[R124-126]

+    match text.char_indices().nth(MAX_COMMAND_CHARS) {
+        None => text.to_string(),
+        Some((i, _)) => format!("{}\n… cut at {MAX_COMMAND_CHARS} characters — the rest runs unseen", &text[..i]),
Evidence
The added UI helper deliberately renders only the first 4096 characters while retaining approval
functionality. The built-in agent has no corresponding command-length check: it forwards cmd to
the proposal event and, after approval, writes that same complete value to the PTY.

ui/src/ai_bar.rs[112-127]
src-tauri/src/agent.rs[335-365]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The built-in agent can propose and execute commands longer than the approval block displays. The UI explicitly marks the hidden suffix as running unseen, while the agent execution path writes the complete command after approval.

## Fix Focus Areas
- ui/src/ai_bar.rs[123-127]
- src-tauri/src/agent.rs[335-365]

## Recommended Fix
Enforce `MAX_COMMAND_CHARS` before a built-in `AgentAction::Run` reaches `agent_propose` or the PTY write. Reject the overlong model reply and ask the agent to provide a shorter command; do not allow an approval decision to execute text omitted from the approval surface.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Idle sockets exhaust threads 🐞 Bug ☼ Reliability
Description
TaskPool::spawn calls add_thread whenever no worker is waiting, creating a fresh
operating-system thread without enforcing a connection-worker limit. An unauthenticated loopback
client can keep each worker blocked while tiny_http reads an incomplete or persistent request, so
repeated accepted connections consume threads and memory before parsed requests reach
application-level admission controls.
Code

src-tauri/vendor/tiny_http/src/util/task_pool.rs[R80-81]

+        if self.sharing.waiting_tasks.load(Ordering::Acquire) <= queue.len() {
+            self.add_thread(Some(code));
Evidence
Each accepted socket is submitted to the modified task pool, which selects add_thread whenever no
distinct idle worker is available, and add_thread directly invokes thread::spawn. The assigned
worker then iterates over its client connection for the connection's lifetime and blocks while
waiting for CRLF to complete an incomplete request header, retaining the newly created thread
without any bounded-pool mechanism.

src-tauri/vendor/tiny_http/src/util/task_pool.rs[69-85]
src-tauri/vendor/tiny_http/src/util/task_pool.rs[88-134]
src-tauri/vendor/tiny_http/src/client.rs[76-105]
src-tauri/vendor/tiny_http/src/lib.rs[282-337]
src-tauri/vendor/tiny_http/src/util/task_pool.rs[88-97]
src-tauri/vendor/tiny_http/src/lib.rs[313-328]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The vendored pool spawns unbounded connection-reader threads when its idle workers are busy. Incomplete or persistent unauthenticated HTTP connections can retain those threads during header parsing, allowing accepted sockets to exhaust process resources before application-level request admission applies.

## Fix Focus Areas
- src-tauri/vendor/tiny_http/src/util/task_pool.rs[69-85]
- src-tauri/vendor/tiny_http/src/client.rs[76-105]
- src-tauri/vendor/tiny_http/src/lib.rs[313-337]

## Recommended Fix
Preserve enough bounded concurrency to handle bursts, but impose a hard maximum on active connection-reader threads and queue excess sockets or reject and close them when capacity is exhausted. Add a finite request-header read deadline so clients that never complete their headers release their worker and connection.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Agent reads expose authorization tokens 🐞 Bug ⛨ Security
Description
secret_at strips only literal spaces before Authorization: and starts the replacement at an
opening quote, where its matcher immediately produces an empty match. Inputs such as
Authorization:\tBasic dXNlcjpwYXNz or Authorization:"Basic abc123" therefore reach agent-facing
read paths without redaction.
Code

src-tauri/src/lib.rs[R1787-1790]

+    let spaces = pre.iter().rev().take_while(|&&c| c == b' ').count();
+    let named = &pre[..i - spaces];
+    if ends_with_ci(named, "authorization:") {
+        return Some((i, run_end(b, i, |c| !b"\r\n\"'".contains(&c)), "authorization"));
Evidence
The redactor counts only byte-space characters before checking for authorization:, and its value
predicate rejects quotes at the first byte. The corpus establishes authorization headers as a
supported credential shape, while redact is explicitly used for agent-facing output.

src-tauri/src/lib.rs[1630-1647]
src-tauri/src/lib.rs[1786-1791]
evals/redaction-corpus.json[18-19]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Recognizable authorization values bypass redaction when separated by a tab or beginning immediately with a quote.

## Fix Focus Areas
- src-tauri/src/lib.rs[1786-1791]
- evals/redaction-corpus.json[18-19]
- evals/redact.mjs[87-94]

## Recommended Fix
Treat supported horizontal whitespace consistently, consume an optional opening quote before matching the authorization value, and preserve that quote around the replacement. Add corpus cases for tab-separated and quoted authorization values, then update both implementations to produce identical output.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. Malformed task files crash creation 🐞 Bug ☼ Reliability
Description
load_from accepts t_18446744073709551615 as a valid persisted ID and restores last_task to the
maximum unsigned integer. The next create_task overflows at last_task += 1, panicking in checked
builds or wrapping to t_0 and violating ID uniqueness otherwise.
Code

src-tauri/src/coord.rs[R299-301]

+        self.last_task += 1;
+        let task = Task {
+            id: format!("t_{}", self.last_task),
Evidence
Persisted tasks are deserialized without ID invariants, and load_from assigns the greatest
parseable t_<u64> suffix directly to last_task. Creation then performs an unchecked increment
before formatting the next identifier.

src-tauri/src/coord.rs[129-151]
src-tauri/src/coord.rs[395-415]
src-tauri/src/coord.rs[299-301]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A syntactically valid tasks file containing the maximum numeric task ID makes the next task creation overflow.

## Fix Focus Areas
- src-tauri/src/coord.rs[395-415]
- src-tauri/src/coord.rs[299-301]

## Recommended Fix
Validate all persisted task IDs during loading, including their format, uniqueness, and whether another ID can be allocated. Reject an exhausted counter as a broken task board, and use checked increment during creation so malformed state returns an error instead of panicking or wrapping.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
Review mode: 🧠 Deep: This is a highly logic-dense, cross-cutting concurrency and command-routing change spanning many independent paths, with substantial security and data-loss-like blast radius where redundant review could catch subtle defects.

Grey Divider

Tip of the day
💡 Did you know, you can keep summaries lean with Finding overflow, which tucks the rest behind 'View more'

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src-tauri/src/lib.rs
Comment on lines +1787 to +1790
let spaces = pre.iter().rev().take_while(|&&c| c == b' ').count();
let named = &pre[..i - spaces];
if ends_with_ci(named, "authorization:") {
return Some((i, run_end(b, i, |c| !b"\r\n\"'".contains(&c)), "authorization"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Agent reads expose authorization tokens 🐞 Bug ⛨ Security

secret_at strips only literal spaces before Authorization: and starts the replacement at an
opening quote, where its matcher immediately produces an empty match. Inputs such as
Authorization:\tBasic dXNlcjpwYXNz or Authorization:"Basic abc123" therefore reach agent-facing
read paths without redaction.
Agent Prompt
## Issue description
Recognizable authorization values bypass redaction when separated by a tab or beginning immediately with a quote.

## Fix Focus Areas
- src-tauri/src/lib.rs[1786-1791]
- evals/redaction-corpus.json[18-19]
- evals/redact.mjs[87-94]

## Recommended Fix
Treat supported horizontal whitespace consistently, consume an optional opening quote before matching the authorization value, and preserve that quote around the replacement. Add corpus cases for tab-separated and quoted authorization values, then update both implementations to produce identical output.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread src-tauri/src/coord.rs
Comment on lines +299 to +301
self.last_task += 1;
let task = Task {
id: format!("t_{}", self.last_task),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

4. Malformed task files crash creation 🐞 Bug ☼ Reliability

load_from accepts t_18446744073709551615 as a valid persisted ID and restores last_task to the
maximum unsigned integer. The next create_task overflows at last_task += 1, panicking in checked
builds or wrapping to t_0 and violating ID uniqueness otherwise.
Agent Prompt
## Issue description
A syntactically valid tasks file containing the maximum numeric task ID makes the next task creation overflow.

## Fix Focus Areas
- src-tauri/src/coord.rs[395-415]
- src-tauri/src/coord.rs[299-301]

## Recommended Fix
Validate all persisted task IDs during loading, including their format, uniqueness, and whether another ID can be allocated. Reject an exhausted counter as a broken task board, and use checked increment during creation so malformed state returns an error instead of panicking or wrapping.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread ui/src/ai_bar.rs
Comment on lines +124 to +126
match text.char_indices().nth(MAX_COMMAND_CHARS) {
None => text.to_string(),
Some((i, _)) => format!("{}\n… cut at {MAX_COMMAND_CHARS} characters — the rest runs unseen", &text[..i]),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

2. Built-in commands run unseen 🐞 Bug ⛨ Security

proposal_block truncates commands after MAX_COMMAND_CHARS and labels the omitted suffix as
running unseen, but the approval handler still approves the original proposal. The built-in agent
passes an unbounded parsed reply to agent_propose and later writes that same full cmd to the
PTY, so a model-generated suffix beyond 4096 characters can execute without human review.
Agent Prompt
## Issue description
The built-in agent can propose and execute commands longer than the approval block displays. The UI explicitly marks the hidden suffix as running unseen, while the agent execution path writes the complete command after approval.

## Fix Focus Areas
- ui/src/ai_bar.rs[123-127]
- src-tauri/src/agent.rs[335-365]

## Recommended Fix
Enforce `MAX_COMMAND_CHARS` before a built-in `AgentAction::Run` reaches `agent_propose` or the PTY write. Reject the overlong model reply and ask the agent to provide a shorter command; do not allow an approval decision to execute text omitted from the approval surface.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +80 to +81
if self.sharing.waiting_tasks.load(Ordering::Acquire) <= queue.len() {
self.add_thread(Some(code));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

3. Idle sockets exhaust threads 🐞 Bug ☼ Reliability

TaskPool::spawn calls add_thread whenever no worker is waiting, creating a fresh
operating-system thread without enforcing a connection-worker limit. An unauthenticated loopback
client can keep each worker blocked while tiny_http reads an incomplete or persistent request, so
repeated accepted connections consume threads and memory before parsed requests reach
application-level admission controls.
Agent Prompt
## Issue description
The vendored pool spawns unbounded connection-reader threads when its idle workers are busy. Incomplete or persistent unauthenticated HTTP connections can retain those threads during header parsing, allowing accepted sockets to exhaust process resources before application-level request admission applies.

## Fix Focus Areas
- src-tauri/vendor/tiny_http/src/util/task_pool.rs[69-85]
- src-tauri/vendor/tiny_http/src/client.rs[76-105]
- src-tauri/vendor/tiny_http/src/lib.rs[313-337]

## Recommended Fix
Preserve enough bounded concurrency to handle bursts, but impose a hard maximum on active connection-reader threads and queue excess sockets or reject and close them when capacity is exhausted. Add a finite request-header read deadline so clients that never complete their headers release their worker and connection.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

…il it

eight_agents_for_five_seconds_break_no_bound wrote tasks.json on every task
change while eight threads hammered the board. On CI's Ubuntu runner, under
the rest of the suite, that paced the run to 305 messages in 5 s, and the
assertion that the run reached every ceiling (ring 500, 64 active, 256 total —
there so the bounds tests cannot pass vacuously) failed. macOS's disk was fast
enough to hide it.

The bounds are the board's, not the disk's. The threads now run against an
in-memory board; the file is written once afterwards and reloaded, which is
the kill-and-reload half of the test and the only part that needs a path.
…-read

r11_one_holder_one_guard_at_every_transition failed once on CI's Ubuntu leg
("a grant with no guard was left holding the shell") and passed 10/10 in
isolation there. The turn lock is process-global: a handler thread that an
earlier test left behind can `touch` it in the gap between take_turn returning
and the test's re-read, and that grants the queued r11c with THAT test's claim
— a legitimate grant, with a guard, that the old assertion mistook for a
holder without one.

The busy payload is built inside the critical section, so it is the one
reading no other thread can disturb: it now must say no holder AND r11c at
position 1. Outside the lock the test asserts R11 itself — a holder iff a
guard — and that ⌘J's own claim was untouched.
…ing and grants nobody

In the full suite on Linux r11_one_holder_one_guard_at_every_transition
failed at "preempt refused while AwaitingHuman": the lock had a holder, the
test's own approval slot was free. Since M3 every tools/call runs
touch(caller), and touch — like every lock op — swept first, and a sweep
grants the head of the queue. So an M2 board test running in parallel
(post_message from a stub that never asked for the shell) was the thread that
granted r11c, with ITS stub's claim; the test then found a holder whose guard
belonged to nobody it knew.

In the app there is one claim, so the grant itself would have been right; the
flaw is in who makes it. An agent reading the board is not waiting for the
shell, and its message is not the moment to re-read leases and hand the shell
on. A stale ticket's settle — a command's late Block for a released turn — is
the same kind of non-event. Both now return no events and touch nothing.
Waiters re-ask every retry_after_ms and every hub_state read sweeps, so a
lapsed lease is still noticed by someone who wants the shell.

set_state_is_keyed_by_ticket pins both: with the shell free and a waiter at
the head, a stale settle and a stranger's touch each grant nobody. agree() now
names the holder it found, so the next such failure says who.
…ed ones

the_17th_held_connection_gets_503_and_no_thread failed in 2 of 6 full-suite
runs on Linux and 0 of 17 alone. Under load a poll was in flight when the
last of the 16 holds reached the accept loop, so for that instant the cap was
full and the HELD request was the one refused — 15 parked, and every later
poll answered 200 until the deadline.

A refused hold is not silent: it hears a 503 on its socket, while a parked
one hears nothing. The poll loop now peeks each held socket with a 1 ms read
timeout and re-opens any that was answered, so the 503 it waits for is always
the one that means sixteen are parked.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant