Repository navigation
feat(agent): enforce parent authority for delegated sessions - #6618
Conversation
Inherit the real caller's sandbox policy, preserve trusted message provenance, and delegate direct-child approvals with explicit human escalation in the parent conversation. Keep child sessions out of sidebar roots while retaining child browsing and source navigation. Generated-by: Maka
M4n5ter
left a comment
There was a problem hiding this comment.
Code & Test Review (English) — 4 blocking bugs / authority gaps (incl. CI failures), 5 cleanliness & UX issues, 2 test cleanups
Summary
The concurrency and provenance fundamentals in this PR are genuinely clean: the two-phase lock in Owner::respond_inner (plugins/agent/native/src/owner/interactions/delegation.rs:127-180) avoids holding runs.lock() across human waits while re-verifying permission_basis before commit, confirm_child_response (delegation.rs:364-374) uses tokio::select! to withdraw parent SessionApproval prompts cleanly if the child interaction settles first, temporal grant containment (Scope::Turn authorizing child Scope::Once only) is sound, and [Message source (Host-provided): ...] is projected at the model boundary without polluting persisted message text or digests.
However, 2 blocking regressions are currently failing 5 native CI shards, 2 authority/provenance gaps remain on sibling session Paths, and several type/projection choices leave unnecessary dead branches and hot-path overhead.
1. Blocking Bugs, CI Regressions & Authority Gaps
-
Owner::creation_permissionsbreaks cross-instanceWorkHub/Graphworker creation (fails 5nativeCI shards)Owner::creation_permissions(plugins/agent/native/src/owner.rs:713-725) inspectsscope.identity.agent()and callsself.scoped_store(scope, &invocation.session_id).await?.scoped_store(owner.rs:657) rejects!self.owns(id)withErr("agent_session_unavailable"). When aWorkHuborGraphcoordinator (wh_..., owned by the WorkHubOwnerinstance) creates a worker session on the ordinaryagentOwnerinstance (s_...),self.owns("wh_...")isfalse—causing every WorkHub/Graph worker dispatch to fail withagent_session_unavailable.- Fix: Resolve caller authority from shared
SessionStore/maka_agent_authoritywheninvocation.session_idbelongs to a sibling coordinator instance in the same profile store rather than rejecting viaself.owns(...).
-
Owner::respond_innerregresses missing/wrong-sessionrequest_idfrom domainRejectedinto untyped RPCErr(fails 2interactionsCI tests)- Previously,
commit_response_unlocked(plugins/agent/native/src/owner/interactions.rs:116-140) returnedOk(InteractionResult::Rejected { reason: InteractionRejection::Unavailable })whenrequest_iddid not belong toinput.session_id. respond_inner(plugins/agent/native/src/owner/interactions/delegation.rs:108-110) now callsself.interaction(&input.session_id, &input.request_id).await?up front, turning a missing or wrong-sessionrequest_idintoErr("agent_interaction_unavailable")(breakingnative_form_validates_original_fields_and_commits_before_resumingandnative_question_roundtrip_is_bound_owned_and_first_wins). The same raw?propagation exists inchild_answered(delegation.rs:371, 423-427).
- Previously,
-
Tool-ceiling inheritance (
tools) still trusts the workspace donor instead of the calling agent (authority bypass)Owner::create(plugins/agent/native/src/owner.rs:782-864),fork.rs:135-141, andimports.rs:352-369fixedpermissionsto inherit fromscope.identity.agent(), but lefttoolsreading fromWorkspaceSelection::Session(or defaulting toNone—unrestricted—forDirectory,Project, andIsolatedGit).- A tool-restricted non-Bot agent can spawn a
Directorychild session withtools: Noneand escalate out of its tool allowlist. Intersect or bound childtoolsby the real calling agent's live tool ceiling acrosscreate,fork, andimport.
-
SessionEditQueue(editQueue) lacks caller/ownership checks and mutates queued messages while preserving originalMessageOriginproducts/maka/bundle/src/installation.ts:241-245grantsSessionEditQueueto all agents,plugins/agent/native/src/service.rs:1039-1046andowner/queue/controls.rs:148enforce no caller ownership guard, andplatform/event-log/src/message_queue/edit.rs:94-112rewrites queued message text in-place while retainingentry.source.message.origin(Nonefor a human or anotherSession). A delegated child could rewrite a human's queued prompt in the parent session while keeping human provenance.- Audit sibling control endpoints consistently as well:
SessionChange(archive/delete),SessionUpdate,SessionStop(may_controlinnotifications.rs:106currently restricts onlyBot), andSessionResume.
2. Cleanliness, Type Modeling & UX Polish
- Merge
origindirectly intoRowDirectory::Userinstead of adding a Postcard compatibility variant (plugins/agent/facts/src/history/semantic/directory.rs:65-68, 101-106):RowDirectory::AttributedUserwas appended solely to preserve old Postcard layouts (// Append to preserve the Postcard layout of existing directory variants) and was also missed inevery_row_kind_preserves_positions_measures_and_independent_flags(codec/tests.rs:78-141). Internal semantic cache layouts do not carry backwards-compatibility guarantees—foldoriginintoRowDirectory::Userdirectly. - Model
SessionApprovalwith a closed narrow approval enum instead ofBox<InteractionAnswer>(plugins/agent/facts/src/interaction.rs:174-180): Only 4 allow decisions can ever be escalated (ServiceApproval(Allow),Permissions(Allow),ClientCapability(Allow),ComputerApp(Once|Session|Always)). Wrapping unrestrictedBox<InteractionAnswer>permits impossible states (Question,Form,Deny, nestedSessionApproval) in the schema and forced ~90 lines of unreachable UI branches and dead locale keys inSessionApprovalRequest.tsx:48-209andInteractionComposer.tsx:272-283.- Also note
delegation.rs:147, 174-178: when a human clicks Deny child decision,input.answerbecomesDeny(requiring zero parent authority), yet a concurrent parentpermission_basisedit still aborts withAuthorizationChangedand drops the human's denial.
- Also note
rootsOnly: truehides parked child interactions fromNeedsYouandneeds_you_count(products/maka/workbench/app/browsing.ts:95, 154,platform/event-log/src/sessions/catalog.rs:173-177, 234-241): BecauseSessionSendis asynchronous, a child session can park on a question or approval after its parent turn has already completed or stopped; filteringNeedsYoustrictly toparentSessionId IS NULLmakes those waiting child prompts invisible.- Avoid per-token full-row scans and permanent title caching in
createMessageSenders(Conversation.tsx:533-555,messageSenders.ts:43-67):Conversation.tsxsubscribes toprojection()(which ticks on every streaming model token / activity delta) and allocatesArray.from(projection().rowsById.values())on every tick even thoughoriginonly changes on user/queue rows;messageSenders.tsalso caches the one-shotobservetitle forever even if a child's auto-generated title arrives later. - Surface
Proposed child decisionabove the fold or gate approval on scroll (InteractionComposer.tsx:850, 904-938, 1109): PuttingRequested accessaboveProposed child decisioninside amaxHeight: 336scroll container clips the proposed grant scope (e.g.For this session) below the fold whileApprove child decisionis immediately clickable without scrolling. - Consistent human provenance header in mixed-origin turns (
plugins/agent/engine/src/executor.rs:171-175vsuser.rs:47-50): External executors formatorigin: Noneas[Message source (Host-provided): null]whereas native model turns omit the header for human messages.
3. Test Cleanliness
- Backend tests (
plugins/agent/native/src/owner/tests/session_parent_authority.rs,plugins/agent/engine/src/production_tests.rs): Clean, readable, behavioral, and 100% event-driven with zerosleeps. Please add coverage for: (a) cross-instanceWorkHub(wh_...) caller session creation, (b) humanDenyonSessionApproval(including across a concurrent parent permission change), and (c)ChildSettledprompt withdrawal. - Desktop GPUI test (
products/maka/desktop/tests/desktop_new_session.rs:1753-1959): Deterministic (no sleeps), but packs 5 distinct behaviors into one 207-line test in the serialized (-j 1) GPUI suite, seeds the child via rawstore.create_sessioninstead of exercisingSessionCreate, relies on hardcoded pixel scroll deltas (px(-500.0)) and coordinate assertions (bounds.left() >= px(768.0)), and unconditionally writes 4 PNG artifacts (desktop.artifact(...)) on every CI run.
4. Cross-PR Notes (with #6617)
- Merging alongside
#6617has textual conflicts inproducts/maka/bundle/src/installation.tsandpackages/plugin-sdk/src/contracts.ts(plus generated SDK contracts). - Two silent cross-PR hazards to watch when combining both branches:
desktop_new_session.rs:1795-1819in this PR passes"model": fixture.selectiontosendandSessionSend, which compiles cleanly against#6617and fails at runtime ('model' was unexpected).#6617'splugins/agent/native/src/executor/oar/history.rs:71-133formats prior turns withoutMessageOrigin, stripping this PR's sender provenance on OAR multi-turn handoff.
代码与测试评审(简体中文) — 4 项阻塞级 Bug / 权限缺口(含 CI 挂点根因)、5 项整洁度与交互细节问题、2 项测试建议
总体评价
这个 PR 的核心并发与溯源机制写得很漂亮:Owner::respond_inner(plugins/agent/native/src/owner/interactions/delegation.rs:127-180)采用两阶段锁,不在人工审批等待期间持锁,并在最终提交前重验 permission_basis 防住 TOCTOU;confirm_child_response(delegation.rs:364-374)利用 tokio::select! 在子会话交互提前结束时自动撤回父会话的 SessionApproval,不留孤儿审批框;时域授权包含关系(父 Scope::Turn 仅可批子 Scope::Once)清晰严谨;[Message source (Host-provided): ...] 仅在模型投影边界注入,不污染事件日志原文与摘要。
但目前存在 2 项直接导致远端 CI 5 个 native 分片挂掉的阻塞级回归、2 项同类路径未对齐的权限/溯源缺口,以及违反仓库无兼容分支 / 精确类型建模原则的冗余代码,建议一并收口。
1. 阻塞级 Bug、CI 挂点根因与权限缺口
-
Owner::creation_permissions误拒跨实例调用,打挂所有WorkHub/Graph子会话创建(CI 5 个native分片挂点)Owner::creation_permissions(plugins/agent/native/src/owner.rs:713-725)读取scope.identity.agent()后调用了self.scoped_store(scope, &invocation.session_id).await?。- 而
scoped_store(owner.rs:657)强校验if !self.owns(id)(只认s_前缀)。当WorkHub或Graph协调器(wh_...,由 WorkHubOwner实例持有)向普通agentOwner创建 worker 会话时,self.owns("wh_...")为false,全部报agent_session_unavailable失败。 - 建议:当调用方
invocation.session_id属于同一存储下的跨实例协调器会话时,直接从共享SessionStore读取其实时maka_agent_authority::permissions::live权限,不要被单实例self.owns拦截。
-
Owner::respond_inner将不存在/跨会话的request_id从领域Rejected退化为未类型化 RPC 错误(CIinteractions2 个测试挂点)- 原先
commit_response_unlocked(plugins/agent/native/src/owner/interactions.rs:116-140)在request_id不属于当前session_id时返回Ok(InteractionResult::Rejected { reason: InteractionRejection::Unavailable })。 - 现在
respond_inner(plugins/agent/native/src/owner/interactions/delegation.rs:108-110)提前调用self.interaction(&input.session_id, &input.request_id).await?,导致缺失或跨会话request_id直接抛Err("agent_interaction_unavailable")(打挂native_form_validates_original_fields_and_commits_before_resuming与native_question_roundtrip_is_bound_owned_and_first_wins)。同文件child_answered(delegation.rs:371, 423-427)也存在同样的?裸抛问题。
- 原先
-
只约束了
permissions,漏了同类的工具上限(tools)继承(权限绕过)Owner::create(plugins/agent/native/src/owner.rs:782-864)、fork.rs:135-141与imports.rs:352-369将permissions改成了继承真实调用方scope.identity.agent(),但tools仍然取自WorkspaceSelection::Session(若选Directory、Project或IsolatedGit则直接是tools: None全放开)。- 工具受限的非 Bot 子会话只需新建一个
Directory子会话,就能获得无限制的全量工具。应排查create/fork/import所有同类路径,用调用方的实时工具上限约束子会话tools。
-
SessionEditQueue(editQueue)缺少归属校验,可篡改排队消息并保留原MessageOriginproducts/maka/bundle/src/installation.ts:241-245对所有 Agent 开放了SessionEditQueue,但plugins/agent/native/src/service.rs:1039-1046与owner/queue/controls.rs:148无调用方身份/归属检查,且platform/event-log/src/message_queue/edit.rs:94-112在原地修改排队消息文本时保留了原entry.source.message.origin(人类None或其他会话身份)。子会话可借此改写父会话里人类排队的指令并冒充人类来源。- 建议同步排查同类控制接口对非 Bot 子会话的父/兄弟越权边界:
SessionChange(归档/删除)、SessionUpdate、SessionStop(notifications.rs:106的may_control目前只限制了Bot)以及SessionResume。
2. 代码整洁度、类型建模与交互细节
- 去掉 Postcard 兼容变体
RowDirectory::AttributedUser,直接合入RowDirectory::User(plugins/agent/facts/src/history/semantic/directory.rs:65-68, 101-106):专门追加变体保留旧 Postcard 布局既增加了双分支维护负担,还漏加进了codec/tests.rs:78-141的全变体往返测试。内部语义缓存格式无需保留兼容分支,直接将origin合入RowDirectory::User更干净。 - 用闭合的窄枚举替代
SessionApproval { answer: Box<InteractionAnswer> }(plugins/agent/facts/src/interaction.rs:174-180):实际只有 4 种放行动作会升级为父会话审批,直接包裹完整的Box<InteractionAnswer>让Question、Form、Deny、递归SessionApproval等非法状态在类型与 Schema 中均可表示,迫使SessionApprovalRequest.tsx:48-209和InteractionComposer.tsx:272-283多写了约 90 行永远走不到的防御分支与死翻译词条。- 另见
delegation.rs:147, 174-178:当人类点击 Deny child decision 后,input.answer已变为无需父授权的Deny,此时若父会话permission_basis恰好变动,仍会被误拒为AuthorizationChanged导致人类的拒绝被丢弃。
- 另见
rootsOnly: true会隐藏停靠待处理的子会话交互(products/maka/workbench/app/browsing.ts:95, 154、platform/event-log/src/sessions/catalog.rs:173-177, 234-241):由于SessionSend是异步的,子会话完全可能在父轮次结束后才停靠在提问或审批上;NeedsYou和待处理计数一刀切过滤parentSessionId IS NULL会导致用户漏看等待人工介入的子会话。- 避免
createMessageSenders在流式热路径上全量扫行并永久缓存初始标题(Conversation.tsx:533-555、messageSenders.ts:43-67):Conversation.tsx直接订阅projection()(模型流式输出每个 token 都会触发),每次都Array.from(projection().rowsById.values())全表扫描;且messageSenders.ts一次性缓存首次observe结果后,子会话后续自动生成的标题不会更新。 - 优化
SessionApproval滚动折叠体验(InteractionComposer.tsx:850, 904-938, 1109):当前将Requested access放在上方,导致关键的Proposed child decision(如子会话拟授予For this session)在336px限高容器内被折叠在首屏下方,而“批准”按钮无需滚到底即可直接点击。 - 对齐混合来源轮次中人类消息的溯源头格式(
plugins/agent/engine/src/executor.rs:171-175vsuser.rs:47-50):外部执行器将人类消息(origin: None)格式化为[Message source (Host-provided): null],而原生模型路径对人类消息不加头,建议统一。
3. 测试整洁度
- 后端测试(
plugins/agent/native/src/owner/tests/session_parent_authority.rs、plugins/agent/engine/src/production_tests.rs):非常整洁,纯行为驱动、零sleep。建议补充 3 个关键回归场景:(a) 跨实例WorkHub(wh_...)调用方创建子会话;(b) 人类在SessionApproval上点击Deny(含停靠期间父权限并发变更);(c) 子交互提前结算触发ChildSettled自动撤回。 - 桌面端 GPUI 测试(
products/maka/desktop/tests/desktop_new_session.rs:1753-1959):虽然没有sleep,但把 5 个独立行为塞进了串行(-j 1)套件的一个 207 行大测试里,用底层store.create_session绕过了真实SessionCreate,依赖硬编码像素滚轮(px(-500.0))和坐标断言(bounds.left() >= px(768.0)),且每次 CI 运行都会无条件向磁盘写出 4 张 PNG(desktop.artifact(...))。
4. 与 #6617 合入联动的互踩提醒
- 两边同时修改了
products/maka/bundle/src/installation.ts和packages/plugin-sdk/src/contracts.ts(含生成的 SDK 文件),存在合并冲突。 - 两处编译不报错但运行时/语义互踩的地方:
- 本 PR 在
desktop_new_session.rs:1795-1819新增的测试向send/SessionSend传了"model": fixture.selection,与#6617合并后编译能过、运行时直接报'model' was unexpected。 #6617的plugins/agent/native/src/executor/oar/history.rs:71-133跨后端拼接历史轮次时未携带MessageOrigin,会导致本 PR 的跨会话发送者身份溯源在切换到 OAR 续跑时静默丢失。
- 本 PR 在
Automated review generated by Antigravity.
Resolve real caller policy across Agent instances and durable coordinator dispatch, bound derived tool ceilings, and restrict queued message edits to their true author. Preserve typed interaction rejection and committed human denial, narrow escalation answers, and keep pending children discoverable without restoring them to normal sidebar roots. Add targeted authority, settlement, persistence and real desktop workflow regressions; preserve existing WorkHub task controls and explicit service-approval semantics rather than introducing a global session ACL. Generated-by: Maka
Complete the Browsing fixture with needsYouCount and resolve test clicks from button centers instead of flooring their top-left bounds outside the hit target. Generated-by: Maka
Summary
Review follow-up
Addressed in
3c92b6320:Unavailablerejection for missing/wrong-session interaction IDs; retain actual infrastructure errors.This does not add a global session-management ACL: existing WorkHub selected-worker task controls and explicitly human-approved service calls retain their established semantics. Cross-PR integration with #6617 remains separate while that PR is unmerged.
Security / review focus
Parent identity comes from trusted execution/native dispatch scope, never model-supplied metadata. Creation takes a policy snapshot, not an ongoing inheritance link. Delegated approval checks effective filesystem/network/service/client authority and grant duration, revalidates the parent permission basis before allowing, and settles or withdraws obsolete prompts against the original child request. System permission remains OS-owned; persistent application approval retains the existing human-only route.
Verification
3c92b6320: run 41786827194 exposed two terminal workspace-pagination test failures. Both were reproduced locally, then fixed in95f2d537e: complete theBrowsing.needsYouCountfixture contract and click button centers rather than flooring top-left bounds to a cell outside the button (the collapse target starts at y=218, while the old click landed at y=216). No production pagination changes, relaxed assertions, retries or timeout increases.terminal::ui::testsmodule passed locally: 21/21, including both original failures. Rustfmt, Biome format, ASF headers and diff checks passed.Screenshots
Updated from the actual Workbench on the review-fix branch using the GPUI/WGPU offscreen desktop renderer and an isolated real Host fixture. The model is mocked; SessionCreate, SessionSend, human confirmation and source navigation use the production paths. The child access request is seeded into its active invocation. No private user conversations are used.
Exact proposed approval is visible before the original request
Waiting children remain discoverable
Trusted sender opens beside the child
Child browser retains descendants
AI use
Tool(s) and scope: Maka assisted with design, implementation, targeted tests, UI fixture verification, review follow-up and PR preparation. Material AI-authored commits include
Generated-by: Maka.Checklist
Does this PR entail a change in behavior?