Skip to content

Commit 1d6e665

Browse files
committed
feat: add tests for useGitSidebar, useProviderModels, WebAgentChat, and hub-relay-client
- Implement tests for `useGitSidebar` to verify isolated branch switching behavior. - Add tests for `useProviderModels` to ensure fallback behavior during remote discovery. - Create tests for `WebAgentChat` to validate execution custody and event handling. - Introduce tests for `hub-relay-client` to cover connection management and event subscription. feat: implement web bridge routes for persistent state management - Add functionality to manage web bridge routes in local storage. - Ensure routes are recoverable across module reloads without losing authority. feat: enhance surface UI state management - Introduce state management for surface UI to isolate open drawers per chat session. - Implement functions to set and check the open state of surfaces. feat: add worktree selection management for chat sessions - Implement worktree selection isolation for chat sessions and Git workspace tabs. - Provide functions to resolve selected worktrees based on session context. feat: define shared hub relay types for consistent protocol handling - Create shared types for hub relay communication, including connection tickets and control frames. feat: started the browser-parity work. Implemented/connected: - Browser attachment upload path - MCP registry loading and secure ID-only server selection - GitHub status, PR listing, workflow runs, issues, - create/merge/approve operations - OpenAI/xAI browser voice using Brain-held keys - Browser editor formatting through workspace Prettier - Persistent Stop button and provider model fixes
1 parent 4b66c57 commit 1d6e665

56 files changed

