Skip to content

Commit cbd43fa

Browse files
matt2eclaude
andcommitted
refactor(desktop): report the access-policy relay write explicitly
`applyReusableAgentAccessPolicy` signalled "this hit the relay" by returning a different object than it was handed: a matching policy returned the caller's `agent`, a diverging one returned the fresh record from `updateManagedAgent`. `useMentionSendFlow` read that with `readyAgent !== agent` to decide whether an awaited relay round-trip separated its pre-side-effect mention-authorization pass from the publish, and therefore whether to revalidate at the publish boundary (#5681). The contract held today, and the safe failure direction (a gratuitous new object) only costs a redundant pass — but the unsafe direction is silent: a future in-place cache update that writes to the relay and returns the caller's object would skip the publish-boundary revalidation, and nothing pinned the convention. Make the signal load-bearing by construction. - `applyReusableAgentAccessPolicy` now returns `{ agent, wrote }` (`ApplyReusableAgentAccessPolicyResult`), with `wrote` set from whether `updateManagedAgent` actually ran rather than from anything about the returned record. Its doc comment names the send-path consumer so the flag is not mistaken for incidental. - The send path destructures `{ agent: readyAgent, wrote }` and sets `wroteRelayState` from `wrote`; the existing-member branch supplies `{ agent, wrote: false }`. Behaviour is identical — for the current implementation the two signals agree case for case. - `provisionChannelManagedAgent`'s two reuse branches destructure the agent out; they never consulted the identity signal. Three unit tests pin the contract in a new `channelAgents.accessPolicy.test.mjs`: a matching policy reports `wrote: false`, returns the input agent, and issues no command; a diverging policy reports `wrote: true` and invokes `update_managed_agent` with the resolved policy; and a write whose response is content-identical to the input still reports `wrote: true`, which is the case an identity or content comparison would miss. The repository file-size ratchet stays red on this branch for app_state.rs, agents.rs, managed_agents/runtime.rs and useMentionSendFlow.ts. All four were already over before this change; useMentionSendFlow.ts holds at its inherited 1077 lines here, so this commit adds nothing to the ratchet and does not split the pre-existing four. Verified: desktop tsc --noEmit, biome check over src + tests (exit 0), desktop unit tests (5810 tests, 5804 passed; the 5 failures are the pre-existing inboxReopenNavigation and useRetainedProjectGitViews loader failures, present on origin/main), and the full mentions (84) and channels + agent-access-warning (93) Playwright smoke suites against a pnpm build:e2e bundle. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent cff56e2 commit cbd43fa

3 files changed

Lines changed: 178 additions & 16 deletions

