Skip to content

Commit 7f5e47e

Browse files
committed
feat: enhance delegation handling and placement enforcement
- Updated `buildDelegationPreamble` to improve isolation messaging and authority of owner placement choices. - Modified `useChatSessions` to include `checkoutPath` for better session management. - Enhanced `useComposerSend` to handle pending sends and cancellation more effectively. - Introduced `useDelegatedThreads` to enforce delegation placement rules, ensuring shared children respect owner choices. - Added `useDelegationPlacement` to manage session placement choices before sending requests. - Implemented new tests for delegation placement and compaction policies to ensure robust functionality. - Created shared utilities for handling chat artifact frames and image file validation. - Updated styles for better UI presentation of context usage details. - Adjusted Vitest configuration to include TypeScript files in test patterns.
1 parent 9d4d87c commit 7f5e47e

82 files changed

Lines changed: 2412 additions & 414 deletions

File tree

Some content is hidden

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

‎AGENTS.md‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,40 @@ Update corresponding Docs in [CrewCode Docs](/docs/), and [AGENTS.md](/AGENTS.md
2424

2525
## Agent Notes
2626

27+
Image files open read-only in Code Editor tabs; chat attachments and agent
28+
Markdown images/image links open the shared in-app viewer. Use the typed
29+
`fsReadDataUrl` boundary for workspace images, retaining the bounded local/SSH
30+
read path. Render SVG only as an inert image; never turn it into an active app
31+
document or persist image bytes in editor-session state. Keep generated-code
32+
artifact sandboxing separate. See `docs/image-viewer.md`.
33+
34+
Chat artifacts use the sandboxed Artifacts panel for HTML/SVG fences and supported
35+
workspace/HTTP links. Keep generated scripts in an opaque iframe without native
36+
capabilities; read files through the typed client and registered workspace root.
37+
Serve interactive previews through the dedicated artifact protocol/static web
38+
bootstrap with a response-header sandbox; never loosen renderer script CSP or
39+
send artifact HTML in HTTP queries. Keep the desktop, direct-web, and Hub policy aligned.
40+
Do not confuse SSH loopback with the client host. Codex MCP elicitations require
41+
real action/content responses and cancellation; never answer unknown server
42+
requests with empty success. Sandbox extensions remain explicit turn-scoped
43+
grants, including in Full Access. See `docs/chat-artifacts.md`.
44+
45+
Delegation first-send placement is an explicit CrewCode choice before provider
46+
dispatch. Honor the persisted owner isolation choice, pin shared checkout paths
47+
separately from isolated worktree metadata, and never checkout the parent to
48+
satisfy delegation. Cancel pending sends on Stop/session or checkout changes;
49+
recheck parent liveness and cohort after worktree creation, preserving interrupted
50+
results without launching workers. Stop during bridge startup must cancel prompt
51+
forwarding and stale-bridge retries, targeting only the exact late bridge id.
52+
See `docs/delegated-threads.md`.
53+
54+
Windows provider discovery must use the shared Windows executable candidates
55+
for desktop, Brain, and usage probes, including native .exe and npm .cmd/.bat
56+
launchers and per-user locations when the GUI PATH is stale. Never use Unix
57+
which/Bash probes on Windows. Local agent spawning must route batch launchers
58+
through the existing Windows spawn adapter; SSH resolves on the host. See
59+
`docs/getting-started.md`.
60+
2761
Mobile window tabs use the bottom workspace dock's Tabs button and an on-demand
2862
sheet; never reserve a top tab-strip row on phones. Preserve exact tab selection,
2963
observed activity, pinned-tab close protection, built-in/plugin new-tab actions,
@@ -50,6 +84,20 @@ aggregate result usage. Use SDK category `kind` and full detail for the
5084
measured Claude meter; summary detail is approximate. See
5185
`docs/context-usage-meter.md`.
5286

87+
The chat header Context action directly toggles the session context management
88+
sidebar, including through mobile Actions. Use the latest reported session usage,
89+
retain unknown/empty states and native-compaction invalidation, and group provider
90+
detail separately from category totals without adding overlapping counters.
91+
Token-log row icons use the shared icon set, stay decorative, and retain text
92+
labels and wrapping for nested details and compaction policy rows. Compact token
93+
values consistently with k/M suffixes while retaining exact counts on hover and
94+
for assistive text; do not abbreviate percentages or contributor item counts.
95+
Keep provider compaction policy separate from occupancy and prompt budget; expose
96+
only observed settings and explicit configured thresholds, otherwise unknown.
97+
Typed/picked /compact must use native provider operations, preserve sessions, and
98+
wait for native confirmation rather than treating an acknowledgement as completion.
99+
Never start a second automatic compactor or erase a fresh post-boundary reading.
100+
53101
The context popover stays compact. Its Token logs action opens the full
54102
provider breakdown in a scrollable right sidebar, including for crew chats;
55103
keep the row data out of the small popover. See `docs/context-usage-meter.md`.
@@ -133,6 +181,24 @@ answers are explicit failures, never empty answers, and provider-side resolution
133181
withdraws the card through the `RequestUserFn` abort signal. See
134182
`docs/agent-activity-overlay.md`.
135183

184+
Solo agent replies render Markdown as text streams and retain the same Markdown
185+
renderer at completion. Keep renderer component identities stable across deltas
186+
so code blocks and link actions do not remount on every update.
187+
188+
Solo chat keeps one Thinking log and one Work log per agent turn, including live
189+
interleaved events and restored history. Open Thinking during the active turn;
190+
keep the Work log closed by default but manually expandable. Collapse both on turn completion; completed history starts closed and remains manually
191+
expandable. Preserve manual disclosure during tool/reasoning pauses.
192+
Solo Work logs separate file-modifying calls from other tools into independent
193+
chevron sections with counts. Preserve source row identity and manual section
194+
disclosure during streaming; collapse sections at completion. Classify edits,
195+
writes, patches, and calls with observed file-change evidence as file calls;
196+
reads stay in other tools.
197+
Show the aggregated changed-file chips only after the turn ends, not while tools
198+
are running or between tool calls. Keep log headers free of bottom dividers and
199+
retain complete turn scope when paging.
200+
See `docs/tailwind-renderer.md`.
201+
136202
Thinking-log headers use the shared outlined thought-bubble icon; keep the
137203
streaming shimmer and separate disclosure chevron behavior intact.
138204
Turn Work Log headers use the shared outlined work-log icon alongside the

‎docs/chat-artifacts.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Chat artifacts and browser access
2+
3+
Agent replies expose **Open artifact** on HTML and SVG fenced code blocks.
4+
Supported workspace-file links and HTTP(S) links expose **Preview** beside the
5+
normal link. Preview opens the Artifacts panel while keeping the chat available.
6+
Image links open the in-app image viewer directly; other normal links retain
7+
their editor/in-app-browser behavior. HTTP previews also
8+
offer **Open in app browser**, since some sites refuse iframe embedding.
9+
10+
HTML/SVG previews run scripts in a sandboxed iframe with an opaque origin, no
11+
Electron bridge, no same-origin allowance, no popups, and no top navigation.
12+
They can load network resources; opening a preview runs its supplied code.
13+
Interactive content loads through a dedicated preview document, served by the
14+
desktop `crewcode-artifact:` protocol or the web/Hub `/crewcode-artifact-frame`
15+
route. Its response enforces `sandbox allow-scripts` without same-origin access;
16+
it permits artifact scripts without widening the trusted renderer's script CSP.
17+
The app's frame policy permits these previews and HTTP(S) pages. Artifact content
18+
travels only in the URL fragment, never an HTTP request body/query or server log.
19+
The preview endpoint is public static bootstrap code with no workspace access.
20+
Workspace files are read through the typed CrewCode client and existing
21+
registered-root checks, including SSH. Text/HTML previews are limited to 2 MB.
22+
HTML must be self-contained or use absolute network URLs: relative workspace
23+
dependencies are not served by the panel. Markdown/text files display as source;
24+
Image files use the shared viewer with Fit, Actual size, zoom, dimensions, and
25+
Reload, including SVG as an inert image. Image reads support local and SSH
26+
workspaces up to 25 MB. See [In-app image viewing](image-viewer.md).
27+
JSX requires a running build/dev server.
28+
Previews are ephemeral and do not create another copy of the artifact.
29+
30+
For SSH workspaces, loopback HTTP previews require explicit port forwarding:
31+
`127.0.0.1` in the desktop/browser refers to the client computer, not the remote
32+
workspace host. The panel explains this rather than loading the wrong machine.
33+
34+
Codex browser automation is separate from this panel and the Electron browser.
35+
The app-server bridge handles `mcpServer/elicitation/request` using MCP's
36+
`action`/`content` response. Full Access automatically accepts consent-only forms;
37+
forms requesting data and URL-based authentication remain interactive. Structured
38+
form data is entered as a JSON object using the existing request card; malformed
39+
JSON is an explicit error. MCP/provider validation remains authoritative.
40+
Stop, process exit, and provider-side request resolution withdraw pending cards.
41+
Both numeric and string server request ids retain their exact identity.
42+
Unknown server requests return an explicit unsupported-method error rather than
43+
an empty success object that a tool might interpret as user denial.
44+
45+
Codex `item/permissions/requestApproval` displays the exact requested sandbox
46+
extension and grants it only after an observed acceptance, for the current turn.
47+
Ask/Plan/read-only sessions cannot grant those extensions. Full Access retains
48+
the existing workspace-write sandbox and dangerous-command tripwire. A prompt
49+
claiming full access cannot remove an OS sandbox; `spawn EPERM` still requires
50+
examining the provider's actual execution environment. External browser services
51+
can also enforce gates CrewCode does not control. This feature does not install
52+
an automation backend or prove a browser automation request succeeded.

‎docs/context-usage-meter.md‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,26 @@ The chat meter divides the latest observed context occupancy by the active
44
context window. The numerator is the provider's current prompt/context size,
55
not cumulative billing tokens for the entire conversation.
66

7+
The chat header **Context** button opens the session context management sidebar
8+
directly (also available in the mobile Actions menu). Close it with the close
9+
button, backdrop, or Escape; switching sessions closes the panel. It follows the
10+
newest reported usage snapshot, including cleared occupancy after compaction,
11+
and stays available before the first reading with an explicit empty state.
12+
Opening the panel makes no extra provider requests; the Codex policy read below
13+
happens once at bridge startup.
14+
15+
Token-log rows use decorative icons from the shared icon set beside their text
16+
labels, including nested contributors and compaction policy rows. Token values
17+
use compact k/M suffixes throughout the sidebar; hover or assistive text retains
18+
the exact count. Percentages and contributor item counts retain their own units.
19+
20+
The panel shows reported occupancy, a usage bar, category token counts and
21+
percentages of the full window. Expand MCP tools, system tools/prompt, memory
22+
files, agents, skills, message details, attachments, and provider diagnostics when
23+
reported. Detail rows and billing counters never become additive occupancy;
24+
reserved/headroom/deferred rows have no active percentage. Providers without
25+
categories show observed token counters and explain the missing breakdown.
26+
727
Clicking the context pill opens a compact usage summary. When the provider
828
supplies token details, **Token logs** opens a scrollable right sidebar. The
929
sidebar can be closed with its close button, the backdrop, or Escape. Claude
@@ -89,6 +109,39 @@ The latest usage snapshot is persisted for resumed chats. A new provider
89109
report replaces its window; occupancy normalization and compaction handling
90110
are described in [Conversation storage](conversation-storage.md).
91111

112+
## Provider compaction policy and /compact
113+
114+
The sidebar separates the provider's compaction policy from occupancy and prompt
115+
budget. Codex reads its effective workspace configuration through a bounded,
116+
read-only app-server config/read request at bridge creation. An explicit positive
117+
model_auto_compact_token_limit is labeled as a configured threshold; its counting
118+
scope is shown as full context or growth after the compacted prefix. An unset
119+
model default, an unsupported read, or a timeout stays unknown. The sidebar does
120+
not derive a compaction trigger from the prompt budget or a warning percentage.
121+
Configuration evidence is a startup snapshot, not a live countdown.
122+
123+
Claude exposes the resolved autoCompactEnabled value used by the bridge. Its SDK
124+
does not currently supply a numeric trigger through this integration. CrewCoder
125+
owns its persisted autoCompact policy; its current ACP usage contract does not
126+
report a numeric trigger or enabled setting. Both show unknown fields explicitly.
127+
The latest matching provider compaction event supplies manual/automatic status,
128+
including started, completed, failed/interrupted, or an explicitly inferred drop.
129+
CrewCode does not introduce a second automatic compactor.
130+
131+
Typed and picked /compact commands use the same native provider path on desktop
132+
and Brain/browser: Codex thread/compact/start, Claude /compact through the SDK,
133+
and CrewCoder's advertised session/compact extension. These paths preserve the
134+
provider session instead of replacing it with a separate CrewCode summary.
135+
Codex waits for the native boundary, not the RPC acknowledgement. Claude requires
136+
a compact_boundary before reporting success. Stop during startup cancels dispatch
137+
and retry; concurrent turns/compaction are refused. A Codex manual-operation
138+
completion timeout fails and stops the owned process, without retrying or claiming
139+
success. Existing unsupported/fallback behavior remains for older providers.
140+
141+
Successful native boundaries invalidate old occupancy. A fresh post-boundary
142+
reading is retained even if it arrives before the manual RPC returns. Policy
143+
metadata survives renderer occupancy invalidation; no zero usage is fabricated.
144+
92145
## Automatic compaction
93146

94147
Claude's `compact_boundary`, Codex app-server's `contextCompaction` completion,

‎docs/current-state.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Current state
22

3+
Chat image attachments, agent Markdown images/image links, and Code Editor image
4+
files open in the app with fit, zoom, actual size, dimensions, and reload. Image
5+
editor tabs are read-only; desktop/web/Hub use the typed workspace client and SSH
6+
uses SFTP binary reads. See [In-app image viewing](image-viewer.md).
7+
38
Desktop system-tray behavior is opt-in through **Settings → General → Keep running in background**. Enabling it creates an OS tray with explicit **Open CrewCode** and **Quit CrewCode** actions; closing the window hides it without stopping terminals or agents, while tray Quit follows the normal cleanup path. Windows and Linux also restore on tray click (Linux StatusNotifierItem Activate is typically a single click). Disabling the preference removes the tray immediately. macOS retains its Dock icon, and web/Hub/headless runtimes never emulate the tray. See `docs/system-tray.md`.
49

510
Real agent integration is wired through normalized bridges (pi, OpenCode, Claude, Codex, Hermes, CrewCoder, Ollama, and OpenRouter) with PTY panes remaining available for terminals.
@@ -186,7 +191,7 @@ Inactive standalone terminal tabs remain mounted for PTY/process continuity, but
186191

187192
Idle refreshes follow the same responsiveness contract. The five-second prompt/skill/command scan is App-owned, so unchanged content must preserve the prior library object and slow scans must stay single-flight; local scan reads use asynchronous filesystem APIs rather than blocking Electron main. The automatic GitHub poll must use asynchronous, bounded child processes and preserve the prior App state for an unchanged result. Never add `spawnSync`, `readdirSync`, `statSync`, or `readFileSync` to an interval-, focus-, or visibility-driven status path. See `docs/terminal-stream-performance.md`.
188193

189-
Structural message updates (tool calls and new thinking blocks) must stay isolated from the workspace shell. `Messages`' `areRowsEqual` compares a work-log anchor's actual source `ToolCallMessage` identities; never replace that with blanket live-turn invalidation, because a growing thinking/text sibling would rebuild every work log in the turn. Agent rows receive a precomputed `showTurnSummary` boolean instead of reading the whole transcript. Self-contained rows — `thinking` above all — re-render only when their own message changes. `chronologicalStreamSegments` caches splits per chunk string, so a growing block only re-splits its tail instead of every chunk on every flush (that was quadratic in turn length); it also appends units in a loop rather than `push(...units)`, which throws on very long blocks. Solo-chat auto-follow runs in the next animation frame, not `useLayoutEffect`: reading `scrollHeight` synchronously during every React commit forced shell-wide layout. Keep `.thread-shell` layout/paint-contained so transcript reflow cannot invalidate the workspace drawer.
194+
Structural message updates (tool calls and new thinking blocks) must stay isolated from the workspace shell. `Messages`' `areRowsEqual` compares a work-log anchor's actual source `ToolCallMessage` identities; never replace that with blanket live-turn invalidation, because a growing thinking/text sibling would rebuild every work log in the turn. Agent rows receive a precomputed `showTurnSummary` boolean instead of reading the whole transcript. Self-contained rows re-render only when their own message changes. Solo chat aggregates thinking and tools separately per turn; grouped anchors compare source identities so only changes to their own log invalidate them. Solo Thinking logs start open during active turns while Work logs start closed and remain manually expandable; both collapse at observed turn completion, and load closed in completed history while remaining manually expandable, without header dividers; history paging retains complete visible turns. `chronologicalStreamSegments` caches splits per chunk string, so a growing block only re-splits its tail instead of every chunk on every flush (that was quadratic in turn length); it also appends units in a loop rather than `push(...units)`, which throws on very long blocks. Solo-chat auto-follow runs in the next animation frame, not `useLayoutEffect`: reading `scrollHeight` synchronously during every React commit forced shell-wide layout. Keep `.thread-shell` layout/paint-contained so transcript reflow cannot invalidate the workspace drawer.
190195

191196
`ChatPane` is still not `React.memo`'d, but that is now a cost/benefit call rather than a correctness trap: `MessageRow` is already memoized and `Messages` pages at 50 rows, so an App-driven ChatPane re-render is cheap reconciliation. Memoize only against a profile, never against a theory.
192197

‎docs/delegated-threads.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,28 @@ This is distinct from Crew Surface. Crew lanes are ephemeral, live in one tab, a
88
exist for the duration of a crew run. Delegated threads are ordinary `Session`s with
99
transcripts, archiving, and drawer rows — they outlive the turn that made them.
1010

11+
## First-send placement choice
12+
13+
With Delegate enabled, the first user send pauses at a CrewCode choice card before
14+
any provider prompt is sent. Choose **Isolated worktree from the displayed branch**
15+
or **Current checkout**, which shows its exact path. The choice is stored on the
16+
session and applies to every new child regardless of the agent's isolation request.
17+
A different parent checkout or branch requires another choice. For the main checkout
18+
this means an isolated branch from committed main, or workers sharing main's files.
19+
Origin is a Git remote, not an executable checkout; CrewCode never implicitly fetches,
20+
switches branches, or copies uncommitted changes to satisfy this choice.
21+
22+
Cancel, Stop, toggling delegation off, switching sessions/checkouts, or unmounting
23+
withdraws the pending send and preserves the draft. Stop also cancels a pending
24+
provider startup, stops its exact late bridge id, and prevents missing-bridge retries
25+
from forwarding the prompt after interruption. Choosing placement does not
26+
create a worktree itself. If the parent stops while an actual worktree creation is
27+
in flight, the result is preserved for inspection and no child starts. The handler
28+
rechecks parent liveness, choice, and turn cohort after creation. Shared children
29+
persist their checkout path separately from isolated-worktree/branch metadata;
30+
worker follow-ups and foreground chat sends use that path rather than whichever
31+
checkout happens to be selected later. SSH delegation remains explicitly unavailable.
32+
1133
## Contract
1234

1335
- Delegation is **off by default**, enabled per session.

0 commit comments

Comments
 (0)