Lines changed: 3740 additions & 370 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,5 @@ packaging/arch/pkg/
4747
packaging/arch/src/
4848
packaging/arch/*.deb
4949
packaging/arch/*.pkg.tar.*
50+
tester/
51+
test-workspace/

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ The shared React renderer supports desktop and direct browser clients. New rende
147147

148148
Remote-access credentials are authority boundaries. Pairing tokens must remain short-lived, memory-only, and single-use. Persist only device-session digests in owner-only atomic stores; enforce expiry and revocation. Browser HTTP/WebSocket origins must match exactly or be explicitly configured—never reflect arbitrary `Origin`/forwarded headers. Keep authentication limiters bounded, and do not hardcode CJ's `crewcode.logixhub.icu` deployment as a default Hub URL.
149149

150-
The self-hosted Hub is a separate `crewcode hub` process, not Electron renderer state. Keep its SQLite store owner-only and server-side; persist WebAuthn public credentials and only digests of browser/CSRF secrets. Bootstrap credentials and WebAuthn challenges stay short-lived and memory-only. Require user verification, exact configured RP origin/id, one-use challenges, secure HttpOnly SameSite cookies, and CSRF checks for mutations. Machine enrollment tokens must also stay short-lived, memory-only, single-use, and rate-limited; persist only machine bearer digests at the Hub and keep the brain credential file owner-only. Presence is outbound-only and revocation must fail closed. Do not let Hub identity or machine presence imply brain execution authority: tickets, relay, command scope, and brain-side authorization remain separate gates.
150+
The self-hosted Hub is a separate `crewcode hub` process, not Electron renderer state. Keep its SQLite store owner-only and server-side; persist WebAuthn public credentials and only digests of browser/CSRF secrets. Bootstrap credentials and WebAuthn challenges stay short-lived and memory-only. Require user verification, exact configured RP origin/id, one-use challenges, secure HttpOnly SameSite cookies, and CSRF checks for mutations. Machine enrollment tokens must also stay short-lived, memory-only, single-use, and rate-limited; persist only machine bearer digests at the Hub and keep the brain credential file owner-only. Presence and relay connections are outbound-only and revocation must fail closed. Hub connection tickets remain short-lived, memory-only, one-shot, browser-session/user/machine bound, and exact-origin protected. Relay application frames must stay end-to-end encrypted and ordered; the Hub may route metadata but must not receive RPC/source/terminal/agent plaintext. Do not let Hub identity, machine presence, or requested ticket scope imply Brain execution authority: `crewcode brain` defaults to no RPC grants, and every decrypted method must pass both explicit Brain-local scope and registered-workspace validation. Relay loss means pending outcomes are interrupted, never successful.
151151

152152
### Path alias
153153

‎docs/execution-custody.md‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,25 @@ anything else is, by definition, unexplained.
215215

216216
**Remote-access transport** (`src/main/agents/bridge-service.ts`) — partial.
217217
Mid-turn mode changes are refused and deferred, and orphaned permission requests
218-
are cancelled on close/abort/stop. It does **not** yet persist custody records or
219-
implement the halt/reauthorize lifecycle. Stated plainly rather than implied.
218+
are cancelled on explicit abort/stop or provider close. In Hub mode, browser relay
219+
loss now detaches rather than stopping Brain-owned agents and PTYs. The Brain keeps
220+
a bounded 1,000-event/1 MiB replay window per detached resource, caps each user at
221+
100 owned resources, exposes execution status, and permits the same authenticated
222+
owner with the required Brain-local scope
223+
to reclaim a stable resource id using a fresh encrypted connection. Reclaimed events
224+
are held until the browser chat subscriber and recovered execution route are ready,
225+
preventing a fast completed reply from falling between transport setup and App mount.
226+
Interrupted RPCs and prompts are never replayed. The completed conversation transcript remains in the
227+
Brain-local conversation store.
228+
229+
This custody is currently **Brain-process-resident**, not crash durable. A Brain
230+
process stop, VPS restart, machine revocation, or loss of the persistent Brain-to-Hub
231+
relay closes the loopback backend and its provider processes. Remote access still
232+
does not persist the full halt/reauthorize journal described above, so such a loss
233+
must not be presented as a successfully completed turn. A fresh connection drops
234+
resource ids the restarted Brain could not actually reclaim. The next explicit user
235+
prompt may idempotently reassert the stable bridge and create a replacement provider
236+
process, but CrewCode never replays the interrupted prompt or infers its outcome.
220237

221238
**Not yet covered:** terminal (PTY) panes, plugin capability sessions, and SSH
222239
host-key changes during a live session. Crew merges have their own equivalent

‎docs/security-model.md‎

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,19 +76,41 @@ outbound HTTPS requests. Presence goes offline after 90 seconds without a succes
7676
heartbeat, and owner revocation immediately makes the bearer credential fail closed.
7777
Browser mutations retain exact-origin and CSRF enforcement.
7878

79-
**Authority limit:** presence proves only that the enrolled process recently
80-
possessed its machine credential. It does not authorize commands, filesystem access,
81-
agent execution, a relay, or a connection ticket. The current Ed25519 key is reserved
82-
for later signed-ticket/relay work; heartbeats currently authenticate with the
83-
separate bearer credential over TLS.
79+
**Connection and execution gates:** only an authenticated Hub browser session plus
80+
CSRF can issue a 60-second memory-only ticket for one owned, active, relay-connected
81+
machine. Ticket ids are one-shot even after a wrong-secret guess. The authenticated
82+
outbound Brain WebSocket and exact-origin browser WebSocket are paired only for that
83+
machine; the relay bounds frame size and buffered output, applies a shared per-connection
84+
token bucket (240-frame/8 MiB burst, refilling at 60 frames and 2 MiB per second),
85+
and never accepts arbitrary destinations. Browser and Brain then use ephemeral P-256 ECDH. The Brain signs the
86+
handshake transcript with its enrolled Ed25519 key, and ordered application frames
87+
use direction-separated HKDF/AES-256-GCM keys. The Hub sees routing metadata and
88+
handshake public values, but not RPC, source, terminal, prompt, or response plaintext.
89+
90+
Hub identity still does not grant execution. `crewcode brain` grants no RPC scope by
91+
default and requires explicit local `--workspace-root` plus repeatable
92+
`--allow-scope` settings. Each decrypted method is classified at the Brain and must
93+
be included in both the ticket request and local grant. The reused backend then
94+
revalidates registered workspace roots for filesystem, Git, PTY, and agent calls.
8495

8596
**Tests:** `hub-server.test.ts` covers CSRF, issue/enroll, replay rejection, stale
8697
presence, heartbeat, and revocation. `hub-machine-enrollment.test.ts` covers URL
87-
policy, argument-secret avoidance, credential validation, and owner-only file mode.
98+
policy, argument-secret avoidance, credential validation, owner-only file mode, and
99+
Brain CLI grants. `hub-relay.test.ts` covers ticket expiry/one-shot behavior,
100+
authenticated relay routing, Ed25519-authenticated E2EE, scoped read success, local
101+
scope denial, per-connection traffic rejection, and ticket replay rejection.
102+
`hub-relay-client.test.ts` covers explicit fresh-ticket reconnect without RPC replay.
88103

89104
**Residual limitation:** machine credential rotation/logout and recovery are not yet
90-
implemented. The long-running brain presence process requires an external service
91-
manager for automatic restart and does not yet use signed per-request challenges.
105+
implemented. Relay traffic is bounded per connection, but durable bandwidth metrics
106+
and broader aggregate abuse accounting are not implemented. Browser relay loss now
107+
detaches Brain-owned terminals and agents instead of stopping them. A fresh encrypted
108+
connection can explicitly reclaim stable resource ids, with up to 100 owned resources
109+
per user and 1,000 events / 1 MiB of detached evidence buffered per resource;
110+
interrupted RPCs are never replayed.
111+
Execution custody is still process-resident rather than crash durable: Brain process,
112+
VPS, revocation, or persistent Brain-to-Hub relay loss can stop execution without a
113+
complete remote halt journal. Attachment tunneling is also not implemented.
92114

93115
## Hop 1 — untrusted content -> agent
94116

‎docs/web-remote-access.md‎

Lines changed: 90 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -64,14 +64,35 @@ pairing URL, exchanges it for a brain-local session, and talks directly to that
6464
brain. This mode is for loopback, LAN, or a trusted tailnet. It requires a reachable
6565
address and does not provide account login or machine discovery.
6666

67-
### Self-hosted Hub mode (identity foundation implemented)
68-
69-
The first Hub slice is implemented as the separate `crewcode hub` process. It
70-
provides durable local identity storage, first-owner passkey bootstrap, passkey
71-
sign-in, revocable browser sessions, audit events, and an authenticated machine-list
72-
skeleton. Machine enrollment, outbound brain presence, connection tickets, relay,
73-
end-to-end browser-to-brain encryption, and the shared renderer adapter remain
74-
planned; the current Hub cannot remotely control a brain yet.
67+
### Self-hosted Hub mode (encrypted relay preview implemented)
68+
69+
The separate `crewcode hub` process now provides durable local identity storage,
70+
first-owner passkey bootstrap, passkey sign-in, revocable browser sessions, machine
71+
enrollment/presence, short-lived one-shot connection tickets, a bounded outbound
72+
relay, and an end-to-end encrypted browser-to-Brain transport. The Hub dashboard can
73+
open the shared renderer for an online machine. Workspace, terminal, and agent RPC
74+
use the existing typed web-client adapter through the encrypted tunnel.
75+
76+
This is still a preview: recovery codes, live dashboard updates, persisted remote
77+
crash-durable execution custody, attachment tunneling, cross-device chat discovery,
78+
and durable bandwidth accounting remain incomplete. Per-connection frame and byte
79+
token buckets are enforced. Browser disconnect now detaches Brain-owned agents and
80+
terminals; a fresh encrypted connection explicitly reclaims known stable resource ids
81+
and replays only bounded observed events, never interrupted RPC requests or prompts.
82+
The browser discovers same-owner execution routes before the shared App mounts and
83+
buffers reclaimed events until chat subscribers are ready. If an earlier connection
84+
already consumed the detached event window, a completed execution can recover its
85+
latest assistant reply from the Brain-local conversation store over an owner-checked,
86+
agent-scoped encrypted RPC. The browser persists only the opaque chat/resource route
87+
needed to request that recovery across a full page close; it contains no credential
88+
or added authority. Recovery events use stable ids and are idempotent in chat.
89+
The Brain dashboard reports running/completed/blocked/failed/interrupted executions.
90+
This survives browser/network loss while the Brain process and its persistent Hub
91+
relay remain alive. A Brain/VPS restart still interrupts active execution and does
92+
not replay the unobserved prompt. After reconnect, CrewCode can recover the latest
93+
persisted assistant reply and an explicit new user prompt idempotently reasserts the
94+
stable bridge, creating a replacement provider process only when the Brain's
95+
process-local execution registry is gone.
7596

7697
A user runs one always-on **CrewCode Hub** on a Linux desktop, headless server,
7798
NAS, or other trusted host. The Hub serves the React application, local sign-in,
@@ -162,9 +183,11 @@ never evidence that a command or agent turn completed.
162183
1. The signed-in browser selects a machine.
163184
2. The Hub issues a very short-lived, single-use connection ticket bound to the
164185
local user, browser session, machine id, requested protocol, and random nonce.
165-
3. The browser and brain connect through the Hub relay. The brain validates the
166-
signed ticket and rejects expired, replayed, revoked, wrong-audience, or
167-
unauthorized-user tickets.
186+
3. The browser presents the opaque ticket once to the Hub relay. The Hub consumes
187+
it, revalidates machine ownership/revocation, and sends immutable user/session/
188+
scope claims over the machine-authenticated outbound channel. Expired, replayed,
189+
wrong-machine, offline, or revoked tickets are rejected. Tickets are memory-only,
190+
not self-contained bearer claims or durable signed tokens.
168191
4. The browser and brain perform an authenticated end-to-end handshake using the
169192
enrolled machine public key and a browser ephemeral key before privileged RPC is
170193
enabled.
@@ -268,10 +291,19 @@ AuditEvent(id, user_id?, machine_id?, browser_session_id?, type, created_at, met
268291
outbound heartbeat presence, dashboard status, and revocation are complete.
269292
Machine logout/credential rotation remain.**
270293
9. Implement the bounded Hub relay and a transport-neutral multiplexed tunnel with
271-
authenticated end-to-end browser-to-brain encryption.
294+
authenticated end-to-end browser-to-brain encryption. **Preview complete:**
295+
one-shot 60-second tickets, outbound authenticated WebSocket relay, P-256 ephemeral
296+
ECDH, enrolled Ed25519 Brain authentication, HKDF/AES-256-GCM ordered frames,
297+
30-minute idle and 8-hour absolute connection expiry, backpressure/frame bounds,
298+
per-connection frame/byte token buckets, and typed RPC/event multiplexing are
299+
implemented. Explicit fresh-ticket browser reconnect preserves UI state without
300+
replaying interrupted operations and reclaims known Brain-owned terminal/agent
301+
ids. Stable web bridge ids allow the same remote thread to reattach after a page
302+
reload. Cross-device thread discovery and Brain-process restart recovery remain.
272303
10. Replace the direct-only browser connection screen with local Hub sign-in,
273304
machine list/status, machine selection, reconnect, and revocation UI while
274-
retaining an explicit direct-pairing route.
305+
retaining an explicit direct-pairing route. **Initial machine selection and shared
306+
renderer launch are complete; automatic reconnect and live status remain.**
275307
11. Persist remote execution custody and test disconnect, restart, revocation,
276308
replay, cross-user isolation, relay compromise, and backpressure behavior.
277309
12. Move the desktop application onto the same backend contract.
@@ -316,16 +348,30 @@ crewcode brain
316348
Enrollment creates an Ed25519 machine identity plus a random bearer credential in
317349
`~/.crewcode/brain/hub-machine.json`, written with owner-only permissions. The Hub
318350
stores the public key and only a SHA-256 digest of the bearer secret. `crewcode brain`
319-
then makes outbound HTTPS heartbeat requests every 30 seconds; the dashboard marks a
320-
machine offline after 90 seconds without a successful heartbeat. Revoking it in the
321-
dashboard immediately rejects later heartbeats. Enrollment tokens are never written
351+
then maintains an authenticated outbound WebSocket relay and sends HTTPS heartbeats
352+
every 30 seconds; the dashboard marks a machine offline after 90 seconds without a
353+
successful heartbeat. Revoking it closes active relay sessions and rejects later
354+
heartbeats. Enrollment tokens are never written
322355
to the Hub database and are invalidated by Hub restart, expiry, first successful use,
323356
or a failed guess against their id.
324357

325-
This presence process does **not** accept commands, expose workspaces, start agents,
326-
or establish a relay. The Ed25519 key is reserved for the later signed-ticket and
327-
encrypted-relay stages; current heartbeat authentication uses the separate random
328-
machine bearer credential over HTTPS.
358+
Remote authority is disabled by default. Enable only explicit Brain-local roots and
359+
scopes, for example:
360+
361+
```bash
362+
crewcode brain \
363+
--workspace-root ~/developing \
364+
--allow-scope workspace:read \
365+
--allow-scope workspace:write \
366+
--allow-scope terminal \
367+
--allow-scope agent
368+
```
369+
370+
Hub sign-in and ticket scope requests cannot widen these grants. Every RPC method is
371+
classified again at the Brain and filesystem/PTY/agent operations retain registered-
372+
workspace enforcement. The enrolled Ed25519 identity signs each ephemeral P-256
373+
handshake; HKDF-derived AES-256-GCM keys encrypt ordered application frames so the Hub
374+
routes ciphertext rather than source, terminal, prompt, or response content.
329375

330376
Planned direct-auth and remaining Hub commands:
331377

@@ -342,10 +388,9 @@ The initial CLI distribution is implemented. From a checkout, run `npm run serve
342388
from a published package, run `npx crewcode@latest` or `crewcode serve`. It
343389
builds/serves the shared renderer, defaults to loopback, prints a single-use pairing
344390
URL, resolves installed provider CLIs without Electron, and shuts down cleanly on
345-
SIGINT/SIGTERM. The direct-auth CLI and remaining machine-management/relay commands above remain
346-
planned. Enrollment and dashboard revocation are implemented. `crewcode hub` has its
347-
own standalone setup/sign-in/machine-list screen; it does not yet mount the shared
348-
CrewCode workspace client.
391+
SIGINT/SIGTERM. The direct-auth CLI and remaining machine-management commands above
392+
remain planned. Enrollment, dashboard revocation, machine selection, and shared
393+
CrewCode workspace-client launch through the encrypted Hub relay are implemented.
349394

350395
## Current backend extraction
351396

@@ -359,6 +404,11 @@ are now Electron transport adapters for those operations. Native folder pickers,
359404
attachment handling, formatting, and destructive filesystem mutations remain in
360405
the Electron adapter until their browser API and validation contracts are added.
361406

407+
Hub-relayed attachment tunneling is not implemented. The browser can list the
408+
Brain-owned MCP registry and select entries by opaque id; `bridge.start` resolves
409+
those ids server-side and never accepts executable MCP command or environment
410+
definitions from the browser.
411+
362412
`PtyService` now owns process lifecycle independently of Electron. Both Electron
363413
IPC and the remote server adapt that service. Browser terminal creation is
364414
restricted to registered workspace roots, commands use authenticated HTTP RPC,
@@ -370,4 +420,19 @@ providers. The reusable service now persists provider resume IDs and normalized
370420
user/assistant transcript fallback, and exposes provider compaction. Complex
371421
cross-provider handoff summaries and every desktop-only surface still live in the
372422
Electron application; browser chat intentionally uses the same bridge contract
373-
without pretending unsupported desktop controls are available.
423+
without pretending unsupported desktop controls are available. Prompt acceptance is
424+
not treated as turn completion: the browser keeps the Stop control active until an
425+
authoritative terminal bridge event arrives. Provider model discovery uses the same
426+
authenticated RPC and keeps curated fallback choices visible while that asynchronous
427+
discovery is pending or unavailable. The GitHub sidebar can read Brain-local `gh`
428+
status, pull requests, workflow runs, and issues, and can create/merge/approve pull
429+
requests inside registered workspaces without exposing the Brain's GitHub token.
430+
Browser voice supports Brain-configured OpenAI/xAI realtime client secrets,
431+
dictation, and speech; permanent keys remain server-side, remote key mutation is
432+
denied, and remote audio is bounded to 8 MiB. Browser editor formatting is routed to
433+
workspace-local Prettier through the sandboxed filesystem service.
434+
435+
Delegation/Crew lifecycle transport, plugin iframe asset/capability routing,
436+
Brain-local voice sidecars, remote GitHub login/logout/repository publishing, file
437+
watch events, and language-server framing remain incomplete browser work. They must
438+
not be represented as enabled merely because the shared desktop UI mounts.

0 commit comments

Comments
 (0)