File tree

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import { applyReusableAgentAccessPolicy } from "./channelAgents.ts";
5+
6+
const AGENT_PUBKEY = "a".repeat(64);
7+
const ALLOWED_PUBKEY = "b".repeat(64);
8+
9+
// `wrote` is load-bearing: the message-send path (useMentionSendFlow) uses it
10+
// to decide whether an awaited relay round-trip separated its pre-side-effect
11+
// mention-authorization pass from the publish, and therefore whether it must
12+
// revalidate at the publish boundary (#5681). These tests pin the flag against
13+
// the relay write itself, not against the identity of the returned record.
14+
15+
function rawAgent(overrides = {}) {
16+
return {
17+
pubkey: AGENT_PUBKEY,
18+
name: "fizz",
19+
persona_id: null,
20+
relay_url: "wss://relay.example",
21+
acp_command: "buzz-acp",
22+
agent_command: "goose",
23+
agent_args: [],
24+
mcp_command: "",
25+
turn_timeout_seconds: 0,
26+
idle_timeout_seconds: 0,
27+
max_turn_duration_seconds: 0,
28+
parallelism: 1,
29+
system_prompt: null,
30+
model: null,
31+
status: "running",
32+
pid: null,
33+
created_at: "2026-01-15T00:00:00Z",
34+
updated_at: "2026-01-15T00:00:00Z",
35+
last_started_at: null,
36+
last_stopped_at: null,
37+
last_exit_code: null,
38+
last_error: null,
39+
log_path: null,
40+
start_on_app_launch: false,
41+
backend: { type: "local" },
42+
backend_agent_id: null,
43+
respond_to: "owner-only",
44+
respond_to_allowlist: [],
45+
...overrides,
46+
};
47+
}
48+
49+
function managedAgent(overrides = {}) {
50+
return {
51+
pubkey: AGENT_PUBKEY,
52+
name: "fizz",
53+
respondTo: "owner-only",
54+
respondToAllowlist: [],
55+
...overrides,
56+
};
57+
}
58+
59+
function installTauriInvoke(handler) {
60+
const prior = globalThis.window;
61+
globalThis.window ??= {};
62+
window.__TAURI_INTERNALS__ = { invoke: handler };
63+
return () => {
64+
globalThis.window = prior;
65+
};
66+
}
67+
68+
test("a matching access policy reports no write and returns the agent untouched", async (t) => {
69+
const calls = [];
70+
t.after(
71+
installTauriInvoke((command, args) => {
72+
calls.push([command, args]);
73+
return Promise.resolve(null);
74+
}),
75+
);
76+
77+
const agent = managedAgent();
78+
const result = await applyReusableAgentAccessPolicy(agent, {});
79+
80+
assert.equal(result.wrote, false);
81+
assert.equal(result.agent, agent);
82+
assert.deepEqual(calls, []);
83+
});
84+
85+
test("a diverging access policy reports the write and returns the updated agent", async (t) => {
86+
const calls = [];
87+
t.after(
88+
installTauriInvoke((command, args) => {
89+
calls.push([command, args]);
90+
return Promise.resolve({
91+
agent: rawAgent({
92+
respond_to: "allowlist",
93+
respond_to_allowlist: [ALLOWED_PUBKEY],
94+
}),
95+
profile_sync_error: null,
96+
});
97+
}),
98+
);
99+
100+
const agent = managedAgent();
101+
const result = await applyReusableAgentAccessPolicy(agent, {
102+
respondTo: "allowlist",
103+
respondToAllowlist: [ALLOWED_PUBKEY],
104+
});
105+
106+
assert.equal(result.wrote, true);
107+
assert.equal(result.agent.respondTo, "allowlist");
108+
assert.deepEqual(result.agent.respondToAllowlist, [ALLOWED_PUBKEY]);
109+
assert.deepEqual(calls, [
110+
[
111+
"update_managed_agent",
112+
{
113+
input: {
114+
pubkey: AGENT_PUBKEY,
115+
respondTo: "allowlist",
116+
respondToAllowlist: [ALLOWED_PUBKEY],
117+
},
118+
},
119+
],
120+
]);
121+
});
122+
123+
test("the write is reported even when the update hands back an unchanged record", async (t) => {
124+
// Callers must not re-derive the write by comparing the returned record
125+
// against the one they passed in — a backend that normalizes the policy
126+
// away, or a cache layer that mutates in place and hands the caller's own
127+
// object back, still wrote to the relay. Under such a comparison the send
128+
// path would silently skip the publish-boundary revalidation.
129+
let invoked = 0;
130+
t.after(
131+
installTauriInvoke(() => {
132+
invoked += 1;
133+
return Promise.resolve({
134+
agent: rawAgent(),
135+
profile_sync_error: null,
136+
});
137+
}),
138+
);
139+
140+
const agent = managedAgent();
141+
const result = await applyReusableAgentAccessPolicy(agent, {
142+
respondTo: "anyone",
143+
});
144+
145+
assert.equal(invoked, 1);
146+
assert.equal(result.wrote, true);
147+
assert.equal(result.agent.respondTo, agent.respondTo);
148+
assert.deepEqual(result.agent.respondToAllowlist, agent.respondToAllowlist);
149+
});

