Repository navigation
Conversation
… 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.
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars. ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: 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. Comment |
PR Summary by QodoAdd leased agent turns, worktree commands, and secure hub coordination
AI Description
Diagram
High-Level Assessment
Files changed (37)
|
Code Review by Qodo
1. Built-in commands run unseen
|
| 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")); |
There was a problem hiding this comment.
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
| self.last_task += 1; | ||
| let task = Task { | ||
| id: format!("t_{}", self.last_task), |
There was a problem hiding this comment.
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
| 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]), |
There was a problem hiding this comment.
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
| if self.sharing.waiting_tasks.load(Ordering::Acquire) <= queue.len() { | ||
| self.add_thread(Some(code)); |
There was a problem hiding this comment.
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.
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.rsdiffers from main by exactly one line (preempt_if_idle()at the top ofagent_start);pty_write_internalstill 3 callers;enter_approves,agent_propose,MIN_REVIEW,decision_stands,agent_decidebyte-identical.What
TurnLockincoord.rsover an injected clock (the module grep test now also forbidsInstant::nowandlock(): FIFO queue of 8, tickets never reused, holder statesIdle | 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 inUnknownis never handed on by the lock.set_stateis keyed by ticket so a late Block from a released turn cannot idle the agent's next one.static TURN+static TURN_GUARD, andapply()is the only place a guard is taken or dropped (grep-asserted). R11 — holder ⇔AgentState.running— is tested on every transition including a panic inrun_gatedand a cancel whileAwaitingHuman(parked sender dropped →agent_proposefalse, no PTY write).request_turn,release_turn(a non-holder's release answers like "no turn").BUSYis gone:run_commandauto-requests, returns{position, holder, holder_state, retry_after_ms}asisErrorwhen not granted inside its wait, auto-releases on the Block — never fromUnknown.hub_state.turnv2. Sweep on every lock op and everyhub_stateread; no timer thread.( cd <wt> && <cmd> )beforeparse_run_args, sois_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 aworktreeargument.agent-donewith an owner check in the bar; no morethinking… (0/12)on external proposals;/mcp turnand/mcp turn releaseon all four surfaces (SLASH_ROWS25 → 28); release refused whileRunning, allowed fromUnknownwith a warning;initializestates the turn contract. ⌘J preempts an idle remote holder only.Found by the adversaries and fixed
OSC 133;Din 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_endnow needs the Block and the shell back in the foreground (tcgetpgrpon the master vsshell_pid; unknowable = not ended), for the first wait and the late one.preemptedonce, before any proposal.Also in this branch (from #5's last commit)
tiny_httpvendored 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 gettimeout-minutes: 20.Not verified
Real Codex/Cursor/Claude Code taking turns on one shell, and the 30 s
sleepscenario leaving the second agent incommand_still_running— needs the app and real clients.