‎desktop/src/features/agents/channelAgents.ts‎

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -132,26 +132,39 @@ type ChannelAgentReuseContext = {
132132
>[];
133133
};
134134

135+
export type ApplyReusableAgentAccessPolicyResult = {
136+
agent: ManagedAgent;
137+
/**
138+
* True when reconciling the policy required a relay write. Callers that
139+
* sequence authorization around this call — the message-send path revalidates
140+
* mention authorization at the publish boundary whenever an awaited relay
141+
* round-trip separated it from its earlier pass — depend on this flag rather
142+
* than on comparing the returned record's identity against the input, so the
143+
* signal survives any future change to whether an update returns a fresh
144+
* object.
145+
*/
146+
wrote: boolean;
147+
};
148+
135149
export async function applyReusableAgentAccessPolicy(
136150
agent: ManagedAgent,
137151
request: Pick<CreateManagedAgentInput, "respondTo" | "respondToAllowlist">,
138152
persona?: Pick<AgentPersona, "respondTo" | "respondToAllowlist">,
139-
) {
153+
): Promise<ApplyReusableAgentAccessPolicyResult> {
140154
const policy = resolveReusableAgentAccessPolicy(request, persona);
141155
const matches =
142156
agent.respondTo === policy.respondTo &&
143157
agent.respondToAllowlist.length === policy.respondToAllowlist.length &&
144158
agent.respondToAllowlist.every(
145159
(pubkey, index) => pubkey === policy.respondToAllowlist[index],
146160
);
147-
if (matches) return agent;
148-
149-
return (
150-
await updateManagedAgent({
151-
pubkey: agent.pubkey,
152-
...policy,
153-
})
154-
).agent;
161+
if (matches) return { agent, wrote: false };
162+
163+
const { agent: updatedAgent } = await updateManagedAgent({
164+
pubkey: agent.pubkey,
165+
...policy,
166+
});
167+
return { agent: updatedAgent, wrote: true };
155168
}
156169

157170
export async function attachManagedAgentToChannel(
@@ -329,7 +342,7 @@ export async function provisionChannelManagedAgent(
329342
const definition = context.personas.find(
330343
(persona) => persona.id === input.personaId,
331344
);
332-
const updatedAgent = await applyReusableAgentAccessPolicy(
345+
const { agent: updatedAgent } = await applyReusableAgentAccessPolicy(
333346
reusable,
334347
input,
335348
definition,
@@ -358,7 +371,7 @@ export async function provisionChannelManagedAgent(
358371
context.channelMemberPubkeys,
359372
);
360373
if (reusable) {
361-
const updatedAgent = await applyReusableAgentAccessPolicy(
374+
const { agent: updatedAgent } = await applyReusableAgentAccessPolicy(
362375
reusable,
363376
input,
364377
);

‎desktop/src/features/messages/ui/useMentionSendFlow.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -179,16 +179,16 @@ export function useMentionSendFlow({
179179
const agent = managedAgentsByPubkey.get(pubkey);
180180
if (!agent) continue;
181181
try {
182-
const readyAgent = existingMembers.has(pubkey)
183-
? agent
182+
const { agent: readyAgent, wrote } = existingMembers.has(pubkey)
183+
? { agent, wrote: false }
184184
: await applyReusableAgentAccessPolicy(
185185
agent,
186186
{},
187187
personas.find((persona) => persona.id === agent.personaId),
188188
);
189-
if (readyAgent !== agent) {
190-
// A distinct record back means the access-policy update hit the
191-
// relay; a matching policy returns `agent` itself without writing.
189+
if (wrote) {
190+
// The access-policy reconciliation hit the relay; a matching
191+
// policy reports `wrote: false` and stays on the fast path.
192192
wroteRelayState = true;
193193
}
194194
if (participants.has(pubkey)) {

0 commit comments

Comments
 (0)